Advertisement
MrDoyle

20) String Builder and String Formatting

Feb 10th, 2021
1,516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. public class Main {
  2.  
  3.     public static void main(String[] args) {
  4.  
  5.         //inefficient as it creates a new string location in memory each time you "add" to the original
  6.         String info = "";
  7.  
  8.         info += "My name is Bob.";
  9.         info += " ";
  10.         info += "I am a builder.";
  11.  
  12.         System.out.println(info);
  13.  
  14.  
  15.         //more efficient, as it edits the original rather than creating new instances of the variable
  16.         StringBuilder sb = new StringBuilder("");
  17.  
  18.         sb.append("My name is Sue.");
  19.         sb.append(" ");
  20.         sb.append("I am a lion tamer.");
  21.  
  22.         System.out.println((sb.toString()));
  23.  
  24.  
  25.         StringBuilder s = new StringBuilder();
  26.  
  27.         s.append("My name is Rodger.")
  28.         .append(" ")
  29.         .append("I am a skydiver.");
  30.  
  31.         System.out.println((s.toString()));
  32.  
  33.         // Formatting ///
  34.         System.out.println("Here is some text.\tThat was a tab.\nThat was a new line.");
  35.  
  36.         //formatting characters allow more control
  37.         System.out.printf("Total cost %-10d; quantity is %d\n", 5, 120);
  38.  
  39.         for(int i=0; i<20; i++){
  40.             System.out.printf("%-2d: %s\n", i, "Here is some text");
  41.         }
  42.  
  43.         //formatting floating point values
  44.         System.out.printf("Total value: %.2f\n", 5.68784);
  45.         System.out.printf("Total value: %10.2f\n", 343.47649);
  46.        
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement