Some notes about String in Java Java 11.10.2013

StringBuffer vs StringBuilder

String is immutable and final in Java and every modification in String result creates a new String object. Immutability offers two main benefit. First, hashcode value can be cached which makes it a faster hashmap key and one of the reason why String is a popular key in HashMap. Second, because String is final it can be safely shared between multiple threads without any extra synchronization.

If you want mutable string you should use StringBuffer (available from Java 5 onwards). StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 is available similar class called StringBuilder which is a copy of StringBuffer but without synchronization.

StringBuilder str = new StringBuilder("Hello");
str.append(" world!");

Empty string

String in Java is considered empty if its not null and it’s length is zero.

Here are three ways to check empty string:

1) Checking if String is empty by using String.length()

if(string != null && string.length() == 0){ return true; }

2) Find if string is empty by using equals() method of String

return "".equals(name);

3) Checking if string is empty by using isEmpty() method String (available from Java 6 onwards)

input3.isEmpty()

Reverse string

Reverse string using Stringbuffer

String reverseStr = new StringBuffer(str).reverse().toString();

Converting

To integer

int i = Integer.parseInt("123");

To string

// from integer
String s = String.valueOf(123);
String s = String.format ("%d", 123);

// from date
Date dateNow = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
String dateString = dateFormat.format(dateNow);

// from double
Double d = 3.14;
String s = String.valueOf(d);

To date

String someDate = "11.10.2013";
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date theDate = (Date) dateFormat.parse(someDate);

To double

String s = "3.14";
Double d = new Double(s);
Double d = Double.valueOf(s);

Replace string

Replace character sequence in String

String oldString = "Hello!";
String newString = oldString.replace("Hello", "Bye");

Replace all matched pattern in String

String oldString = "Hello!";
String newString = oldString.replaceAll("^H", "B");

Split string

String names = "John,Alis,Mary,Pamela";
String[] splits = names.split(",");

Cut string

String s = "The very same Munchhausen.";
String ss = s.substring(0, 2);

Search string

String class provides convenient method to see if a sub-string or a pattern exists in String object. You can use indexOf() which will return position of character or String, if that exist in current String object or -1 if character doesn't exists in String. lastIndexOf is similar but it searches from end. String.match(String regex) is even more powerful, which allows you to search for a regular expression pattern inside String.

String s = "The very same Munchhausen.";
if(s.indexOf("Munchhausen") != -1){
    System.out.println("String contains Munchhausen at index :" + s.indexOf("Munchhausen"));
}

if(s.matches("M.*")){
     System.out.println("String starts with M");
}

Why is String immutable in Java?

The exact reason for this is best known to the people who created the String class. But here are some probable reasons. You may also read this as advantages of String immutability.

String Constant Pool. Strings are created in a special memory area in java heap known as "String Intern pool".

While you create a new String variable (without using the String constructor, see note below), it searches the pool to check whether is it already exist. If it is exist, then return reference of the existing String object. If String is not immutable, changing the String with one reference will lead to wrong value for the other references.

Java can have a string pool because strings are immutable.

Note: Using String() constructor or any other String function like substring(), concat(), replace() etc which internally uses String() constructor always create new string constant in the pool unless we call the method intern().

Security. String is widely used as parameter for many java classes, e.g. to obtain network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed and could lead to security issues.

Concurrency. Strings are implicitly thread safe because of immutability. Therefore, Strings can be shared across various different threads without the need of synchronization.

Caching. Since Strings are immutable, they can be cached and perform better compared to mutable counterparts. This is the reason why Strings are preferred as keys in hashmaps.

In a HashMap, being immutable guarantees that hashcode will always the same, so that it can be cached without worrying the changes.

Class loading. String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).