Java Tutorial Series - Playing with Strings

Strings are the most important topic when learning Java. We will be dealing with different operations on Strings in this article, will get to know what StringBuilder class does, StringBuffer class, the difference between the two and string formatting actions.

A String is immutable, which means once it is created, it cannot be changed.

StringBuilder Class in Java- 

Let's see an example on how to use append method for StringBuilder -

StringBuilder sb = new StringBuilder() ;
sb.append("This is testing blog");
sb.append(" ");
sb.append("We are learning about Strings here");

System.out.println(sb.toString());

Difference between StringBuilder and StringBuffer - 

Ever wondered why Java provide 2 different classes with similar functionality.
  • StringBuffer is thread safer version of StringBuilder. It is used in multi threaded version.
  • StringBuilder is light in weight because it is not thread safe.

String Formatting - 

\n - used for new line
\t - to provide ample space
printf() - for fomatted strings
print() - prints in a single line
println() - prints a line and then jumps to another line.
%d - for Integers
%s - for Strings
%f - for flaot

Example -
System.out.printf("Total cost : %d", 5);
System.out.printf("Total cost : %d,  Quantity : %d ", 5, 22);
System.out.printf("Total value : %.2f\n", 5.6);     // %.2f - will have 2 decimal places

Rounding off applies in float digits.


Comments

Popular posts from this blog

Azure Tutorials Series - Azure Networking

Coforge Interview Questions | Automation Testing profile

Testing in CI/CD