Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
What is String in Java - Java String Methods & Type (Examples)

What is String in Java - Java String Methods & Type (Examples)

02 Dec 2024
Beginner
7.81K Views
24 min read
Learn with an interactive course and practical hands-on labs

Free Java Course With Certificate

String Functions in Java

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 Full Stack Course.

What are Strings in Java?

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 situated in Java. lang package. 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.

Example:

String name = "ScholarHat";

 Strings in Java

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 string's value, it might impact other references and cause problems.
  • To avoid these conflicts, Java ensures that string objects are immutable, meaning that their values cannot be changed.

Immutable String in Java

Definition: In Java, strings are immutable, meaning that once a string object is created, its value cannot be changed. Any operation that modifies a string creates a new string object in memory rather than altering the original one.

Characteristics:

  • String immutability ensures security, simplicity, and efficiency in Java.
  • It is thread-safe, meaning multiple threads can use a string without synchronization issues.
  • Strings are stored in the String Pool for better memory optimization.

Advantages:

  • Makes strings secure, especially when used in sensitive areas like database connections.
  • Optimizes memory usage through the String Constant Pool.

Example:

public class ImmutableStringExample {
    public static void main(String[] args) {
        String str = "Hello";
        str.concat(" World");
        System.out.println(str); // Output: Hello
        
        String newStr = str.concat(" World");
        System.out.println(newStr); // Output: Hello World
    }
}     

Explanation: The concat method does not change the original string str but creates a new string newStr.

Memory Allotment of String

Definition: In Java, memory for strings is managed through two main areas:

  • Heap Memory: Used for strings created using the new keyword.
  • String Constant Pool: A special area in the heap for storing string literals.

Characteristics:

  • The String Pool allows reusability of string objects to optimize memory usage.
  • Strings created using literals are stored in the String Constant Pool.
  • Strings created with the new keyword are stored in the Heap Memory but can still reference the pool if intern() is used.

Advantages:

  • Reduces memory consumption for commonly used strings.
  • Improves performance in applications where string manipulation is frequent.

Example:

public class StringMemoryExample {
    public static void main(String[] args) {
        String s1 = "Hello";  // Stored in String Pool
        String s2 = "Hello";  // References the same object in String Pool
        String s3 = new String("Hello"); // Stored in Heap Memory
        String s4 = s3.intern(); // References String Pool object

        System.out.println(s1 == s2); // true
        System.out.println(s1 == s3); // false
        System.out.println(s1 == s4); // true
    }
}       

Explanation:

  • s1 and s2 point to the same object in the String Pool.
  • s3 is a new object in the heap.
  • s4 uses intern() to refer to the String Pool object.

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 ComparisonExample


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 StringExample


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 Full Stack Development Course 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

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

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

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

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

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

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
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this