What is String in Java - Java String Types and Methods (With Examples)

What is String in Java - Java String Types and Methods (With Examples)

12 Apr 2024
Beginner
3.87K Views
20 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

String Functions in Java: An Overview

String Functions in Java are various functions available in the Java string class to manipulate strings. Strings are specific types of objects in java.lang class that represents a sequence of characters. For creating and manipulating Strings, the Java platform needs a String class. In this Java tutorial, we will learn the concepts of Strings in Java in detail. If you're interested in gaining expertise in working with Java strings and earning a recognized achievement, consider enrolling in our Java Certification Course.

What is a Java String Function?

In Java, String does not identify as a datatype. It identifies as a class, a fundamental data type in Java. Any programmer can create a String by instantiating the String class that is situated in the package of java.lang. The Java string methods assist in generating some methods and construction for creating, manipulating, and searching a String. The objects of string functions in Java are immutable.

Read More - Top 50 Java Interview Questions For Freshers

How to Create a String Object in Java?

There are a few steps to create a String Object in Java, those are:

How to Create a String Object?

Java String Example


class String_Creation_Demo
{
  public static void main(String[] args)
  {
    String ob1 = new String(); //creates an empty string

    //new keyword helps to create an object of class String
    System.out.println("Empty String: " +ob1);

    char arr[] = {'j','k','a','q','e' };
    String ob2 = new String(arr); //String from an array

    System.out.println("Contents of Array String: " +ob2);

    String ob3 = new String(arr,1,2); //String from subsequence of an array
    System.out.println("Contents of subsequence of Array String: " +ob3);

    String ob4 = new String(ob3); //String from another string object
    System.out.println("Contents of Array String ob4: " +ob4);
  }
}

Output

Empty String: 
Contents of Array String: jkaqe
Contents of subsequent of Array String: ka
Contents of Array String ob4: ka

2 Ways to Create a String Object in Java

String objects can be created using two ways:

  1. Using String Literal
  2. Using new keyword

1. Using String Literal

In computer science, a literal is a term used to represent a value. Double quotes can be used to produce and represent Java String literals. You can insert any text or character between double quotes.

Syntax

<string_type> <string_variable> = "<sequence_of_string>";
Example
Let's look at the illustration of creating a string using a string literal in our Java Online Editor.

public class Main {

  public static void main(String args[]) {
    // A string object
String demoString = “Scholarhat”;
     System.out.println(demoString);
  }
}
Output

Scholarhat

2. Using new keyword

The Java new keyword can be used to construct strings. A new object of the String class is produced in the heap memory, outside the string constant pool, when a string is created with the new command. These objects, as opposed to string literals, are given their place on the heap, regardless of whether or not another object with an identical value is already present there.

Syntax

String stringName = new String("string_value");

Example


public class Main {
  public static void main(String[] args) {
   String str = new String("ScholarHat");
   System.out.println(str);
  }
}
Output
Scholarhat

Read More - Java Programmer Salary In India

Interfaces and Classes in Strings in Java

The CharSequence interface is implemented by the class known as CharBuffer. By using character buffers instead of CharSequences, this class enables their use. Java.util.regex's regular-expression package serves as an illustration of this usage. A string is a collection of characters. String objects in Java are immutable, which means they can never be modified after they have been created.

Interfaces and Classes in Strings in Java

CharSequence Interface

In Java, the CharSequence Interface is used to represent the order of characters.

CharSequence Interface

The following list includes classes that implement the CharSequence interface:

  1. String
  2. StringBuffer
  3. StringBuilder

1. String

A string is an immutable class i.e. it cannot be changed. We need to create a new object and functions like toupper, tolower, etc return a new object.

Example


String str= "Scholarhat";
           or
String str= new String("Scholarhat")

2. StringBuffer

The majority of the functionality of strings is provided by the peer class of StringBuffer. StringBuffer represents expandable and writable character sequences, whereas the string represents fixed-length, immutable character sequences.

Example


StringBuffer demoString = new StringBuffer("Scholarhat");

3. StringBuilder

A mutable string of characters is represented by the Java class StringBuilder. The StringBuilder class offers a substitute for the String Class in Java since it constructs a mutable sequence of characters instead of an immutable one as the String Class does.

Example


StringBuilder demoString = new StringBuilder();
demoString.append("Scholarhat");

StringTokenizer

A string can be divided into tokens using Java's StringTokenizer class. A StringTokenizer object internally maintains a current position within the string to be tokenized. A token is returned by taking a substring of the string used to create the StringTokenizer object.

Example

StringTokenizer

Java Strings: Mutable or Immutable

  • Strings in Java are immutable, i.e. once they are formed, their values cannot be altered.
  • To avoid conflicts that can result from numerous references to the same string object, immutability is required.
  • Multiple references may point to a single string object in the String constant pool in Java.
  • If one reference was permitted to change the value of the string, it might have an impact on other references and cause problems.
  • Java makes sure that string objects are immutable, meaning that their values cannot be changed, to avoid these conflicts.

Methods of Java Strings

NameDescription
length()Returns the length (number of characters) of the string.
charAt(int index)Returns the character at the specified index within the string (indexing starts at 0).
substring(int beginIndex)Returns a new string that is a substring of the original string starting from the specified beginIndex.
substring(int beginIndex, int endIndex)Returns a substring of the original string starting from beginIndex and ending just before endIndex.
concat(String str)Concatenates the specified string str to the end of the current string.
equals(Object obj)Check if the current string is equal to the specified object. Returns true if equal, false otherwise.
equalsIgnoreCase(String anotherString)Compares the current string to another string, ignoring case differences.
indexOf(String str)Returns the index of the first occurrence of the specified substring str within the string, or -1 if not found.
replace(char oldChar, char newChar)Replace all occurrences of oldChar with newChar in the string.
split(String regex)Splits the string into an array of substrings based on the regular expression regex.

String Manipulation

String manipulation mainly works for changing the case, fetching a character from a string, and trimming the content. There are other various important methods in string manipulation such as:

String Manipulation

String Manipulation Example in Java in our Java Compiler


class String_Manipulation_Demo
{
  public static void main(String[] args)
  {
    String ob1 = "Scholar-Hat"; //creates a string object

    //string length
    System.out.println("Length of the String: " +ob1);

    char arr[] = {'j','k','a','q','e' };
    String ob2 = new String(arr); //String from an array

    //string concatenation
    System.out.println("Concatenate String and String Array: " +ob1.concat(ob2));

    //to upper case
    System.out.println("Contents of String in uppercase: " +ob1.toUpperCase());

    //to lower case
    System.out.println("Contents of String in lowercase: " +ob1.toLowerCase());

    //split function
    for(String res: ob1.split("-",2))
    System.out.println("Splitting the String: " +res);

    //contains function
    System.out.println("Contains() function in String: " +(ob1.contains("Scholar")));

    //Replace function
    System.out.println("Replace function in String: " +(ob1.replace('o','a')));

    //ReplaceAll function
    System.out.println("ReplaceAll function in String: " +(ob1.replaceAll("lar","o")));

    //substring function
    System.out.println("Substring in String: " +(ob1.substring(3,6)));

    //trim function
    String str = " Scholar-Hat! ";

    System.out.println("Without Trim function in String: " +str);
    System.out.println("Trim function in String: " +(str.trim())); 
  }
}

When you'll execute the above program in the Java Playground to see the output.

Output

Length of the String: Scholar-Hat
Concatenate String and String Array: Scholar-Hatjkaqe
Contents of the String in uppercase: SCHOLAR-HAT 
Contents of the String in lowercase: scholar-hat 
Splitting the String: Scholar
Splitting the String: Hat
Contains() function in String: true
Replace function in String: Schalar-Hat
ReplaceAll function in String: Schoo-Hat
Substring in String: ola
Without Trim function in String: Scholar Hat!
Trim function in String: Scholar Hat!

String Comparison

Some important methods are used to make the string comparison, such as:

String Comparison

String Comparison Example


class String_Comparison_Demo
{
  public static void main(String[] args) 
  {
    String ob1 = "Scholar-Hat"; //creates a string object
    String ob2 = "scholar-hat";

    //equals function
    System.out.println("Using equals function: " +(ob1.equals(ob2)));

    System.out.println("Using equalsIgnoreCase function: " +(ob1.equalsIgnoreCase(ob2)));

    //compareTo function
    System.out.println("Using compareTo function: " +(ob1.compareTo(ob2))); 
    System.out.println("Using compareToIgnoreCase function: " +(ob1.compareToIgnoreCase(ob2)));

    //startsWith function
    System.out.println("Using startsWith function: " +(ob1.startsWith("Sc"))); 

    //endsWith function
    System.out.println("Using endsWith function: " +(ob1.endsWith("at"))); 
  }
}

Output

Using equals functions: false
Using equalsIgnoreCase functions: true
Using compareTo functions: 4
Using compareToIgnoreCase functions: 0
Using startsWith functions: true 
Using endsWith functions: true

Searching in a String

There are some specific methods to search characters in a String Object, those are:

Searching in a String

Searching in a String Example


class String_Searching_Demo
{
  public static void main(String[] args)
  {
    String ob1 = "Scholar-Hat"; //creates a string object
    System.out.println("Using indexOf function: " +ob1.indexOf('a'));
    System.out.println("Using lastIndexOf function: " +ob1.lastIndexOf('a'));
  }
}

Output

Using indexOf function: 5
Using lastIndexOf function: 9

Summary

In this comprehensive Java tutorial, we covered the Java strings methods, string functions in Java, and string operations in Java, which are essential topics to explore during a Java Online Course with a Certificate As you can see, there are a variety of operations and methods that can be performed on Java Strings. Do some experimenting and see which methods work best for your purposes.

FAQs

Q1. Why string objects are immutable in Java?

Because string objects cannot be changed after being created, Java makes them immutable to protect the security and integrity of data.

Q2. What is a string in Java with an example?

A string is a group of characters in Java. Example: String myString = "Hello, Java!";

Q3. What are Java 8 strings?

The java.util.StringJoiner class was added in Java 8 to allow for more effective string concatenation.

Q4. What is Java string data type?

A series of characters are represented by the string data type in Java. It's defined by the class java.lang.String.

Q5. Why string is used in Java?

Java uses strings to manipulate text, store text data, and carry out various actions on text.

Q6. What is string format?

In Java, the term "string format" describes setting a template with placeholders that will later be filled in with data. Example: "Hello,%s!" can be formatted as "Hello, Java!" by adding the word "Java".

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Angular Certification Course Jun 16 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jun 17 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
ASP.NET Core Certification Training Jun 17 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
.NET Microservices Certification Training Jun 23 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
ASP.NET Core (Project) Jun 23 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Azure Developer Certification Training Jun 23 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
React JS Certification Training | Best React Training Course Jun 30 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
ASP.NET Core Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Generative AI For Software Developers Jul 14 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this