×

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

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.

Java Math round() Method

The round() method of Java Math class returns a long or an int value that is closest to the argument and is rounded to positive infinity. Syntax: public static int round(float a)public...

2 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

Hello Program in Java

Hello Program in Java The Hello program in Java displays the word Hello on the console. It is the basic program in Java. In this section, we will learn different ways...

3 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Java Network Programming (Socket Programming in Java)

JAVA NETWORK Network programming is used to execute programs across multiple machines that are connected by a network. The java.net package contains a collection of classes and interfaces that provide this...

3 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

StringBuilder in Java

StringBuilder in Java Java StringBuilder class is introduced since JDK 1.5. The StringBuilder class is mainly used to create modifiable or mutable strings. Note that the StringBuilder class is not synchronized....

7 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

How to Convert Date to Timestamp in Java

How to Convert Date to Timestamp in Java You can convert Date to Timestamp by using the getTime() method of Date class. It returns the long millisecond from Epoch which can...

1 minute read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Class vs Object in Java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Pangram Program in Java

If a string comprises all alphabet letters from A to Z or from a to z without regard to case, it is referred to as a pangram. Some examples of pangram...

3 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.