Short overview of how String objects can be used in Java
Size: 137.18 KB
Language: en
Added: Jul 11, 2024
Slides: 16 pages
Slide Content
Java Strings Using Strings in practice
Java String Character sequence Immutable Class defined in the java.lang package Instantiate a String Object: Using a String literal ( series of characters enclosed in double quotes ) String s1 = “ Cat ”; Via the String constructor ( see API for different constructors ) String s2 = new String (“ Cat ”);
Java String – Memory Output of the following code?
Java String – Memory Output of the following code? s1 == s2 : true s1 == s3 : false
Java String – Memory Java Memory Heap as a Java Object String s2 = new String (“ Cat ”); String pool in the Java Memory Heap String interning Flyweight pattern String s1 = “ Cat ”;
Java String – API Extends java.lang.Object E.g.: equals (other: Object) : boolean , hashCode () : int , … Implements: Serializable, CharSequence , Comparable<String> E.g.: compareTo (other: String) : int , charAt (index: int ) : char, … String specific API E.g.: isEmpty () : boolean , …
StringBuilder Mutable
StringBuffer Mutable Thread-safe Slower
Java String – Formatting String.format Conversion specifiers : %d ( decimal integer), %f ( floating point), %c ( any character ), … Many more options ( see documentation ) String fs; fs = String.format (" Variable 1 (%f) is of type float, while " + " the 2nd variable (%d) is an integer, " + " and the 3rd one, %s, is a string... ", floatVar , intVar , stringVar ); Formatter class ( java.util ) StringBuilder sbuf = new StringBuilder (); Formatter fmt = new Formatter ( sbuf ); fmt. format (" PI = % f%n ", Math .PI ); System .out. print ( sbuf. toString ()); // you can continue to append data to sbuf here.
Use cases – Instantiation Benchmarking: String Object: new ( with various constructors ), literal StringBuffer constructor (s) StringBuilder constructor (s)