• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

Java String Handling Program Methods [Coding Examples Explained]

Pranati Paidipati/21483/5
CodeJAVA

In the previous tutorial, we have learned the basic object-oriented programming concepts and have built a base in Java. Now, moving ahead, we will be discussing a new section in Java, String Handling in Java.

We will cover following topics related to String Handling in Java Programming.

Post Content

  • What is String in Java?
  • How to Create String in Java? (Syntax)
  • Where is the String object stored?
  • Java String Methods (Explained with Code Example):
    • charAt()
    • compareTo()
    • equals()
    • length()
    • replace()
    • toLowerCase()
    • toUpperCase()
    • trim()
    • concat()
    • split()
    • valueOf()

 

What is String?

In computer science, a string is a series of characters, which are either a literal or some variable, for example, “Happy” is a string of 5 characters.

But in Java, strings are observed as objects that represent a sequence of characters of String class type. The String class is a wrapper class in java.lang.String package.

A string once created cannot be modified, i.e., a string is immutable.

How to create a String in Java?

In Java, a string object can be created using two varied ways, namely –

  1. Using String literal
  2. Using ‘new’ keyword

1. Using String literal:

A String literal in Java is created using double quotes and assigning this literal to an instance.

For example (Syntax):

String example = “Happy Learning” ;

2. Using ‘new’ keyword:

Here, we use the new keyword to create a String instance.

For example (Syntax):

String example = new String (“Happy Learning”);

This way of creating a string in Java creates 2 objects- one in the String constant pool (if the example doesn’t exist in the constant pool) and one in the memory heap.

Where is the String object stored?

As a string object is created, it is stored in a pool of Strings called the String pool which is in turn stocked up in the heap memory of Java.

Java string object stored in string pool

Fig: Storing of String Objects in Java

Moving ahead, Java String class implements 3 varies interfaces, to be precise- CharSequence, Serializable, and Comparable.

The Object class is the superclass of String class. As we have seen prior, Strings are immutable, thus whenever we mutate a string a new string gets created. To create a mutable string, Java makes us available with service classes, namely – StringBuilder and StringBuffer.

Java string class interfaces

 

As we have learned that, String in Java is a class, and thereby it is obvious that it has wide-ranging methods associated with it.

Java String Handling Program Methods

Let’s sneak peek into some of the frequently used methods allied with the String class.

#1 charAt (int index)

This method returns the character value at the specified index.

Example:

public class CharAtSample{
           public static void main(String args[]){
                       String sample = “csestack.org”;
                       char ch1 = sample.charAt(4);
                       System.out.println(ch1);
           }
}

Output :

t

#2 compareTo(String certainString) :

This is a method of Comparable interface and is implemented by the String class. It is used to compare a certain string to the current string. As a result, the method returns 0, positive or negative value after comparison.

  • 0 when both strings are equal
  • positive if string s1 is greater than string s2
  • negative if string s1 is less than string s2.

Example:

public class CompareToSample{ 
           public static void main(String args[]){ 
           String s1="string"; 
           String s2="string"; 
           String s3="ring"; 
           String s4="swing"; 

           System.out.println(s1.compareTo(s2));
           //0 because both are equal 

           System.out.println(s1.compareTo(s3));
           //1 because "s" is 1x greater than "r"

           System.out.println(s1.compareTo(s4)); 
           // -3 because "t" is 3x lower than "w"
           }
 }

Output:

0
1
-3

#3 equals (Object obj) :

This method returns a Boolean value, i.e. true if the comparing string is matching and false if it doesn’t.

Example:

public class EqualsSample{ 
           public static void main(String args[]){ 

                   String s1="string"; 
                   String s2="string"; 
                   String s3="swing"; 

                   System.out.println(s1.equals(s2));
                   //true because both are equal 

                   System.out.println(s1.equals(s3)); 
                   //false because both are not equal
            }
}

Output:

True
False

#4 length( ) :

This method returns an integer value that specifies the complete length of the string.

Example:

public class EqualsSample{ 
         public static void main(String args[]){ 

                 String s1="Happy "; 
                 String s2="Learning";  

                 System.out.println(s1.length()); 
                 // 5 is the length of happy string

                 System.out.println(s2.length()); 
                 //8 is the length of learning string
          }
}

Output:

5
8

#5 replace(char oldLetter, char newLetter) :

This method returns a new string where all the occurrences of the old character are replaced by the new character in the string.

Example:

public class EqualsSample{ 
          public static void main(String args[]){ 

                   String s1="string";
                   String s2 = replace(“t”,”w”); 

                   System.out.println(s2);
          }
}

Output:

swing

#6 toLowerCase ( ) :

This method converts all the characters in the string into lower case.

Example:

public class ToLowerCaseSample{ 
            public static void main(String args[]){ 

                  String s1="HAPPY LEARNING"; 
                  String s2 = s1.toLowerCase(s1);

                  System.out.println(s2);
            }
}

Output:

happy learning

#7 toUpperCase () :

This method converts all the characters in the string into uppercase.

Example:

public class ToUpperCaseSample{ 
           public static void main(String args[]){ 

                  String s1="happy learning"; 
                  String s2 = s1.toUpperCase(s1);

                  System.out.println(s2);
           }
 }

Output:

HAPPY LEARNING

#8 trim ( ):

This method returns a string that omits the leading and trailing whitespaces present in the actual string.

Example:

public class TrimSample{ 
            public static void main(String args[]){ 

                  String s1="      Happy Learning          ";  

                  System.out.println(s1 +”:csestack.org”);
                  System.out.println(s1.trim() +”:csestack.org”);
             }
}

Output:

      Happy Learning          :csestack.org
Happy Learning:csestack.org

#9 concat(String newString):

This returns a new concatenated string which has a new string placed right at the end of the old string. The new string is the tagged on a string.

Example:

public class ConcatSample{ 
          public static void main(String args[]){ 

                   String s1="Welcome to"; 
                   String s2 =” csestack.org !!”;
                   String s3 = s1.concat(s2);
                   
                   System.out.println(s3);
           }
}

Output:

Welcome to csestack.org !!

#10 split( ):

This method returns a character array after splitting the given string against the specified regular expression.

Example:

public class SplitSample{ 
         public static void main(String args[]){ 

                String s1="Maths:25 English:23 Science:22"; 
                String [] s2 = s1.split(“\\s”); 
                //splits based on whitespace

                 for(String word: s2){
                          System.out.println(s2);
                 }
          }
}

Output:

Maths:25
English:23
Science:22

#11 valueOf ( ):

This method is used to convert the varied types into String, like int to string, long to string, Boolean to string, float to string, etc.

Example:

public class ValueOfSample{ 
         public static void main(String args[]){

                float value = 11.50;
                String s1 = String.valueOf(value);

                System.out.println(s1+”%”); 
                //concatenating the obtained string
          }
}

Output:

11.50%

These are thee different types of Java String handling program methods. The String class doesn’t limit itself to the above-mentioned methods, it has many more useful methods that could make programming easy. Try using few of the String methods, and enjoy coding.

Happy Learning !!


« Basic Data Types in JavaJava Operators in Detail »

Javajava string
Pranati Paidipati
I am a graduate in computer science with a creative bent of mind for writing content. With great gusto, I enjoy learning new things. I trail in database management system, and object-oriented programming languages like Java, C/C++.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Ameya acharya
    January 7, 2018 at 5:17 pm

    Very well explained Pranati 🙂

    • Reply
      Pranati
      February 1, 2018 at 11:57 am

      Thank you so much 🙂

  • Reply
    Ridhima
    June 19, 2020 at 7:26 pm

    Thank You very much mam

  • Reply
    Diljit
    November 10, 2020 at 11:21 am

    Very good explanation. I have got 100% clarity.

  • Reply
    Cathy Kelly
    April 4, 2021 at 8:26 am

    Hi,
    I just found your website. I love it! Keep up the incredible work!
    Cathy

Leave a Reply Cancel reply

Basic Java Tutorial

  1. Java- Tutorial Overview
  2. Java- Features & Characteristics
  3. Java-  Installation & Setup
  4. Java- Hello, World Program!
  5. Java- JDK vs JVM vs JRE
  6. Java- Data Types & Variables
  7. Java- String & its Methods
  8. Java- Different Operators Types
  9. Java- Flow Control Statements
  10. Java- Exception Handling
  11. Java- ‘throw’ vs ‘throws’ Keyword
  12. Java- RegEx
  13. Java 12- New Advanced Features

Java OOPs concepts

  1. Java- OOPs Introduction
  2. Java- Classes & Objects
  3. Java- Constructor & Overloading
  4. Java- Method Overload vs Override
  5. Java- Access Modifiers
  6. Java- Abstraction
  7. Java- Inheritance
  8. Java- Interfaces
  9. Java- Nested Inner Classes

Java Advanced

  1. Java- Applet vs Application
  2. Java- HashMap Collections
  3. Java- ArrayList
  4. Java- HashSet
  5. Java- HashMap vs HashSet
  6. Java- Reverse Linked List

Java Exercise

50+ Java Coding Questions [Practice]

Java Projects

Patient Billing Software

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard