×

Java Strings

String class is the most used class in Java programming language. The string is the sequence of characters, which is treated as objects in Java.

Creating String objects

We create String objects using a new operator or by using string literal values within double quotes. But there is a big difference between them about how these objects are stored and referred to, by Java.

Example 1.

public class ExampleString {
public static void main(String[] args) {
StrObj stringClass = new StrObj();
System.out.println(stringClass.str1 == stringClass.str2);
}
}
class StrObj {
String str1 = new String("INDIA");
String str2 = new String("INDIA");
}

Output:

false

String objects created using new operator always refer to separate objects, even if they store the same sequence of characters.

Example 2.

public class ExampleString {
String str1 = "INDIA";
String str2 = "INDIA";
public static void main(String[] args) {
ExampleString stringClass = new ExampleString();
System.out.println(stringClass.str1==stringClass.str2);
}
}

Output:

true

When the string object is created using literal method, JVM searches for the same sequence of character in the string pool. If it finds the same sequence, JVM does not create the string object but make it refer to the same string previously created. Hence str2 will point to the object created by the str1 that’s why the result is true here.

We can also create a string object using

System.out.println("INDIA");

If the matching value is found in the string pool, the value is reused. If the matching value is not found in the string pool, JVM has first to create it and then place it to the spring pool.

Let's count some string objects:

1 String star = new String("Star");
2 String star2 = "Star";
3 System.out.println("Star");
4 System.out.println("Moon");
5 System.out.println("Moon" == "star");
6 String star1 = new String("Star");

Line 1 creates a String object having value “Star” in heap memory.

Line 2 creates a String object and place it to the string pool.

Line 3 does not create String object since the same value is stored in the string pool.

Line 4 creates a String object having value “Moon” and place it to the string pool.

Line 5 creates String object since “star”  has a lower case ‘s’ and it is treated as a different value.

Line 6 creates a String object having value “Star” in heap memory.

String class is Immutable

String class is immutable, and it means that the object of this class can not be modified.

This is for performance reason, and the JVM can reuse this object which led to low memory overhead and good performance.

String class is made immutable by following three steps.

  • The value of the String object is stored in the char array (char value[]) and it is marked final so that it cannot be modified or re-initialized.
  • The length of the array is fixed and cannot be increased once initialized.
  • All methods defined in the string class do not modify the array value instead, they return a new String object.

Methods of the String Class

charAt(): It is used to retrieve a character at a specified index of a String :

Example:

public class Myclass{ 
public static void main(String args[]){ 
String country = new String("India");
System.out.println(country .charAt(0)); //  returns “I”
System.out.println(country .charAt(3)); // returns “i”
    } 
}

Output:

I
i

This method may throw a runtime exception if we seek the position out of the range

Example:

System.out.println(country.charAt(5));

the exception is java.lang.StringIndexOutOfBoundsException.

indexOf():  This method search for the occurrence of a character or a String, if it found in the target String, it returns the first matching position else -1.

Example :

public class MyClass {
public static void main(String[] args) {
String country = "INDIA";
System.out.println(country.indexOf('D')); // prints 2
System.out.println(country.indexOf("I")); // prints 0
}
}

Output:

2
0

By default, JVM starts searching from index position 0 if we want to start searching at some specific position we may pass it like

public class MyClass {
public static void main(String[] args) {
String country = "INDIA";
System.out.println(country.indexOf('I', 2)); //prints 3
}
}

Output:

3

substring(): It returns the substring of the targeted string. It is of two kinds,

Example :

public class MyClass {
public static void main(String[] args) {
String country = "INDIA";
String sub = country.substring(2);  // prints DIA
String sub1 = country.substring(2,4); // prints DI
System.out.println(sub);
System.out.println(sub1);
}
}

Output:

DIA
DI

The first output will print from seeking the position to the end of the given string.

The second will print from seeking position to the last value-1(does not include the character at the end position).

It should be noted that the total length of the resulted string is

(end Index) - (beginning Index).

trim(): This method removes the leading and trailing whitespace and returns a new string.

Example :

public class MyClass {
public static void main(String[] args) {
String str = "  This Is Text    ";
System.out.println(str);       // prints “  This Is Text    ”
System.out.print(str.trim()); // prints “This Is Text”
}
}

Output:

This Is Text    
This Is Text

replace('a', 'A'): This method replaces all the specified occurrence of a char value with another value. We can also replace String with another String.

Example :

public class MyClass {
public static void main(String[] args) {
String country = "INDIA";
System.out.println(country.replace('I', 'A'));  // prints ANDAA
System.out.println(country.replace("DI", "LI")); //prints INLIA
}
}

Output:

ANDAA
INLIA

length() : length() method  is used to retrieve the length of a String.

Example :

public class MyClass {
public static void main(String[] args) {
System.out.println("India".length()); // prints 5
}
}

Output:

5

Equality of Strings

equals() method is used to compare the equality of two string. This method returns true if the object being compared to a string object and have the same characters sequence.

public class MyClass {
public static void main(String[] args) {
String v1 = new String("INDIA");
String v2 = new String("INDIA");
System.out.println(v1.equals(v2));     //prints true
System.out.println(v1 == v2);     //prints false
}
}

Output:

true
false

String Concatenation

A string can be concatenated using concat() or “+” operator.

str1.concat(str2)

or like

"INDIA".concat(" IS A COUNTRY") // prints INDIA IS A COUNTRY

or like

"INDIA"+"My Country" // prints INDIA My COUNTRY

Example:

public class MyClass {
public static void main(String[] args) {
String str1 = new String("INDIA");
String str2 = new String(" USA");
System.out.println(str1.concat(str2));
System.out.println( "INDIA".concat(" IS A COUNTRY"));   // prints INDIA IS A COUNTRY
System.out.println( "INDIA"+" Is My Country"); // prints INDIA My COUNTR
}
}

Output:

INDIA USA
INDIA IS A COUNTRY
INDIA Is My Country

Java String Methods List


Related Topics

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Java Virtual Machine (JVM)

JVM is a virtual runtime environment to execute Java byte codes. The JVM doesn’t understand the keywords we used to write code. That is why it is converted into bytecode. It controls the...

3 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Coin change problem in dynamic programming

In this tutorial, we will understand a popular problem called the coin changeproblem through dynamic programming. This problem checks the logical and critical thinking ability of the person. Dynamic Programming...

5 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Java md5 Hash Example

A 128-bit hash value is generated by the Message Digest Algorithm 5, which is a cryptographic algorithm. A stationary hash value is generated by the hash function from data of...

3 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.