Java Strings Methods

What is string in java?

String is a sequence of characters, String class is available in java to create and manipulate strings. Simple way to create string
String str = "input string!";
String is also array of characters. String class has multiple constructors to create string object. character array in String constructor.
char[] chars = {'i', 'n', 'p', 'u', 't', ' ', 's', 't', 'r', 'i', 'n', 'g', '!'};
String str = new String(chars);

Java Programming Language String Methods

This page explains some of the functionalities of strings and example programs.

Equal Check in Strings

public class JavaString1 {                                                                                                                                    
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     char[] chars = {'i', 'n', 'p', 'u', 't', ' ', 's', 't', 'r', 'i', 'n', 'g', '!'};
     String str1 = new String(chars);                                           
     if(str == str1) {                                                          
       System.out.println("Strings are matched!");                              
     } else {                                                                   
       System.out.println("Strings are not matched!");                          
     }                                                                          
   }                                                                            
}      
'==' is legal in most programming languages but it's wrong in java for string equal comparison. Output:
$ java JavaString1
Strings are not matched!
Correct way to check equal comparison between strings.
public class JavaString1 {                                                                                                                                    
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     char[] chars = {'i', 'n', 'p', 'u', 't', ' ', 's', 't', 'r', 'i', 'n', 'g', '!'};
     String str1 = new String(chars);                                           
     if(str.equals(str1)) {                                                     
       System.out.println("Strings are matched!");                              
     } else {                                                                   
       System.out.println("Strings are not matched!");                          
     }                                                                          
   }                                                                            
}      
Output:
$ java JavaString1
Strings are matched!

String length method

length method is used to get number of characters in a string.
public class JavaString2 {                                                                                                                                     
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("String Length: " + str.length());                      
   }                                                                            
}   
Output:
$ java JavaString2
String Length: 13

Strings Concatenation

concat method or + operator is used for string concatenation.
string1.concat(string2);
or
string3 = string1 + string2;
string1 += string2;
public class JavaString2 {                                                      
                                                                                
   public static void main(String args[]) {                                     
     String str1 = "input ";                                                    
     String str2 = "string!";                                                   
     System.out.println("Concatenated Strings way1: " + str1.concat(str2));     
     System.out.println("Concatenated Strings way2: " + (str1 + str2));         
   }                                                                            
}  
Output:
$ java JavaString2
Concatenated Strings way1: input string!
Concatenated Strings way2: input string!

Getting a character using index in string

public class JavaString2 {                                                                                                                                    
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("Char at index 2: " + str.charAt(2));                   
   }                                                                            
}    
Output:
$ java JavaString2
Char at index 2: p

Check string is starting with particular string

public class JavaString2 {                                                                                                                                     
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("Is string starts with 'ing!': " + str.startsWith("inp")); 
   }                                                                            
}                                                                               
Output:
$ java JavaString2
Is string starts with 'inp': true

Check string is ending with particular string

public class JavaString2 {                                                                                                                                     
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("Is string ends with 'ing!': " + str.endsWith("ing!")); 
   }                                                                            
}                                                                               
Output:
$ java JavaString2
Is string ends with 'ing!': true

Getting first identified index for character or string from left to right (starting index 0 default) in a string

int indexOf(String str)
int indexOf(char ch)
int indexOf(int ch)
public class JavaString2 {                                                                                                                                   
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("index of character 's' in string " + str.indexOf("s"));
   }                                                                            
}  
Output:
$ java JavaString2
index of character 's' in string 6

Getting index of a character or string and search starting from specified index

int indexOf(String str, int fromIndex)
int indexOf(char ch, int fromIndex)
int indexOf(int ch, int fromIndex)
if character is not found in string, -1 will be returned.
public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("index of character 'n' in string " + str.indexOf("n", 4));
   }                                                                            
}  
Output:
$ java JavaString2
index of character 's' in string 10

Character specified in integer format

public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("index of character 88 in string " + str.indexOf(88, 4));
   }                                                                            
} 
Output:
$ java JavaString2
index of character 's' in string -1

String lastIndexOf method

This method is same as indexOf and only difference is reverse order(right to left).
public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("last index of character 'n' in string " + str.lastIndexOf("n"));
   }                                                                            
} 
Output:
$ java JavaString2
last index of character 'n' in string 10
Using from last index:
public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("last index of character 'n' in string " + str.lastIndexOf("n", 9));
   }                                                                            
}  
Output:
$ java JavaString2
index of character 's' in string 1

String trim method

Removes leading and trailing empty spaces in string.
public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = " input string!  ";                                           
     System.out.println("string after trim: " + str.trim());                    
   }                                                                            
}                                                                               
Output:
$ java JavaString2
string after trim: input string!

String replace method

Replacing all substring (part of character, part of string or string) with another string in a string.
public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("string after replaced substring: " + str.replace("string", "text"));
   }                                                                            
}    
Output:
$ java JavaString2
string after replaced substring: input text!
public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("string after replaced substring: " + str.replace('t', 'q'));
   }                                                                            
}   
Output:
$ java JavaString2
string after replaced substring: inpuq sqring!

String replace first occurence only

Replace first occurence of substring only in a string.
public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "input string!";                                              
     System.out.println("string after replaced first occurence substring: " + str.replaceFirst("t", "q"));
   }                                                                            
}     
Output:
$ java JavaString2
string after replaced first occurence substring: inpuq string!

Convert string into uppercase letters

public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "Input String!";                                              
     System.out.println("To upper case: " + str.toUpperCase());                 
   }                                                                            
}   
Output:
$ java JavaString2
To upper case: INPUT STRING!

Convert string into lowercase letters

public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "Input String!";                                              
     System.out.println("To lower case: " + str.toLowerCase());                 
   }                                                                            
}                                                                               
Output:
$ java JavaString2
To lower case: input string!

Getting Substring from specified index

public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "Input String!";                                              
     System.out.println("Substring starting from index '5': " + str.substring(4));
   }                                                                            
} 
Output:
$ java JavaString2
Substring starting from index '5': t String!

Substring from starting index and ending index in a string

public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "Input String!";                                              
     System.out.println("Substring starting from index '5' ending index '7': " + str.substring(4, 7));
   }                                                                            
}  
Output:
$ java JavaString2
Substring starting from index '5' ending index '7': t S

Converting string into characters array

public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "Input String!";                                              
     System.out.println("String into char array: " + str.toCharArray()[6]);     
   }                                                                            
}   
Output:
$ java JavaString2
String into char array: S

String split method

public class JavaString2 {                                                      
   public static void main(String args[]) {                                     
     String str = "Input String!";                                              
     String[] arr = str.split(" ");                                             
     for(int i=0; i<arr.length; i++) {                                        
      System.out.println("index '" + Integer.toString(i) + "': " + arr[i]);     
     }                                                                          
   }                                                                            
}   
Output:
$ java JavaString2
index '0': Input
index '1': String!

Java Examples

GCD and Rational Number Java Program

Java Queue Program using exception

Java Stack Program using exception

Addition of three integers java program

Biggest of three integers java program

Fibonacci numbers java program

Arithmetic Operations Menu java program

Second Smallest Element In Array Java Program

Transpose Of A Matrix Java Program

Java Program to Display triangle of stars (*)

Java Programming Prints Product Tables

Java Program to Display triangle of numbers

Java Program to Get Current Date

Java Program to Find Character Vowel or Consonent

Java Program to Compute HCF and LCM

Java Program to Sum the Command Line Integer Arguments

Java Programm to Multiply the Command Line Integer Arguments

Java Program to Find Multiplication of Command Line Floating Point Numeric Arguments

Java Program to Check String Contains or Not

Java Program to Get Grade Description using Switch

Java Program for CSV File Reader

Java Program to Find Character Frequency Count in String using for each

Java Program to Find Min from Integer Array by Passing Array to Method

Java Program Linear Search

Binary Search Java Program

Ternary Search Java Program

Java Program to Generate Range of Numbers

Java Program to Generate Range of Characters

Java Program to Compute Square Root Value

Java Program to Check Number is Positive or Negative

Java Program to Check Number is Odd or Even

Java Program to Compute Plot Area

Java Program to Convert Number of Days into Years

Java Program to Check a Year is Leap Year, Century Year or Not

Java Program to Check a Character is Digit, Letter or neither digit nor letter

Java Program to Check a Number is Palindrome or not

Java Program to Sum Two Matrix

Java Program to Compute Power

Java Program to Check Number is an Armstrong Number or not

Java Program for Temperature Unit Conversions

Java Program to Generate Random Numbers in Specified Range

Java Program to Compute Sum of Digits and Product of Digits

Java Program to Compute Reverse Number

Java Programming Computes Factorial Value

Java Programming Checks Prime Number or not

Java Program to Compute Harmonic Series

Java Program Generate Floyd's Triangle

Java Program to Reverse String

Java Program to Check Palindrome String or not

Java Program to Open Notepad

Java Program to Search String using RegEx Pattern

Java Program to Search Word in String

Java Program to Get System Environment Variables

Java Program to Get IP Address of Server Name

Java Program for Arrays Sorting and Reverse using sort method

Java Program for Bubble Sorting

Java Program for Selection Sorting

Java Program for Insertion Sorting

Java Program for Merge Sorting

Java Program for Quick Sorting

Java Program for Counting Sort

Java Program for Radix Sorting

Java Program for Sorting Array of Strings

Java Program for String Characters Sorting

Java Program to Sum First N Numbers

Java Program to Product First N Numbers

Java Program to get URL details

Java Program to get URL HTML Content

Java Program to get URL details

Java Program to get URL HTML Content

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^