Java – String

Java – String

This post will cover the following topics in this article

  • Concatenation
  • Performance comparison
  • String Join
  • Substring
  • String Immutable
  • String Pool and equality
  • String compareTo

Concatenation

Plus operator, when 2 string are use with plus operator, string will be combine. Java optimised the performance with concatenate string with plus sign (+). However it does not apply in a loop. This mean that within the looping, it’s is not optimised for the performance. Same goes with String.format by repeating take time parsing and formatting the string.

String gretting = "Hello " + "World!";
## Output ##
Hello World!

When either side is string and numeric, it will combine as string .

String output = "Ocean " + 11;
## Output ##
Ocean 11

When string concatenate with numbers math operations, it need to bracket in math operations to avoid unwanted result.

String output = "Ocean " + 5 + 6; 
## Output ##
Ocean 56

If we expect Ocean 11, it need to include bracket (5+6)

String output = "Ocean " + (5 + 6); 
## Output ##
Ocean 56

String.concat(string)

String class provides a function to concat the string. The performance is slightly better than using + plus join string.

String s1 = "Hello";
String s2 = " World";
String output = s1.concat(s2);
System.out.println(output);  

## Output ##
Hello World

Performance Comparison

Below is a simple program to compare with 2 methods. The result show StringBuilder is more effective compare to + sign.

package com.codeomitted;

import java.time.Duration;
import java.time.Instant;

public class StringConcatenationTest {

  public static void main(String[] args) {
    condatenatePlus();
    condatenateStringBuilder();
  }
	
  public static void condatenateStringBuilder() {
    StringBuilder sb = new StringBuilder();
    Instant start = Instant.now();
    for(int i = 0; i < Character.MAX_VALUE; i++) {
      char c = (char)i;
      sb.append(c);
    }
    Instant finish = Instant.now();
    long timeElapsed = Duration.between(start, finish).toMillis();
    System.out.println(timeElapsed);
  }
	
  public static void condatenatePlus() {
    String output = "";
    Instant start = Instant.now();
    for(int i = 0; i < Character.MAX_VALUE; i++) {
      char c = (char)i;
      output += c;
    }
		
    Instant finish = Instant.now();
    long timeElapsed = Duration.between(start, finish).toMillis();
    System.out.println(timeElapsed);
  }

  public static void concat() {
    String output = "";
    Instant start = Instant.now();
    for(int i = 0; i < Character.MAX_VALUE; i++) {
      char c = (char)i;
      output = output.concat(String.valueOf(c));
    }
		
    Instant finish = Instant.now();
    long timeElapsed = Duration.between(start, finish).toMillis();
    System.out.println("concat: " + timeElapsed);
  }
}

## Output ##
condatenatePlus: 2087
condatenateStringBuilder: 8
concat: 671

String.Join

If we’d like to join String from several strings like first name, middle name, last name or in names array, we can use String.join. First supply argument is separator, and second argument is strings or string array.

public static void main(String[] args) {
		
  String firstname = "Vincent";
  String middlename = "Van";
  String lastname = "Gogh";
		
  String names = String.join("_", firstname, middlename, lastname);
  System.out.println("Name : " + names);
		
  String[] dbNames = {"Vincent", "Van", "Gogh"};
  String fullname = String.join(" ", dbNames);
  System.out.println("Name : " + fullname);
}

## Output ##
Name : Vincent_Van_Gogh
Name : Vincent Van Gogh

Substring

If you’d like to extract a word from a sentence, you can use Java.substring. The easier way to remember 2 argument is include and exclude index.

substring( include index, exclude index)

Eg: “This is hello world”.substring(8, 13);
* Beginning index, inclusive.
* Ending index, exclusive.

To extract the word “hello”, the first index position start from 0 to ‘h’ is 8 (include h) and subsequent end with space position 13 (exclude).

String sentence = "Java is not lorem ipsum";
String java = sentence.substring(0,4);
System.out.println(java);
		
String lorem = sentence.substring(12,17);
System.out.println(lorem);

Substring always return empty string when the first and second arguments are the same index

String asb = "Hello World";
System.out.println(asb.substring(3, 3));

When first index is greater than second argument, or second argument is out of range, StringIndexOutOfBoundsException: will get throw

String asb = "Hello World";
System.out.println(asb.substring(4, 3));

String Immutability

String class, once you create it cannot be change. To prove that, try run the following code.

public static void main(String[] args) {
  String abc = "abc";
  System.out.println("hashcode (abc): " + System.identityHashCode(abc));
		
  abc = "cde";
  System.out.println("hashcode (abc): " + System.identityHashCode(abc));
}

## Output ##
hashcode (abc): 1297685781
hashcode (abc): 1705929636

String Pool and Equality

When string created in double quote “”, java will check from the string pool if found then return the reference, otherwise it create string object then return the reference.

public static void main(String[] args) {
  String s1 = "Hello";
  String s2 = "Hello";
  String s3 = "He" + "llo";
  String s4 = new String("Hello"); // new object create new reference
  String s5 = "He".concat("llo");  //concat method return new String object. thus return new reference
  
  System.out.println("s1 = s2 " + (s1 == s2)); // true
  System.out.println("s1 = s3 " + (s1 == s3)); // true
  System.out.println("s1 = s4 " + (s1 == s4)); // false
  System.out.println("s1 = s5 " + (s1 == s5)); // false

  System.out.println("s1 = " + System.identityHashCode(s1));
		System.out.println("s2 = " + 
  System.identityHashCode(s2));
		System.out.println("s3 = " + 
  System.identityHashCode(s3));
		System.out.println("s4 = " + 
  System.identityHashCode(s4));
		System.out.println("s5 = " + 
  System.identityHashCode(s5));

  ## Output ##
s1 = 1297685781
s2 = 1297685781
s3 = 1297685781
s4 = 1705929636
s5 = 1221555852

CompareTo

To compare 2 string of their sequence one of another, we can use s1.compareTo(s2). If first comes before second return positive value else return negative value. If both string are same return zero.

System.out.println(“A”.compareTo(“B”));

## show negative value
public static void main(String[] args) {
  String first = "John";
  String second = "Micheal";
		
  int result = first.compareTo(second); // expect John , Micheal = negative
		
  System.out.println(result);
		
  if ( 0 > result) {
    System.out.println("John > Micheal");
  } else if ( 0 < result){
    System.out.println("Micheal > John");
  } else {
    System.out.println("Equal string");
  }
}		

The other way to compare 2 string is to use Collator class, it has better performance when compare to multiple string.

Collator c = Collator.getInstance();
if ( c.compare("John", "Micheal") < 0 ) {
   System.out.println("John, Micheal");
} else if ( c.compare("John", "John") == 0 ) {
   System.out.println("John, John");
} else {
   System.out.println("Micheal, John");
}

Write a Reply or Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.