Skip to content

Instantly share code, notes, and snippets.

@tamboer
Created December 16, 2017 11:37
Show Gist options
  • Select an option

  • Save tamboer/252860d0c0f0a28bfc9377d712cf2f92 to your computer and use it in GitHub Desktop.

Select an option

Save tamboer/252860d0c0f0a28bfc9377d712cf2f92 to your computer and use it in GitHub Desktop.
Java Strings

String bulider and string formatting

?Every time you are putting a plus between two strings you are creating a new string.

In Java strings are immutable, once you create a string you can never change it. It looks like you changed it , but it's not true. You are creating a new string, you are not appending to the existing string.

StringBuilder

Use StringBuilder class instead. StringBuilder appends new content, it does not create a new string builder object which is more efficient. -light weight because it's not thread safe.

StringBuffer

-thread safe version of StringBuilder.

Advanced String formatting

-tab and a new line System.out.println("Here is some text \t that was tab \n and this is a new line");

  • Embedding special formatting characters 10 cahracters wide on left %10d

    10 characters wide on right %-10d

Useful formatting

-floating point formatter

System.out.println("Total value is : %f \n" , 5.6);

Get two decimal places only

  • display 5.64 only and round off
  • Note this rounds off System.out.println("Total value is : %.2f \n" , 5.634534534);

10 here means how many characters to use before decimal point -This will create extra space -Put - to have left align System.out.println("Total value is : %.2f \n" , 5.634534534);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment