Skip to content

String

One of the most used data in any program is a text. Java offers String class to represent textual data and its associated methods for text processing.   Having a solid understanding on Java string makes you a efficient and better programmer.

In this code note, we will cover following topics:

  • Into to String
  • Creating String
  • String Methods



› Into to String

String is a textual data representation in Java programming language.   It is essentially a sequence of characters grouped in char array.  If we have a String data "Hello" in your Java code, it would look something like this under the hood.

Where each of the characters are stored in char array and accessible via its indexes.  The String data type makes it simpler for us to work with text data unlike other programming languages where you have to work with char array to represent any text data.

Text data in java is referred as String object, which is essentially a data package that contains text data as well as its convenient processing methods.

If you create a String like this

String state = "Texus";

Here is how this String data or rather String object looks like internally:



› Creating String

In Java, you can create String object in two different ways, by String literal or by the new keyword. Both way results in String object creation and its just matter of style and preference.

Syntax for String literal:

String fact = "java is awsome!";

Syntax for new keyword:

String fact = new String("java is awsome!");

Only difference between them is that if you create a String data using the literal syntax, it will add the created String data to the String Pool for re-usage to reduce the memory usage. For example if you have the following code:

1
2
3
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");

s1 and s2 will points to the same String object, meanwhile the s3 points to its own String object. This can be visually expressed as follows.

The Java's motivation behind the String Pool is that, String object is immutable object, where its data value ( text content ) is not modifiable after it was created.

Immutable Object

In computer science, an immutable object is an object ( data package ) whose data value cannot be modified after it is created. Generally most of the modern programming language represent text data object as immutable object for security benefits and memory effectivnenss.

It turns out whenever you are concatenating a String, you were essentially creating a brand-new String object instead of changing the existing one.

For example take a look at the following example:

1
2
3
4
5
6
7
String name = "alphaleaf";
// concatenate
name += " java training";  
System.out.println(name); 

// --- OUTPUT --- //
alphaleaf java training

This simple concatenation of String results in new String object being created as follows:

concatenation example

The String object "alphaleaf" will be destryoed and new String object "alphaleaf java training" will be creted.



› String Methods

Let's explore some important String methods that you would use in your day-to-day test automation development and also in your coding interviews.

Important String methods

We will cover following String methods. Each method is presented with one example, please make sure of the example and run it yourself.

String methods Returns Usage details
length() integer returns the number of letters in a String
indexOf(text) integer returns the index of given text if it exists, else returns -1
isEmpty() boolean returns true if the string has zero character
contains(text) boolean checks if the String contains input text
equals(text) boolean checks if the String is equal to input text
equalsIgnoreCase(text) boolean checks if the String is equal to input text ignoring cases
startsWith(text) boolean checks if the String starts with input text
endsWith(text) boolean checks if the String ends with input text
toLowerCase() String creates and returns all lowercase String based on the current String.
toUpperCase() String creates and returns all uppercase String based on the current String.
toCharArray() char[] returns char array representation of the current String
charAt(index) char returns a character at the given index number
substring(s, e) String returns a sub String from given index range
replace(o, n) String returns a new String with replacements
split(text) String[] returns a array of String that contains splits of original String
split(text) String[] returns a array of String that contains splits of original String
compareTo(text) integer compares two String, 0 if equal, -1 if smaller, 1 if bigger
String.valueOf(input) String Converts the given different data type value to String data
concat(text) String Concatenates the given text data to the current String

length

This method will return an integer that represent the number of characters in given String.

1
2
3
4
5
6
7
8
// index         01234567890
String phrase = "Hello there";

int size = phrase.length();
System.out.println("Number of chars: " + size);

//===OUTPUT====
Number of chars: 11

indexOf

This method will return an integer that represents the index of given letter or word's start index in the String.

// index         01234567890
String phrase = "Hello there";

int idx_r = phrase.indexOf("r");
int idx_there = phrase.indexOf("there");

System.out.println("Index of r: " + idx_r);
System.out.println("Index of there: " + idx_there);

//===OUTPUT====
Index of r: 9
Index of there: 6

isEmpty

This method will return true boolean value if the String object invoking this message is empty, otherwise it will return false.

// index         01234567890
String phrase = "Hello there";
String space  = "";

boolean r1 = phrase.isEmpty();
boolean r2 = space.isEmpty();

System.out.println("phrase is empty?: " + r1);
System.out.println("space is empty? : " + r2);

//===OUTPUT====
phrase is empty?: false
space is empty? : true

contains

Given the input text, this method return true if the input text exist partially in the current String. Otherwise, it will return false.

// index         01234567890
String phrase = "Hello there";

boolean r1 = phrase.contains("ello");
boolean r2 = phrase.contains("there");
boolean r3 = phrase.contains("xyz");

System.out.println(r1);
System.out.println(r2);
System.out.println(r3);

//===OUTPUT====
true
true
false

equals

Given the input text, this method return 'true' if the input text is 100% equals to the current String that invoked this method.

// index         01234567890
String phrase = "Hello there";

boolean r1 = phrase.equals("hello there"); //false
boolean r2 = phrase.equals("HELLO THERE"); //false
boolean r3 = phrase.equals("Hello there"); //true

System.out.println(r1);
System.out.println(r2);
System.out.println(r3);

//===OUTPUT====
false
false
true

equalsIgnoreCase

Given the input text, this method return true if the input text is same without factoring the lower or upper-casing. This method is known as context equality.

// index         01234567890
String phrase = "Hello there";

boolean r1 = phrase.equalsIgnoreCase("hello there"); //true
boolean r2 = phrase.equalsIgnoreCase("HELLO THERE"); //true
boolean r3 = phrase.equalsIgnoreCase("Hello there"); //true

System.out.println(r1);
System.out.println(r2);
System.out.println(r3);

//===OUTPUT====
true
true
true

startsWith

Given the input text, this method return true if the current String starts with input text. Otherwise, it will return false. Note that this method is case-sensitive. Lowercase and uppercase matters.

// index         01234567890
String phrase = "Hello there";

boolean r1 = phrase.startsWith("Hel"); //true
boolean r2 = phrase.startsWith("hel"); //true
boolean r3 = phrase.startsWith("Hi");  //false

System.out.println(r1);
System.out.println(r2);
System.out.println(r3);

//===OUTPUT====
true
false
false

endsWith

Given the input text, this method returns true if the current String ends with input text. Otherwise, it will return false. Note that this method is case-sensitive, lowercase and uppercase matters.

// index         01234567890
String phrase = "Hello there";
boolean r1 = phrase.endsWith("Re"); //true
boolean r2 = phrase.endsWith("RE"); //true
boolean r3 = phrase.endsWith("re");  //false

System.out.println(r1);
System.out.println(r2);
System.out.println(r3);

//===OUTPUT====
false
false
true

toLowerCase

When this method is invoked on current String, it returns new lowercase version of the current String.

1
2
3
4
5
6
7
// index         01234567890
String phrase = "HELLO THERE";
String ret = phrase.toLowerCase();
System.out.println(ret);

//===OUTPUT====
hello there

toUpperCase

When this method is invoked on current String, it returns new uppercase version of the current String.

1
2
3
4
5
6
7
// index         01234567890
String phrase = "hello there";
String ret = phrase.toUpperCase();
System.out.println(ret);

//===OUTPUT====
HELLO THERE

toCharArray

This method returns char[] array representation of the text in current String. Note that every text data is just a collection of characters.

// index         01234567890
String phrase = "hello there";

// covert String to char array
char[] ret = phrase.toCharArray();

String out = Arrays.toString(ret);
System.out.println(out);

//===OUTPUT====
[h, e, l, l, o,  , t, h, e, r, e]