String Builder
April 30, 2017
Categorised in: Java Core
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 currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.