×

String Handling Method in Java

What is a String?

Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language.

“String” is a Java platform class that allows you to construct and handle strings.

Creating String:

The normal way of a creating String in Java is to simply write:

String s = “Hello World”;

The compiler constructs a String object with the value "Hello world!" whenever it detects a string phrase in your code.

String objects cannot be made by using the new keyword and a function Object, just like any other object. The String class provides 11 constructors that allow you to set the string's initial value from a variety of sources, including an array of characters.

Another way of a creating String is:

String s = new String (“Hello World”);

Where is String Object stored?

When a string object is generated, it is placed in a pool of Strings known as the String pool, which is then stocked in Java's heap memory.

To be accurate, the Java String class implements three different interfaces: CharSequence, Comparable, and Serializable.

String class is a subclass of the Object class

Because strings are immutable, anytime we change one string a new string is formed. Java provides us with many service classes called StringBuilder and StringBuffer that allow us to generate mutable strings.

As we've seen, String in Java is a class, so it's no surprise that it has a large range of methods connected with it.

String Handling Method

charAt (int index):

This method helps in returning the character value at the particular index.

Example:

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

Output:

E

equals (Object obj):

This method returns a Boolean value, indicating if the comparing string matches or not.

Example:

public class EqualsSample{ 
           public static void main(String args[]){ 
 
                   String s1="java"; 
                   String s2="java"; 
                   String s3="string"; 
 
                   System.out.println(s1.equals(s2));
                   System.out.println(s1.equals(s3)); 
            }
}

Output:

True
False

compareTo(String certainString):

This is a Comparable interface method that the String class implements. It is used to compare a string to the one currently in use string. As a consequence of the comparison, the method returns a value of 0 or a positive or negative number.

  • When both the strings are equal it returns 0.
  • If string 1st is less than string 2nd it returns negative.
  • If string 1st is greater than string 2nd it returns positive.

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 1 time greater than "r"
 
           System.out.println(s1.compareTo(s4)); 
           // -3 because "t" is 3 times lower than "w"
           }
 }

Output:

0
1
-3

Length():

This method returns an integer value that shows the full length of the String.

Example:

public class EqualsSample{ 
         public static void main(String args[]){ 
 
                 String s1="helloworld "; 
                 String s2="hello";  
 
                 System.out.println(s1.length()); 
                 // 10 is the length of helloworld string
 
                 System.out.println(s2.length()); 
                 //5 is the length of hello string
          }
}

Output:

10
5

replace(char oldLetter, char newLetter) :

This method returns a new string in which the old character is replaced by the new character in all of the string's occurrences.

Example:

public class EqualsSample{ 
          public static void main(String args[]){ 
 
                   String s1="swap";
                   String s2 = replace(“w”,”n”); 
 
                   System.out.println(s2);
          }
}

Output:

Snap

toLowerCase():

This method changes all the characters in the strings into lowercase.

Example:

public class ToLowerCaseSample{ 
            public static void main(String args[]){ 
 
                  String s1="HELLO WORLD"; 
                  String s2 = s1.toLowerCase(s1);
 
                  System.out.println(s2);
            }
}

Output:

hello world

toUpperCase():

This method changes all the characters in the strings into upper case.

Example :

public class ToUpperCaseSample{ 
           public static void main(String args[]){ 
 
                  String s1="helloworld "; 
                  String s2 = s1.toUpperCase(s1);
 
                  System.out.println(s2);
           }
 }

Output:

HELLOWORLD

concat(String newString):

This produces a new concatenated string with a new string appended to the end of the previous one. The mark on a string is the new string.

Example:

public class ConcatSample{ 
          public static void main(String args[]){ 
 
                   String s1="Welcome to"; 
                   String s2 =”my world”;
                   String s3 = s1.concat(s2);
                    
                   System.out.println(s3);
           }
}

Output:

Welcome to my world

trim():

This function produces a string that is devoid of the leading and following whitespaces found in the original string.

Example:

public class TrimSample{ 
            public static void main(String args[]){ 
 
                  String s1="      My name is          ";  
 
                  System.out.println(s1 +”:Thomson”);
                  System.out.println(s1.trim() +”:Thomson”);
             }
}

Output:

My name is          :Thomson
My name is Thomson

split():

After breaking the input string against the specified regular expression, this method provides a character array.

Example:

public class SplitSample{ 
         public static void main(String args[]){ 
 
                String s1="Hey I Am John"; 
                String [] s2 = s1.split(“\\s”); 
                //splits based on whitespace
 
                 for(String word: s2){
                          System.out.println(s2);
                 }
          }
}

Output:

Hey
I
Am
John

valueOf():

This method converts several types to String, such as integer to string, long to string, Boolean to string, float to string, and so on.

Example:

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


                float value = 89;
                String s1 = String.valueOf(value);
 
                System.out.println(s1+”%”); 
                //concatenating the obtained string
          }
}


Output:

89%

These are the various types of String handling program methods in Java. The String class isn't limited to the methods listed above; it contains a slew of other handy methods that can make programming a breeze.


Related Topics

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Zig Zag star and Number Pattern in Java

We covered many Java pattern applications in the preceding part. We will write Java applications for zigzag star and number patterns in this part. Printing Zig Zag Number Pattern Steps Print one...

3 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.

Java vs DotNET

Before understanding the differences between DotNET and Java, one must know about Java and DotNET. Java Java is a general-purpose programming language that is class-based and object-oriented, with minimal implementation dependencies. Regardless of...

9 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Heart Pattern in Java

Heart Pattern is yet another intricate pattern program, however, due to its complexity, interviewers hardly ever inquire about it. Method for Printing the Heart Number Pattern Put the value of the total row...

2 minutes read.

Java file Reader

File Reader: It is used to read the data from files. This class inherits the properties from Input Stream Reader Class. File Reader is for reading characters from the file. Input Stream: Java.io...

4 minutes read.

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included....

4 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

Java Math log() Method

The log() method of Math class returns the natural logarithmic value for the specified double argument. Syntax: public static double log(double a) Parameters: The parameter ‘a’ represents the value. Return Value: The log() method returns the...

1 minute read.