String class
In Java, String is not implemented as character arrays as in other programming languages. Instead string is implemented as instance of String class. Strings are constants/ immutable and their values cannot be changed after they are created. If any operations that results in the string being altered are performed a new instance of String object is created and returned. This approach is done for implementation efficient by Java. It is recommended to use StringBuffer or StringBuilder when many changes need to be performed on the String. StringBuffer is like a String but can be modified. StringBuffer is thread safe and all the methods are synchronized. StringBuilder is equivalent to StringBuffer and is for use by single thread. Since the methods are not synchronized it is faster.String pools
Whenever we talks about String in Java it is necessary to understand the concept of String pools. When String objects are created using the new() they get created on the Heap. When String objects are created using literal assignments they go to a string pool. Significance of using literal assignments is that if an object already exists in the pool with the same literal, instead of creating a new object the previously created object gets returned. String object supports an intern() method which can be used to move to the pool.public static void main(String[] args) { String literal1 = "Hello"; String object1 = new String("Hello").intern(); String object2 = new String("Hello"); if ( literal1 == object1 ) System.out.println("They are same."); else System.out.println("They are different."); if ( literal1 == object2 ) System.out.println("They are same"); else System.out.println("They are different."); }Output:-
They are same. They are different.
Difference between == and .equals()
- == tests if two String objects references are same.
- .equals() tests if the String values are same.
Examples of using String
Reverse a string in Java
String inputStr = "This is a Java tutorial"; String reversedStr = new StringBuffer(inputStr).reverse().toString();
Split a string in Java using whitespace
String inputStr = "This is a Java tutorial"; String[] arr = inputStr.split("\\s+");
String to int conversion in Java
int i = Integer.parseInt("1000");
int to String conversion in Java
String valueStr= String.valueOf(1000);
String to char array in Java
String inputStr = "This is a Java tutorial"; char[] arr = inputStr.toCharArray();
String to Date conversion in Java
String myDateStr = "Jul 6, 2014"; SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy"); Date myDate = null; try { myDate = dateFormat.parse(myDateStr); } catch (ParseException e) { e.printStackTrace(); } System.out.println(myDate.toString());
0 comments:
Post a Comment