What are Java Strings and How To Implement Them?

A string is an immutable data type, that is, the values cannot be changed once defined. Strings store sequential data of a character type. This "Java Strings" article will explain the string classes and their functionalities adequately through the following docket:

  1. What are Java Strings?
  2. How do you create Java Strings?
  3. Methods based on Java Strings
  4. Java Strings example programs

What Are Java Strings?

Java Strings are character data type objects that are from the class.java.lang library. The Java Strings sequentially store the character type data, and this data can be created and manipulated through a string class.

Example: 

String Simple = "Welcome"; 

How Do You Create Java Strings?

Java Strings are none other than character arrays. The strings are entirely immutable, and we cannot alter it. In case we implement the changes, then the string turns out to become a wholly new string. 

In Java, we can create a string by using two different methods. 

  • Using String Literals
  • Using the New Keyword

String Literal Method

One can easily create a string by following the String Literal syntax below:

<Sting _Type> <String_Name> = "<Sequence_of_Characters>;

By default, Java creates strings using the String Literal method as this creates the strings in String Constant Pool. This procedure is efficient in saving memory.

The New Keyword

String simple = new String("Hello World");

This method uses heap memory and generates one reference variable and two objects. Here, Java creates the string object in heap memory, and the string "Hello World" is saved in a string constant pool, and the variable "simple" will refer to the object in heap memory.

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

Methods Based on Java Strings

There are many string manipulation methods available in Java. We will include the most essential and frequently used string methods to ensure we cover the crucial String Methods. The string methods are as below:

String getBytes()

The name of this method is self-explanatory. The purpose of this method is to convert the character sequence and return the same sequence in byte format.

Let’s take the following example for better understanding:

package simplilearn;

public class Simplilearn {

 public static void main(String args[]) {

  String string = "SIMPLILEARN";

  byte[] data = string.getBytes();

  for (int j = 0; j < data.length; j++) {

   System.out.println(data[i]);

  }

 }

}

//Output:

83

73

77

80

76

73

76

69

65

82

78

String indexOf()

String indexOf() performs a simple function of fetching the index number of a specific character in the string.

Let’s take the following example for better understanding:

package simplilearn ;

public class Simplilearn {

 public static void main(String[] args) {

  String myStr = "Hello World";

  System.out.println(myStr.indexOf("W", 1));

 }

}

//Output

6

String toCharArray()

The functionality of this method is straightforward. It just converts the string into a character array format.

Let’s take the following example for better understanding:

package simplilearn;

public class simplilearn {

 public static void main(String[] args) {

  String string = "Hello World";

  char[] character = string.toCharArray();

  int length = character.length;

  System.out.println("Character Array length is: \n" + character);

  System.out.println("Character Array elements are: \n");

  for (int i = 0; i < length; i++) {

   System.out.println(character[i]);

  }

 }

}

//Output:

Character Array length is: 

[C@15db9742

Character Array elements are: 

H

e

l

l

o

 

W

o

r

l

d

String compareTo()

String compareTo is a method that is similar to string compare, but the difference is, the compareTo method compares the two strings lexically. It provides three types of output, which are: 

  1. Zero
  2. Positive
  3. Negative

Based on the lexicographical comparison result.

Let’s take the following example for better understanding:

package simplilearn ;

public class simplilearn {

 public static void main(String args[]) {

  String string1 = "Simple";

  String string2 = "Simple";

  String string3 = "Welcome";

  System.out.println(string1.compareTo(string2));

  System.out.println(string1.compareTo(string3));

 }

}

//Output:

0

17

String SubString()

SubString method helps us find a specific substring in the main string with the help of index values.

Let’s take the following example for better understanding:

package simplilearn;

public class simplilearn {

 public static void main(String args[]) {

  String Str = new String("Welcome to Simplilearn");

  System.out.print("String at the given location is:\n");

  System.out.println(Str.substring(10, 22));

 }

}

//Output:

String at the given location is: 

Simplilearn

String hashCode()

The String hashCode method will help us check the string, and find the equivalent hash code of it

Let’s take the following example for better understanding:

package simplilearn ;

public class simplilearn {

 public static void main(String args[]) {

  String Text = new String("Simplilearn");

  System.out.println("Hashcode for Word is : " + Text.hashCode());

 }

}

//Output:

Hashcode for Word is: 375088686

String toString()

The String toString() method returns itself a string. We will consider an example for better understanding.

package simplilearn ;

public class simplilearn {

 public static void main(String args[]) {

  String Text = new String("Hello World");

  System.out.print("Converted String : ");

  System.out.println(Text.toString());

 }

}

//Output:

Converted String: Hello World

String concat()

This method combines/concatenates two or more strings together.

Let’s take the following example for better understanding:

package simplilearn ;

public class simplilearn {

 public static void main(String args[]) {

  String string1 = "Hello World.";

  System.out.println(string1);

  string1 = string1.concat(" Learn and excel");

  System.out.println(string1);

 }

}

//Output:

Hello World.

Hello World. Learn and excel.

String lastIndexOf()

The functionality of the String LastIndexOf method is to return the last index of the given character value. If it isn’t existing, then it returns -1. 

Let’s take the following example for better understanding:

package simplilearn ;

public class simplilearn {

 public static void main(String[] args) {

  String string = "Simplilearn";

  int ind = string.lastIndexOf('S', 1);

  System.out.println(ind);

 }

}

//Output:

0

String length()

The String Length method counts the number of characters in a string. In other words, the total length of the string.

Let’s take the following example for better understanding:

Package simplilearn ;

public class simplilearn {

 public static void main(String args[]) {

  String string = "Hello World";

  System.out.println("string length is: " + string.length());

 }

}

//Output:

string length is: 11

String replace()

The "string replace" method aims to replace the existing string with a different one.

Let’s take the following example for better understanding:

package simplilearn ;

public class simplilearn {

 public static void main(String args[]) {

  String string = "GOOGLE";

  String New = string.replace('G', 'D');

  System.out.println(New);

 }

}

//Output:

DOODLE

String split()

 The String Split method splits an entire string into the set of words used to form the statement.

Let’s take the following example for better understanding:

package simplilearn;

public class simplilearn {

 public static void main(String args[]) {

  String data = "Hello World. Welcome to Simplilearn";

  String[] split = data.split("\\s");

  for (String s : split) {

   System.out.println(s);

  }

 }

}

//Output:

Hello

World.

Welcome

to

Simplilearn

String equals()

String compare and String Equals perform the same type of operation. They compare two strings with one another.

Let’s take the following example for better understanding:

package simplilearn;

public class simplilearn {

 public static void main(String args[]) {

  String statement1 = "Data Science";

  String statement2 = "Data Science";

  String statement3 = "Deep Learning";

  System.out.println(statement1.equals(statement2));

  System.out.println(statement1.equals(statement3));

 }

}

//Output:

true

false

String toLowerCase()

The String toLowerCase method converts the string from upper case to lower case.

Let’s take the following example for better understanding:

package simplilearn;

public class simplilearn {

 public static void main(String args[]) {

  String Upper = "HELLO WORLD";

  String Lower = Upper.toLowerCase();

  System.out.println(Lower);

 }

}

//Output:

hello world

String toUpperCase()

String toUpperCase method converts the string from lowercase to uppercase.

Let’s take the following example for better understanding:

package simplilearn;

public class simplilearn {

 public static void main(String args[]) {

  String Lower= "hello world";

  String Upper= Lower.toUpperCase();

  System.out.println(Upper);

 }

}

//Output:

HELLO WORLD

String trim()

The String Trim method eliminates the unnecessary blank and trailing spaces in Strings. 

Let’s take the following example for better understanding:

package simplilearn ;

public class simplilearn {

 public static void main(String[] args) {

  String Original = "Hello World.";

  System.out.println(Original.length());

  System.out.println(Original);

  String trimmed = Original.trim();

  System.out.println(trimmed.length());

  System.out.println(trimmed);

 }

}

//Output:

12

Hello World.

12

Hello World.

String intern()

The String Intern method represents a particular string in canonical form.

Let’s take the following example for better understanding:

package simplilearn;

public class simplilearn {

 public static void main(String[] args) {

  String Word1 = "Hello";

  String Word2 = Word1.intern();

  System.out.println(Word1 == Word2);

 }

}

//Output: 

True

Java Strings Example Programs

Reverse a given string

package simplilearn;

public class simplilearn {

 public static void main(String[] args) {

  String Original = "Simplilearn";

  String Reversed = new StringBuffer(Original).reverse().toString();

  System.out.println("\nString prior to reverse Operation: " + Original);

  System.out.println("\nString after reverse Operation: " + Reversed);

 }

}

//Output:

String before reverse Operation: Simplilearn

String after reverse Operation: nraelilpmiS

Find a substring location inside the string.

package simplilearn ;

public class simplilearn {

 public static void main(String[] args) {

  String Original = "Welcome to Simplilearn";

  int Index = Original.indexOf("Simplilearn");

  if (Index == -1) {

   System.out.println("Simplilearn is not present in the string");

  } else {

   System.out.println("Found the word at index location: " + Index);

  }

 }

}

//Output: 

Found the word at index location: 11

String matching

package simplilearn;

public class simplilearn {

 public static void main(String args[]) {

  String str = new String("Welcome to Simplilearn");

  System.out.print("\nRegex: (.*)Welcome(.*) matches string? ");

  System.out.println(str.matches("(.*)Welcome(.*)"));

  System.out.print("\nRegex: (.*)to(.*) matches string? ");

  System.out.println(str.matches("(.*)Strings(.*)"));

  System.out.print("\nRegex: (.*)Simplilearn matches string? ");

  System.out.println(str.matches("(.*)Simplilearn"));

 }

}

//Output:

Regex: (.*)Welcome(.*) matches string? true

Regex: (.*)to(.*) matches string? false

Regex: (.*)Simplilearn matches string? true

The last occurrence of a word in the string

package simplilearn;

public class simplilearn {

 public static void main(String[] args) {

  String Original = "Hello world. Welcome to Simplilearn";

  int Index = Original.lastIndexOf("Simplilearn");

  if (Index == -1) {

   System.out.println("Word not found");

  } else {

   System.out.println("The last occurrence of the given word is at index " + Index);

  }

 }

}

//Output:

The last occurrence of the given word is at index 24

String replacement

package simplilearn ;

public class simplilearn {

 public static void main(String args[]) {

  String text = "GOOGLE";

  System.out.println(text.replace('G', 'D'));

  System.out.println(text.replaceFirst("GOOGLE", "DOODLE"));

 }

}

//Output:

DOODLE

DOODLE

With this, we have now arrived at the end of this 'Java Strings' article. We hope you enjoyed learning about the essential information related to the Java Strings in a detailed approach.

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Are You Interested in Learning More About Java and Getting Certified? 

Then, check out our Java training and certification program curated by the most experienced real-time industry experts.

Got a question for us? Please mention it in the article's comment section, and we'll have our experts answer it for you right away. 

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.