Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
StringBuffer Class in Java
Next article icon

String Class in Java

Last Updated : 01 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java.

Example of String Class in Java:

Java
// Java Program to Create a String import java.io.*;  class Geeks {     public static void main (String[] args) {              	// String literal     	String s = "Geeks for Geeks String in Java";         	System.out.println(s);     } } 

Output
Geeks for Geeks String in Java 

Explanation:

The above program creates a string using a literal and prints it.

Table of Content

  • Creating a String
    • 1. Using String literal
    • 2. Using new keyword
  • String Constructors in Java
  • String Methods in Java
  • Example of String Constructor and String Methods

Creating a String

There are two ways to create string in Java:

1. Using String literal

String s = “GeeksforGeeks”;

2. Using new keyword

String s = new String (“GeeksforGeeks”);

Example of Creating String in Java

Java
// Java Program to Create a String import java.io.*;  class Geeks {     public static void main (String[] args) {              	// String literal     	String s1="String1";       	System.out.println(s1);              	// Using new Keyword        	String s2= new String("String2");       	System.out.println(s2);     } } 

Output
String1 String2 


String Constructors in Java

String Constructors

Description

String(byte[] byte_arr)

Construct a new String by decoding the byte array. It uses the platform’s default character set for decoding.

String(byte[] byte_arr, Charset char_set)

Construct a new String by decoding the byte array. It uses the char_set for decoding.

String(byte[] byte_arr, int start_index, int length)

Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).

String(byte[] byte_arr, int start_index, int length, Charset char_set)

Construct a new string from the bytes array depending on the start_index(Starting location) and length(number of characters from starting location).Uses char_set for decoding.

String(char[] char_arr)

Allocates a new String from the given Character array.

String(char[] char_array, int start_index, int count)

Allocates a String from a given character array but choose count characters from the start_index.

String(int[] uni_code_points, int offset, int count)

Allocates a String from a uni_code_array but choose count characters from the start_index.

String(StringBuffer s_buffer)

Allocates a new string from the string in s_buffer.

String(StringBuilder s_builder)

Allocates a new string from the string in s_builder.

Let us check these constructors using a example demonstrating the use of them.

Example String Constructor in Java

Java
// Java Program to implement String Constructor import java.nio.charset.Charset;  class Geeks {          // Variables in Methods     static byte[] b_arr = {71, 101, 101, 107, 115};     static Charset cs = Charset.defaultCharset();     static char[] char_arr = {'G', 'e', 'e', 'k', 's'};     static int[] uni_code = {71, 101, 101, 107, 115};     static StringBuffer s_buffer = new StringBuffer("Geeks");     static StringBuilder s_builder = new StringBuilder("Geeks");      public static void main(String[] args) {                  // Method 1         String s1 = new String(b_arr);         System.out.println("Method 1: " + s1);         System.out.println();          // Method 2         String s2 = new String(b_arr, cs);         System.out.println("Method 2: " + s2);         System.out.println();          // This is alternative way for Method 2         String s3 = new String(b_arr, Charset.forName("US-ASCII"));         System.out.println("Method 2 Alternative: " + s3);         System.out.println();          // Method 3         String s4 = new String(b_arr, 1, 3);         System.out.println("Method 3: " + s4);         System.out.println();          // Method 4         String s5 = new String(b_arr, 1, 3, cs);         System.out.println("Method 4: " + s5);         System.out.println();          // This is alternative way for Method 4         String s6 = new String(b_arr, 1, 4, Charset.forName("US-ASCII"));         System.out.println("Method 4 Alternative: " + s6);         System.out.println();          // Method 5         String s7 = new String(char_arr);         System.out.println("Method 5: " + s7);         System.out.println();          // Method 6         String s8 = new String(char_arr, 1, 3);         System.out.println("Method 6: " + s8);         System.out.println();          // Method 7         String s9 = new String(uni_code, 1, 3);         System.out.println("Method 7: " + s9);         System.out.println();          // Method 8         String s10 = new String(s_buffer);         System.out.println("Method 8: " + s10);         System.out.println();          // Method 9         String s11 = s_builder.toString();         System.out.println("Method 9: " + s11);         System.out.println();     } } 

Output
Method 1: Geeks  Method 2: Geeks  Method 2 Alternative: Geeks  Method 3: eek  Method 4: eek  Method 4 Alternative: eeks  Method 5: Geeks  Method 6: eek  Method 7: eek  Method 8: Geeks  Method 9: Geeks...


String Methods in Java

String Methods

Description

int length()

Returns the number of characters in the String.

Char charAt(int i)

Returns the character at ith index.

String substring (int i)

Return the substring from the ith  index character to end.

String substring (int i, int j)

Returns the substring from i to j-1 index.

String concat( String str)

Concatenates specified string to the end of this string.

int indexOf (String s)

Returns the index within the string of the first occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.

int indexOf (String s, int i)

Returns the index within the string of the first occurrence of the specified string, starting at the specified index.

Int lastIndexOf( String s)

Returns the index within the string of the last occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.

boolean equals( Object otherObj)

Compares this string to the specified object.

boolean  equalsIgnoreCase (String anotherString)

Compares string to another string, ignoring case considerations.

int compareTo( String anotherString) 

Compares two string lexicographically.

int compareToIgnoreCase( String anotherString) 

Compares two string lexicographically, ignoring case considerations.

Note: In this case, it will not consider case of a letter (it will ignore whether it is uppercase or lowercase).

String toLowerCase()

Converts all the characters in the String to lower case.

String toUpperCase()

Converts all the characters in the String to upper case.

String trim()

Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle.

String replace (char oldChar, char newChar)

Returns new string by replacing all occurrences of oldChar with newChar.

Note: s1 is still feeksforfeeks and s2 is geeksgorgeeks

boolean contains(CharSequence sequence)

Returns true if string contains contains the given string.

Char[] toCharArray():

Converts this String to a new character array.

boolean startsWith(String prefix)

Return true if string starts with this prefix.


Example of String Constructor and String Methods

Below is the implementation of string constructors and methods in Java.

Java
// Java program to illustrate different  // constructors and methods in String class import java.io.*; import java.util.*;  class Geeks {     public static void main (String[] args)     {         String s= "GeeksforGeeks";         // or String s= new String ("GeeksforGeeks");          // Returns the number of characters in the String         System.out.println("String length = " + s.length());          // Returns the character at ith index         System.out.println("Character at 3rd position = "                            + s.charAt(3));          // Return the substring from the ith  index character         // to end of string         System.out.println("Substring " + s.substring(3));          // Returns the substring from i to j-1 index         System.out.println("Substring  = " + s.substring(2,5));          // Concatenates string2 to the end of string1         String s1 = "Geeks";         String s2 = "forGeeks";         System.out.println("Concatenated string  = " +                             s1.concat(s2));          // Returns the index within the string         // of the first occurrence of the specified string         String s4 = "Learn Share Learn";         System.out.println("Index of Share " +                            s4.indexOf("Share"));          // Returns the index within the string of the         // first occurrence of the specified string,         // starting at the specified index         System.out.println("Index of a  = " +                            s4.indexOf('a',3));          // Checking equality of Strings         Boolean out = "Geeks".equals("geeks");         System.out.println("Checking Equality  " + out);         out = "Geeks".equals("Geeks");         System.out.println("Checking Equality  " + out);          out = "Geeks".equalsIgnoreCase("gEeks ");         System.out.println("Checking Equality " + out);          // If ASCII difference is zero then          // the two strings are similar         int out1 = s1.compareTo(s2);         System.out.println("the difference between ASCII value is="+out1);                  // Converting cases         String w1 = "GeeKyMe";         System.out.println("Changing to lower Case " +                             w1.toLowerCase());          // Converting cases         String w2 = "GeekyME";         System.out.println("Changing to UPPER Case " +                             w2.toUpperCase());          // Trimming the word         String w4 = " Learn Share Learn ";         System.out.println("Trim the word " + w4.trim());          // Replacing characters         String str1 = "feeksforfeeks";         System.out.println("Original String " + str1);         String str2 = "feeksforfeeks".replace('f' ,'g') ;         System.out.println("Replaced f with g -> " + str2);     } } 

Output:

Output


For Set -2, you can refer: Java.lang.String class in Java | Set 2



Next Article
StringBuffer Class in Java

R

Rahul Agrawal
Improve
Article Tags :
  • Java
  • Java-lang package
  • Java-Strings
Practice Tags :
  • Java
  • Java-Strings

Similar Reads

    Basics of Java

    • If you are new to the world of coding and want to start your coding journey with Java, then this learn Java a beginners guide gives you a complete overview of how to start Java programming. Java is among the most popular and widely used programming languages and platforms. A platform is an environme
      10 min read

    • Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible. It is intended to let application developers Write Once and Run Anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java without the
      9 min read

    • Nowadays Java and C++ programming languages are vastly used in competitive coding. Due to some awesome features, these two programming languages are widely used in industries as well as comepetitive programming . C++ is a widely popular language among coders for its efficiency, high speed, and dynam
      6 min read

    • In the journey to learning the Java programming language, setting up environment variables for Java is essential because it helps the system locate the Java tools needed to run the Java programs. Now, this guide on how to setting up environment variables for Java is a one-place solution for Mac, Win
      6 min read

    • Java is an object-oriented programming language that is known for its simplicity, portability, and robustness. The syntax of Java programming language is very closely aligned with C and C++, which makes it easier to understand. Java Syntax refers to a set of rules that define how Java programs are w
      6 min read

    • Java is one of the most popular and widely used programming languages and platforms. In this article, we will learn how to write a simple Java Program. This article will guide you on how to write, compile, and run your first Java program. With the help of Java, we can develop web and mobile applicat
      6 min read

    • Understanding the difference between JDK, JRE, and JVM plays a very important role in understanding how Java works and how each component contributes to the development and execution of Java applications. The main difference between JDK, JRE, and JVM is: JDK: Java Development Kit is a software devel
      4 min read

    • JVM(Java Virtual Machine) runs Java applications as a run-time engine. JVM is the one that calls the main method present in a Java code. JVM is a part of JRE(Java Runtime Environment). Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one s
      7 min read

    • An identifier in Java is the name given to Variables, Classes, Methods, Packages, Interfaces, etc. These are the unique names used to identify programming elements. Every Java Variable must be identified with a unique name. Example: public class Test{ public static void main(String[] args) { int a =
      2 min read

    Variables & DataTypes in Java

    • In Java, variables are containers that store data in memory. Understanding variables plays a very important role as it defines how data is stored, accessed, and manipulated. Key Components of Variables in Java: A variable in Java has three components, which are listed below: Data Type: Defines the k
      9 min read

    • The scope of variables is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers are lexically (or statically) scoped, i.e., scope of a variable can be determined at compile time and independent of the function call stack. In this article, we will learn about
      7 min read

    • Java is statically typed and also a strongly typed language because each type of data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be declared with the specifi
      15 min read

    Operators in Java

    • Java operators are special symbols that perform operations on variables or values. These operators are essential in programming as they allow you to manipulate data efficiently. They can be classified into different categories based on their functionality. In this article, we will explore different
      15 min read

    • Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they
      6 min read

    • Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they
      7 min read

    • Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions be it logical, arithmetic, relational, etc. They are classified based on the functionality they p
      8 min read

    • Operators constitute the basic building block to any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they
      10 min read

    • Logical operators are used to perform logical "AND", "OR", and "NOT" operations, i.e., the functions similar to AND gate and OR gate in digital electronics. They are used to combine two or more conditions/constraints or to complement the evaluation of the original condition under particular consider
      8 min read

    • Operators constitute the basic building block of any programming language. Java provides many types of operators that can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provi
      5 min read

    • In Java, Operators are special symbols that perform specific operations on one or more than one operands. They build the foundation for any type of calculation or logic in programming. There are so many operators in Java, among all, bitwise operators are used to perform operations at the bit level.
      6 min read

    Packages in Java

    • Packages in Java are a mechanism that encapsulates a group of classes, sub-packages, and interfaces. Packages are used for: Prevent naming conflicts by allowing classes with the same name to exist in different packages, like college.staff.cse.Employee and college.staff.ee.Employee.They make it easie
      9 min read

    Flow Control in Java

    • Decision-making statements in Java execute a block of code based on a condition. Decision-making in programming is similar to decision-making in real life. In programming, we also face situations where we want a certain block of code to be executed when some condition is fulfilled. A programming lan
      10 min read

    • The Java if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e. if a certain condition is true then a block of statements is executed otherwise not. Example: [GFGTABS] Java // Java program to ill
      5 min read

    • The if-else statement in Java is a powerful decision-making tool used to control the program's flow based on conditions. It executes one block of code if a condition is true and another block if the condition is false. In this article, we will learn Java if-else statement with examples. Example: [GF
      4 min read

    • The Java if-else-if ladder is used to evaluate multiple conditions sequentially. It allows a program to check several conditions and execute the block of code associated with the first true condition. If none of the conditions are true, an optional else block can execute as a fallback. Example: The
      3 min read

    Loops in Java

    • Looping in programming languages is a feature that facilitates the execution of a set of instructions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition
      7 min read

    • Java for loop is a control flow statement that allows code to be executed repeatedly based on a given condition. The for loop in Java provides an efficient way to iterate over a range of values, execute code multiple times, or traverse arrays and collections. Now let's go through a simple Java for l
      5 min read

    • Java while loop is a control flow statement used to execute the block of statements repeatedly until the given condition evaluates to false. Once the condition becomes false, the line immediately after the loop in the program is executed. Let's go through a simple example of a Java while loop: [GFGT
      3 min read

    • Java do-while loop is an Exit control loop. Unlike for or while loop, a do-while check for the condition after executing the statements of the loop body. Example: [GFGTABS] Java // Java program to show the use of do while loop public class GFG { public static void main(String[] args) { int c = 1; //
      4 min read

    • The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required. Example: Using a for-each l
      8 min read

    Jump Statements in Java

    • In Java, the continue statement is used inside the loops such as for, while, and do-while to skip the current iteration and move directly to the next iteration of the loop. Example: [GFGTABS] Java // Java Program to illustrate the use of continue statement public class Geeks { public static void mai
      4 min read

    • The Break Statement in Java is a control flow statement used to terminate loops and switch cases. As soon as the break statement is encountered from within a loop, the loop iterations stop there, and control returns from the loop immediately to the first statement after the loop. Example: [GFGTABS]
      3 min read

    • return keyword in Java is a reserved keyword which is used to exit from a method, with or without a value. The usage of the return keyword can be categorized into two cases: Methods returning a valueMethods not returning a value1. Methods Returning a ValueFor the methods that define a return type, t
      4 min read

    Arrays in Java

    • Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
      15+ min read

    • Multidimensional arrays are used to store the data in rows and columns, where each row can represent another individual array are multidimensional array. It is also known as array of arrays. The multidimensional array has more than one dimension, where each row is stored in the heap independently. T
      10 min read

    • In Java, Jagged array is an array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D array but with a variable number of columns in each row. Example: arr [][]= { {1,2}, {3,4,5,6},{7,8,9}}; So, here you can check that the number of columns in row1!=row2!=row3. Tha
      5 min read

    Strings in Java

    • In Java, a String is the type of object that can store a sequence of characters enclosed by double quotes, and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array of characters. Java provides a robust and flexible API for handling strings, allowi
      10 min read

    • A string is a sequence of characters. In Java, objects of the String class are immutable, which means they cannot be changed once created. In this article, we are going to learn about the String class in Java. Example of String Class in Java: [GFGTABS] Java // Java Program to Create a String import
      7 min read

    • The StringBuffer class in Java represents a sequence of characters that can be modified, which means we can change the content of the StringBuffer without creating a new object every time. It represents a mutable sequence of characters. Features of StringBuffer ClassThe key features of StringBuffer
      11 min read

    • In Java, the StringBuilder class is a part of the java.lang package that provides a mutable sequence of characters. Unlike String (which is immutable), StringBuilder allows in-place modifications, making it memory-efficient and faster for frequent string operations. Declaration: StringBuilder sb = n
      7 min read

    OOPS in Java

    • Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable. The core idea of OOPs is to bind data and the functions that operate on it,
      13 min read

    • In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
      12 min read

    • Java Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java must belong to a class. Methods are similar to functions and expose the behavior of objects. Example: Java program to demonstrate how to cre
      8 min read

    • In Java, access modifiers are essential tools that define how the members of a class, like variables, methods, and even the class itself can be accessed from other parts of our program. They are an important part of building secure and modular code when designing large applications. Understanding de
      7 min read

    • A Wrapper class in Java is one whose object wraps or contains primitive data types. When we create an object in a wrapper class, it contains a field, and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let's check on the wr
      6 min read

    • Firstly the question that hits the programmers is when we have primitive data types then why does there arise a need for the concept of wrapper classes in java. It is because of the additional features being there in the Wrapper class over the primitive data types when it comes to usage. These metho
      3 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences