Please disable adblock to view this page.

← Go home

String Builder

java-display

April 30, 2017
Published By : Pratik Kataria
Categorised in:

Why String Builder?

public class StringBuild {
	public static void main( String[] args ){
		String str1 = "Hi";
		String str2 = "There";
		String str3 = str1 + ", " +str2 + "!";

	}
}
  • The above code introduces 3 different string objects.
  • This leads to unnecessary memory consumption due to the multiple object creation.
  • At such point you should use StringBuilder
  • public class StringBuild {
    	public static void main( String[] args ){
    		String str1 = "Hi";
    		String str2 = "There";
    		String str3 = str1 + ", " +str2 + "!";
    
    		StringBuilder sb = new StringBuilder("Hi");
    		sb.append(", ");
    		sb.append("There");
    		sb.append("!");
    
    		System.out.println(sb);
    
    	}
    }

    Output: Hi, There!

  • This way there is only one object creation.
  • Here, the append returns a reference to the StringBuilder object.
  • Code Optimization:

    		StringBuilder sb = new StringBuilder("Hi")
    		.append(", ")
    		.append("There")
    		.append("!");

     

Using Scanner

import java.util.Scanner;
public class StringBuild {
	public static void main( String[] args ){
		String str1 = "Hi";
		String str2 = "There";
		String str3 = str1 + ", " +str2 + "!";

		StringBuilder sb = new StringBuilder("Hi")
		.append(", ")
		.append("There")
		.append("!");

		System.out.println(sb);

		Scanner sn = new Scanner(System.in);
		System.out.println("Enter a String");
		String ip = sn.nextLine();  //nextLine waits for user to type in something and press enter

		System.out.println(ip);

	}
}

 

Using StringBuilder and Scanner

import java.util.Scanner;
public class StringBuild {
	public static void main( String[] args ){
		String str1 = "Hi";
		String str2 = "There";
		String str3 = str1 + ", " +str2 + "!";

		StringBuilder sb = new StringBuilder("Hi")
		.append(", ")
		.append("There")
		.append("!");

		System.out.println(sb);

		Scanner sn = new Scanner(System.in);
		System.out.println("Enter a String");
		String ip = sn.nextLine();  //nextLine waits for user to type in something and press enter

		System.out.println(ip);

		//First deleting contents of sb.
		sb.delete(0, sb.length()); //delete(starting position, ending position)

		for(int i = 0; i < 3; i++) {
			ip = sn.nextLine();
			sb.append(ip + "\n");
		}

		System.out.println(sb);

	}
}

Output

  • Hi, There!
  • Enter a String
  • A value
  • A value
  • Hello
  • World
  • !
  • Hello
  • World
  • !

 

Pratik Kataria is a budding programmer, web designer and developer.