No announcement

Building Strings

Strings are immutable in nature i.e., you cannot change the content of a string.

For example:- String message = “Hello World”; here the variable message is currently referring to a string “Hello world”. You can make the variable message to refer to another string say “How are you?”, by setting message = “How are you?”. Once you do that, the variable will now refer to the new string in the String pool., i.e., new memory allocation.

What if you want to modify the existing? Well in that case Java provides us StringBuilder class to build strings.


package com.codingnous.tutorial;

public class BuildingStringsDemo {

	public static void main(String[] args) {

		// Declare string builder object.
		StringBuilder phrase = new StringBuilder();

		// Append string.
		phrase.append("A quick brown fox ");
		// Print the string.

		// Append more.
		phrase.append("jumps over the little lazy dog.");
		// Print the string.

A quick brown fox A quick brown fox jumps over the little lazy dog.

Every time you want to add something, use the append method.