Java Programming 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 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 Programming 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 Programming Gets Current Date

Java Programming Finds Character Vowel or Consonent

Java Programming HCF and LCM Computation

Java Programming Sum of Command Line Integer Arguments

Java Programming Multiplication of Command Line Integer Arguments

Java Programming Multiplication of Command Line Floating Point Numeric Arguments

Java Programming String Contains or Not

Java Programming Gets Grade Description using Switch

Java Programming CSV File Reader

Java Programming Character Frequency Count in String using for each

Java Programming Finds Min from Integer Array by Passing Array to Method

Java Programming Linear Search

Java Programming Binary Search

Java Programming Ternary Search

Java Programming Generates Range of Numbers

Java Programming Generates Range of Characters

Java Programming Computes Square Root Value

Java Programming Checks Number is Positive or Negative

Java Programming Checks Number is Odd or Even

Java Programming Computes Plot Area

Java Programming Convert Number of Days into Years

Java Programming Checks a Year is Leap Year, Century Year or Not

Java Programming Checks a Character is Digit, Letter or neither digit nor letter

Java Programming Checks a Number is Palindrome or not

Java Programming Sum of Two Matrix

Java Programming Power Computation

Java Programming Checks Number is an Armstrong Number or not

Java Programming Temperature Unit Conversions

Java Programming Generates Random Numbers in Specified Range

Java Programming Computes Sum of Digits and Product of Digits

Java Programming Computes Reverse Number

Java Programming Computes Factorial Value

Java Programming Checks Prime Number or not

Java Programming Computes Harmonic Series

Java Programming Generates Floyd's Triangle

Java Programming Reverses String

Java Programming Checks Palindrome String or not

Java Programming Opens Notepad

Java Programming Searches String using RegEx Pattern

Java Programming Searches Word in String

Java Programming Gets System Environment Variables

Java Programming Gets IP Address of Server Name

Java Programming Arrays Sort and Reverse using sort method

Java Programming Bubble Sorting

Java Programming Selection Sorting

Java Programming Insertion Sorting

Java Programming Merge Sorting

Java Programming Quick Sorting

Java Programming Counting Sort

Java Programming Radix Sorting

Java Programming Sorting Array of Strings

Java Programming String Characters Sorting

Java Programming Sum of First N Numbers

Java Programming Product of First N Numbers

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^