All About String in Java

sajith dilshan
Geek Culture
Published in
9 min readFeb 3, 2023
All About String in Java

Java Strings are objects that are backed by a char array and are immutable. The class java.lang.String is used to create a string object.

There are two ways to create a String object:

  1. Using string literal
  2. Using the “new” keyword

1) Using String Literal

A string literal is created by using double quotes. For example:

String str = "Hello World!";

Each time you create a string literal, the JVM checks the string pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn’t exist in the pool, a new string instance is created and placed in the pool.

String str1 = "Hello World!";
String str2 = "Hello World!";
//It doesn't create a new instance

In this example, only one object will be created. The JVM will first create a new object with the value “Hello World!”, and then it will find the string with the same value in the pool and return the reference to the same instance instead of creating a new one.

2) Using “new” keyword

When you use the “new” keyword, a new instance of the string is created in the heap, regardless of whether it already exists in the string pool.

String str1 = new String("Hello World!");
String str2 = new String("Hello World!");

In this example, two objects will be created and two references to those objects will be created.

The string pool is a storage area in Java heap memory where all the other objects are created. It reduces memory overhead and increases performance by reducing the number of String objects created in the JVM. Each time a string literal is created, the JVM checks the string pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn’t exist in the pool, a new instance is created and placed in the pool.

Java String class methods.

01. char charAt(int index) : It returns char value for the particular index

E.g.

public class Example{
public static void main(String args[]){
String name="sajith";
char ch=name.charAt(4);//returns char value at the 4th index
System.out.println(ch);
}}

Output:

t

02. int length() : It returns string length

E.g.

public class Example{
public static void main(String args[]){
String name="sajith";

System.out.println("string length is: "+name.length());//6 is the length of sajith string

}}

Output:

string length is: 6

03. static String format(String format, Object… args) /

static String format(Locale l, String format, Object… args) : It returns a formatted string.

String format

Parameters

locale: specifies the locale to be applied on the format() method.

format: format of the string.

args: arguments for the format string. It may be zero or more.

E.g.

public class Example{
public static void main(String args[]){
String name="sajith";
String sf1=String.format("name is %s",name);
String sf2=String.format("value is %f",32.33434);
String sf3=String.format("value is %32.12f",32.33434);//returns 12 char fractional part filling with 0
System.out.println(sf1);
System.out.println(sf2);
System.out.println(sf3);
}}

Output:

name is sajith
value is 32.334340
value is 32.334340000000

Java String Format Specifiers

Here, we are providing a table of format specifiers supported by the Java String.

Java String Format Specifiers

E.g.

public class Example2 {
public static void main(String[] args) {
String str1 = String.format("%d", 101); // Integer value
String str2 = String.format("%s", "sajith dilshan"); // String value
String str3 = String.format("%f", 101.00); // Float value
String str4 = String.format("%x", 101); // Hexadecimal value
String str5 = String.format("%c", 'c'); // Char value
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
}
}

Output:

101
sajith dilshan
101.000000
65
c

04. String substring(int beginIndex) /
String substring(int beginIndex, int endIndex): It returns substring for given begin index.

E.g.

public class Example {
public static void main(String[] args) {
String s1="sajith Dilshan";
String substr = s1.substring(0); // Starts with 0 and goes to end
System.out.println(substr);
String substr2 = s1.substring(5,10); // Starts from 5 and goes to 10
System.out.println(substr2);
}
}

Output:

sajith Dilshan
h Dil

05. boolean contains(CharSequence s): It returns true or false after matching the sequence of char values.

E.g.

class ContainsExample{
public static void main(String args[]){
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
System.out.println(name.contains("sajith"));
}}

Output:

true
true
false

06. static String join(CharSequence delimiter, CharSequence… elements) /

static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) : It returns a joined string.

E.g.

public class Example{
public static void main(String args[]){
String joinString1=String.join("-","welcome","to","sajith");
System.out.println(joinString1); String date = String.join("/","10","02","2022");
System.out.print(date);
String time = String.join(":", "15","20","20");
System.out.println(" "+time); }}

Output:

welcome-to-sajith10/02/2022 15:20:20

07. boolean equals(Object another) : It checks the equality of string with the given object.

E.g.

public class Example{
public static void main(String args[]){ String s1="sajith dilshan";
String s2="sajith dilshan";
String s3="SAJITH DILSHAN";
String s4="java";
System.out.println("output");
System.out.println(s1.equals(s2));//true because content and case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same }}

Output:

true
false
false

08. boolean isEmpty() : It checks if string is empty.

E.g.

public class Example{
public static void main(String args[]){
String s1="";
String s2="sajith dilshan";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}}

Output:

true
false

Empty Vs. Null Strings

Earlier in this tutorial, we have discussed that the empty strings contain zero characters. However, the same is true for a null string too. A null string is a string that has no value.

//1.
String str = ""; // empty string//2.
String str1 = null; // null string. It is also not containing any characters.

The isEmpty() method is not fit for checking the null strings.

09. String concat(String str) : It concatenates the specified string.

E.g.

public class Example{
public static void main(String args[]){
String s1="Sajith,java string"; // The string s1 does not get changed, even though it is invoking the method
// concat(), as it is immutable. Therefore, the explicit assignment is required here. s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}}

Output:

Sajith,java stringSajith,java string is immutable so assign it explicitly

10. String replace(char old, char new) : It replaces all occurrences of the specified CharSequence.

String replace(CharSequence old, CharSequence new : It replaces all occurrences of the specified CharSequence.

E.g.

Java String replace(char old, char new) method

public class Example1{
public static void main(String args[]){
String s1="java is a popular programming language";
String replaceString=s1.replace('a','e');
//replaces all occurrences of 'a' to 'e'
System.out.println(replaceString);
}}

Output:

jeve is e populer progremming lenguege

E.g.

Java String replace(CharSequence target, CharSequence replacement) method

public class Example2{
public static void main(String args[]){ String s1="my first name is sajith my last name is dilshan";
String replaceString=s1.replace("is","was");//replaces all occurrences of "is" to "was"
System.out.println(replaceString); }}

Output:

my first name was sajith my last name was dilshan

11. static String equalsIgnoreCase(String another) : It compares another string. It doesn’t check case.

E.g.

public class Example{
public static void main(String args[]){
String s1="sajith";
String s2="sajith";
String s3="SAJITH";
String s4="java";
System.out.println(s1.equalsIgnoreCase(s2));//true because content and case both are same
System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored
System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same
}}

Output:

true
true
false

12. String[] split(String regex) : It returns a split string matching regex.

String[] split(String regex, int limit) : It returns a split string matching regex and limit.

E.g.

public class Example{
public static void main(String args[]){
String s1="java string split method by sajith";
String[] words=s1.split("\\s");//splits the string based on whitespace
//using java foreach loop to print elements of string array
for(String w:words){
System.out.println(w);
}
}}

Output:

java
string
split
method
by
sajith

E.g.

public class Example2{
public static void main(String args[]){
String s1="welcome to split world";
System.out.println("returning words:");
for(String w:s1.split("\\s",0)){
System.out.println(w);
}
System.out.println("----------------"); System.out.println("returning words:");
for(String w:s1.split("\\s",1)){
System.out.println(w);
} System.out.println("----------------"); System.out.println("returning words:");
for(String w:s1.split("\\s",2)){
System.out.println(w);
}
}}

Output:

returning words:
welcome
to
split
world----------------returning words:
welcome to split world----------------returning words:
welcome
to split world

13. String intern() : It returns an interned string.

E.g.

public class InternExample{
public static void main(String args[]){
String name1=new String("sajith");
String name2="sajith"; String name3=name1.intern();//returns string from pool, now it will be same as s2 System.out.println(name1==name2);//false because reference variables are pointing to different instance System.out.println(name2==name3);//true because reference variables are pointing to same instance
}}

Output:

false
true

14. int indexOf(int ch) : It returns the specified char value index.

int indexOf(int ch, int fromIndex) : It returns the specified char value index starting with given index.

int indexOf(String substring) : It returns the specified substring index.

int indexOf(String substring, int fromIndex) : It returns the specified substring index starting with given index.

E.g.

int indexOf(int ch) example

public class Example1{
public static void main(String args[]){ String s1="sajith dilshan";
//passing char value
int index4=s1.indexOf('j');//returns the index of s char value
System.out.println(index4);//3

}}

Output:

2

E.g.

Java String indexOf(int char, int fromIndex) Method Example

public class Example2 {
public static void main(String[] args) {
String s1 = "This is indexOf method";
// Passing char and index from
int index = s1.indexOf('e', 12); //Returns the index of this char
System.out.println("index of char "+index);
}
}

Output:

index of char 17

E.g.

Java String indexOf(String substring) Method Example

public class Example3 {
public static void main(String[] args) {
String s1 = "This is indexOf method";
// Passing Substring
int index = s1.indexOf("method"); //Returns the index of this substring
System.out.println("index of substring "+index);
}
}

Output:

index of substring 16

E.g.

Java String indexOf(String substring, int fromIndex) Method Example

public class Example4 {
public static void main(String[] args) {
String s1 = "This is indexOf method";
// Passing substring and index
int index = s1.indexOf("method", 10); //Returns the index of this substring
System.out.println("index of substring "+index);
index = s1.indexOf("method", 20); // It returns -1 if substring does not found
System.out.println("index of substring "+index);
}
}

Output:

index of substring 16
index of substring -1

15. String toLowerCase() : It returns a string in lowercase.

E.g.

public class Example{
public static void main(String args[]){
String s1="My NAME IS saJITH";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}}

Output:

my name is sajith

16. String toLowerCase(Locale l) : It returns a string in lowercase using specified locale.

E.g.

import java.util.Locale;
public class StringLowerExample2 {
public static void main(String[] args) {
String s = "My NAME IS saJITH";
String eng = s.toLowerCase(Locale.ENGLISH);
System.out.println(eng);
String turkish = s.toLowerCase(Locale.forLanguageTag("tr")); // It shows i without dot
System.out.println(turkish);
}
}

Output:

my name is sajith
my name ıs sajıth

17. String toUpperCase() : It returns a string in uppercase.

E.g.

public class Example{
public static void main(String args[]){
String s1="hello sajith";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}}

Output:

HELLO SAJITH

18. String toUpperCase(Locale l) : It returns a string in uppercase using specified locale.

E.g.

import java.util.Locale;
public class Example {
public static void main(String[] args) {
String s = "hello sajith";
String turkish = s.toUpperCase(Locale.forLanguageTag("tr"));
String english = s.toUpperCase(Locale.forLanguageTag("en"));
System.out.println(turkish);//will print I with dot on upper side
System.out.println(english);
}
}

Output:

HELLO SAJİTH
HELLO SAJITH

19. String trim() : It removes beginning and ending spaces of this string.

E.g.

public class Example{
public static void main(String args[]){
String s1=" hello sajith ";
System.out.println(s1+"dilshan");//without trim()
System.out.println(s1.trim()+"dilshan");//with trim()
}}

Output:

hello sajith   dilshan
hello sajithdilshan

20. static String valueOf(int value) : It converts given type into string. It is an overloaded method.

E.g.

public class Example{
public static void main(String args[]){
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);//concatenating string with 10
}}

Output:

3010

* Escape character in Java Strings

Escape sequences are used to signal an alternative interpretation of a series of characters. In Java, a character preceded by a backslash (\) is an escape sequence.

The Java compiler takes an escape sequence as one single character that has a special meaning.

Escape sequence

E.g.

public class EscapeCharaterExample{
public static void main(String args[]){//it inserts a Tab Space
String str = "Sajith\tDilshan";
System.out.println(str);
System.out.println("---------------");
//it inserts a New Line
String str1 = "the best way\nto communicate \nan idea \nis to act it out";
System.out.println(str1);
System.out.println("---------------");
//it insert a backslash
String str2 = "And\\Or";
System.out.println(str2);
System.out.println("---------------");
//it insert a Carriage
String str3 = "Carriage\rReturn";
System.out.println(str3);
System.out.println("---------------");
//it prints a single quote
String str4 = "Wall Street\'s";
System.out.println(str4);
System.out.println("---------------");
//it prints double quote
//String str5 = "New\'Twilight'Line";
String str5 = "'SajithDilshan'";
System.out.println(str5); }
}

Output:

Sajith  Dilshan
---------------
the best way
to communicate
an idea
is to act it out
---------------
And\Or
---------------
Return
---------------
Wall Street's
---------------
'SajithDilshan'

Further references:

Social Media: LinkedIn, Twitter, Instagram, YouTube, GitHub.

--

--

sajith dilshan
Geek Culture

Software Engineer | Technical Writer | Tech Enthusiast