Java String

In this article, we’ll talk about one of the most important classes in Java, the String class.

1. What Is String in Java?

A Java String is basically an array of characters. Additionally, all Strings are immutable so you cannot really change the value of a String, the only way to “change” it, is to assign another string reference to a variable that points to a String.

Time to see how to initialize a String in Java:

String clh = "Code Learn Hub is the best programming Website";

And that’s it, the variable clh now holds the value “Code Learn Hub is the best programming Website”. Also, note that in order to initialize a String you do not have to invoke a constructor using the new keyword.

2. How to Find the Length of a String in Java?

To get the length of strings in Java, you just have to call the method length() of the String class as shown below:

String clh = "Code Learn Hub";
System.out.println(clh.length());

Since the spaces count as characters, this will print 14.

3. How to Split a String in Java?

In many cases, you might have to extract items from a String and then insert it into an array.

This could be done by using the 2 split methods that the String class of Java provides us.

3.1 String[] split(String regex)

This method will split the string based on the regex you provided and return an array of strings with the items you want and with the regex match excluded.

Let’s see how would that work in an example:

String namesString = "Georgios,Nikolaos,Ioannis,Dimitris";
String[] namesArray  = namesString.split(",");
for(String name : namesArray)
    System.out.println(name);

Here we want to split the namesString based on “,“. The result that will be printed is

Georgios
Nikolaos
Ioannis
Dimitris

But what if we wanted to use a regex?

String countriesString = "Greece3USA6UK9";
String[] countriesArray  = countriesString.split("[0-9]");
for(String country : countriesArray)
    System.out.println(country);

In the example above, we wanted to split the countries based on whether a number between 0 and 9 exists between them. Therefore, we pass the regex [0-9] as a parameter and this will print

Greece
USA
UK

An important note here is that you need to be careful and escape special regex characters such as . ? * [ as the result will not be the expected.

For example, this will print nothing.

String countriesString = "Greece.USA.UK";
String[] countriesArray  = countriesString.split(".");
for(String country : countriesArray)
     System.out.println(country);

In order to remedy this, we have to change Line 2 as shown below:

String[] countriesArray  = countriesString.split("\\.");

3.2 String[] split(String regex, int limit)

The difference with the previous method is that you can specify how many times the split will be done; for example, let’s say we want to split the string "Code;Learn;Hub;is;the;Best" in 3 parts, the first will be "Code", the second "Learn" and the third "Hub;is;the;Best.

String clh = "Code;Learn;Hub;is;the;Best";
String[] clhSplitted = clh.split(";", 3);
for(String word : clhSplitted)
    System.out.println(word);

This will print:

Code
Learn
Hub;is;the;Best

If we choose a number less than or equal to zero as the limit, the limit will be ignored and the result will be the same as with the split(String regex).

String clh = "Code;Learn;Hub;is;the;Best";
String[] clhSplitted = clh.split(";", -2);
for(String word : clhSplitted)
    System.out.println(word);

This will print:

Code
Learn
Hub
is
the
Best

4. How to Compare Strings in Java

4.1 Difference Between Equals() And ==

To compare one string with another in Java, the proper way, you first have to know what the String pool is.

When you initialize a string like in the previous sections, the string is stored in a string pool. If you initialize another string variable but it has the same value, you won’t trigger the initialization of a new String. To better understand this, let’s say we run the following 3 lines:

String clh = "Code Learn Hub";
String clhother = "Code Learn Hub";
String clhNew  = new String("Code Learn Hub");

What really happens here is the following:

String pool vs Heap
Figure 1 – String pool vs Heap
  • 1st command is executed: A string "Code Learn Hub" is inserted into the string pool. The variable clh points to that string.
  • 2nd command is executed: The variable clhother points to string “Code Learn Hub”
  • 3rd command is executed: String pool’s “Code Learn Hub” cannot be used in that case. This command will trigger the creation of a new String in the heap memory.

But why should you care about that?

4.2 Comparing With == Operator

Let’s try to compare the strings initialized above using either the == operator or the equals() method of String in Java and see what happens:

String clh = "Code Learn Hub";
String clhother = "Code Learn Hub";
String clhNew  = new String("Code Learn Hub");

System.out.println("clh == clhother? "+(clh == clhother));
System.out.println("clh == clhNew? "+(clh == clhNew));

Line 5: We compare whether these 2 strings point to the same object, so this will print true.

Line 6: This will print false since these 2 variables even though they have the same value, the == operator does not care about that, it just checks if the variables point to the same object.

As a result, you should never compare (as in, compare the strings’ characters to determine whether they’re equal) strings using the == operator. The proper way to compare 2 strings is to use the equals method.

4.3 Comparing With equals() Method

On the other hand, if we compare the following two lines of code with the equals() method, the output will be true, as the value of the strings will be compared.

System.out.println("clh.equals(clhother)? "+(clh.equals(clhother)));
System.out.println("clh.equals(clhNew)? "+(clh.equals(clhNew)));

An important note here is that you should always check if the string whose equals method you will call is null (e.g. if clh was null we would get NPE), in order to avoid the fearful NullPointerException.

Other methods that might be of interest to you are the following:

  • equalsIgnoreCase(String anotherString): This will print true if two strings are equal without taking the case into account (It will print true for “Hello” and “HELLo”, “HelLo” and “HELLO” etc.).
  • contentEquals(StringBuffer sb): This method will call the contentEquals(CharSequence cs) internally and it is the same as equals().
  • contentEquals(CharSequence cs): This will have the same result as equals().

4.4 compareTo and compareToIgnoreCase Μethods

There is a way to compare strings lexicographically and that is the compareTo() and compareToIgnoreCase(). Note that in contradiction with equals() and equalsIgnoreCase() is that they return an int number.

Now let’s see how compareTo works:

  • If the two strings have the same length:
    • For each character of each string, calculate the difference between the two Unicode values:
      • Should the characters have the same value, proceed with the next one. If this is the last character, return 0
      • Should the characters have different value, return the difference between them.
  • If the two strings have different length, e.g. String a has length 5 and String b has length 8 :
    • For the first 5 characters of each string:
      • If the characters have the same value, proceed with the next one.
      • If the characters have different value, return the difference between them
    • After comparing at most 5 characters we have these 2 cases:
      • A different character was found, so the difference between the Unicode values was returned.
      • The first 5 characters of the two strings are the same. In that case, the value to be returned will be the difference between the total characters of the first and the second string(In that case 5 – 8 = -3).

This means the following:

  • If String a is “bigger” than b, it will return a positive number.
  • Should String a is equal to b it will return 0.
  • If String a is “smaller” than b, it will return a negative number.

On the other hand, when it comes to compareToIgnoreCase(), two characters will be compared in a case insensitive manner(This means that ‘A’ will be taken as having the same Unicode value as ‘a’).

Let’s see how this work with an example:

String clhMisspelled = "Code Learn Hab";
String clh = "Code Learn Hub";
String clhUpperCase = clh.toUpperCase();
String clhMixedCase = "CodE LeaRn HUb";
int codePointAtClh = clh.codePointAt(clh.length()-2);
int codePointAtClhMisspelled = clhMisspelled.codePointAt(clhMisspelled.length()-2);

System.out.println("Codepoint value of \"Code Learn Hub\" first different character: "
        + codePointAtClh);
System.out.println("Codepoint value of \"Code Learn Hab\" first different character: "
        + codePointAtClhMisspelled);
System.out.println("Difference between them: "
        + String.valueOf(codePointAtClh-codePointAtClhMisspelled));
System.out.println("\"Code Learn Hab\".compareTo(\"Code Learn Hab\") will return: "
        + clh.compareTo(clhMisspelled));

System.out.println();

System.out.println("\"Code Learn Hub\".compareTo(\"CODE LEARN HUB\") will return: "
        + clh.compareTo(clhUpperCase));
System.out.println("\"Code Learn Hub\".compareToIgnoreCase(\"CODE LEARN HUB\") will return: "
        + clh.compareToIgnoreCase(clhUpperCase));
System.out.println("\"Code Learn Hub\".compareToIgnoreCase(\"CodE LeaRn HUb\") will return: "
        + clh.compareToIgnoreCase(clhMixedCase));
  • Lines 5-6: We calculate the Unicode value of the first character that is different between the two Strings (that is the ‘a’)
  • Lines 12-13: We print the difference between the two Unicode values
  • Line 14-15: We print the result of clh.compareTo(clhMisspelled) which is the same as the result in line 9

The output will be the following:

Codepoint value of "Code Learn Hub" first different character: 117
Codepoint value of "Code Learn Hab" first different character: 97
Difference between them: 20
"Code Learn Hab".compareTo("Code Learn Hab") will return: 20

"Code Learn Hub".compareTo("CODE LEARN HUB") will return: 32
"Code Learn Hub".compareToIgnoreCase("CODE LEARN HUB") will return: 0
"Code Learn Hub".compareToIgnoreCase("CodE LeaRn HUb") will return: 0

5. String Conversions

In this section, we’ll take a look at how we can convert string to another type or the reverse.

5.1 How to Convert Int to String in Java

There are two ways to cast int to String in Java. The first one is calling the method String.valueOf(int number) or call the method Integer.toString(int number).

The first one internally will call the second so you can just call the Integer.toString() instead of String.valueOf().

String a = String.valueOf(5);
String b = Integer.toString(15);

5.2 How to convert string to int in Java

The logic is the same as when you wanted to convert a string to an int in Java. However, unlike in the previous example in which we wouldn’t be able to compile the program if the parameter wasn’t an int, when working with strings we must use try-catch blocks in case the string parameter isn’t an integer. If we do not add try-catch blocks and the string is not of the expected type, a java.lang.NumberFormatException will be produced.

The two methods that you need in this case are Integer.valueOf(String number) and Integer.parseInt(String number). As before, the first will call the second internally.

Let’s see an example:

// Parsing numbers
int a = Integer.parseInt("5");
int b = Integer.valueOf("10");
//This works
int c = Integer.parseInt("05");
// All parsings after this comment will produce NumberFormatException
try {
    int d = Integer.parseInt("05.2");
}
catch (NumberFormatException e){
    e.printStackTrace();
}

try {
    int d = Integer.parseInt("5.2s");
}
catch (NumberFormatException e){
    e.printStackTrace();
}
try {
    int d = Integer.parseInt("Hello");
}
catch (NumberFormatException e){
    e.printStackTrace();
}

As we can observe from the above, we won’t have any problem parsing leading zeros, but the other parsings will fail.

5.3. Table of string-primitive and primitive-string conversions

In this section, we will create a table of conversions from any primitive to string and from any string to primitive.

5.3.1 Primitives to string

Conversion descriptionCommand
int to StringString number = Integer.toString(int i)
short to StringString number = Short.toString(short s)
byte to StringString number = Byte.toString(byte b)
long to StringString number = Long.toString(long l)
float to StringString number = Float.toString(float f)
double to StringString number = Double.toString(float d)
char to StringString character = Character.toString(char c)
boolean to StringString bool = Boolean.toString(boolean b)
Figure 1. Primitives to String conversions

5.3.2 String to primitives

Conversion descriptionCommand
String to intint number = Integer.parseInt(String s)
String to shortshort number = Short.parseShort(String s)
String to bytebyte number = Byte.parseByte(String s)
String to longlong number = Long.parseLong(String s)
String to floatfloat number = Float.parseFloat(String s)
String to doubledouble number = Double.parseDouble(String s)
String to charchar character = Character.parseCharacter(String s)
String to booleanboolean bool = Boolean.parseBoolean(String s)
Figure 2. String to Primitives conversions

As it has been already mentioned, these types of conversions are dangerous and they might produce exceptions. I suggest that you surround them with try-catch blocks.

5.4 Convert string to char array in Java

You might need to convert a string to a char array in order to use methods of the Arrays class. The easiest way to perform this conversion is to use toCharArray() method of String class. Then you will be able to call methods such as Arrays.sort() or Array.binarySearch(char[] a, char key).

Below you can find a simple example of a string to char array in Java and then converting the array back to the string after sorting it:

String clh = "CodeLearnHub";
char[] array = clh.toCharArray();
//sort the string
Arrays.sort(array);
StringBuilder builder = new StringBuilder();
for (char c : array)
    builder.append(c);
clh = builder.toString();
System.out.println(clh);

This will print CHLabdeenoru.

StringBuilder is a class that is used for string concatenation in Java, so after the creation of the builder, we append every character to it and then we call the toString() method in order to convert it back to a string.

6. String manipulation with Java String replace methods

In this section, we’ll answer the question of “how to replace characters in a string in Java”.

6.1 replace(Character oldChar, Character newChar) and replace(CharSequence old, CharSequence new)

The String class in Java provides two methods if you do not need to replace a string by using regex. Let’s see how they work in the example below:

String clh  = "Code Learn Hub";
clh =  clh.replace('e', 'a');
System.out.println(clh);

String hello = "Hello world and Hello world";
hello = hello.replace("Hello", "Bye");
System.out.println(hello);

The output of the above will be:

Coda Laarn Hub
Bye world and Bye world

As you can observe, the replacement is done to every occurrence of the character or String. Additionally, if you want to replace characters or strings based on regex matching, these two methods won’t work for you.

6.2 replaceAll(String regex, String replacement) and replaceFirst(String regex, String replacement)

The difference with the previous methods is that you can use regular expressions with these two methods. Let’s see how they work in an example:

String clh  = "Code 7Learn4 Hub9";
clh = clh.replaceAll("[0-9]", "5");
System.out.println(clh);

String hello = "Hello15 world and Hello world50";
hello = hello.replaceFirst("\\d+", "100");
System.out.println(hello);

This will output:

Code 5Learn5 Hub5
Hello100 world and Hello world50

As you can observe, with replaceAll(), when regex [0-9] is matched (this matches any single-digit number), all of the occurrences matched will be replaced. On the other hand, with replaceFirst(), when regex \\d is matched(this matches any number), only the first match will be replaced and the rest will be ignored.

7. How to concatenate Strings in Java

There are multiple ways to concatenate a string in java, we’ll go through three of them.

7.1 String concatenation in Java with StringBuilder class

You can concatenate strings by using the StringBuilder class as shown below:

String code = "Code";
String learn = "Learn";
String hub = "Hub";
StringBuilder sb = new StringBuilder();
String clh = sb.append(code).append(learn).append(hub).toString();
System.out.println(clh);

This will print CodeLearnHub.

As you can observe, this is the most elegant and clean way to concatenate Strings as it uses the Builder Design pattern and allows you to chain methods. Also, you can append any type of primitive or even an object

7.2 String concatenation with method concat of String class

String concat method can only accept strings as a parameter so it has a limitation when compared with StringBuilder

Below you can find an example:

String code = "Code";
String learn = "Learn";
String hub = "Hub";
System.out.println(code.concat(learn).concat(hub));

7.3 String concatenation using + operator

The simplest way to concatenate strings is to add the strings together as shown below:

String code = "Code";
String learn = "Learn";
String hub = "Hub";
System.out.println(code + learn + hub);

This way of concatenating string does not have type limitations as you can add anything as you would in StringBuilder. However, you might want to choose wisely when it comes to StringBuilder vs + operator as the performance of + operator could be much worse than that of StringBuilder.

8. Conclusion

After reading this article, you should be able to take full advantage of the powerful String class that Java provides. You can find the source code of the examples on our GitHub page.

9. Sources

[1]: String – Oracle