×

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

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Java If Keyword

Definition: The if statement specifies a section of Java code that will run if an if statement's condition is false. The following conditional statements can be used in Java: To provide a block...

3 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.