Java String indexOf

The java string indexOf() method returns index of given character value or substring. If it is not found, it returns -1. The index counter starts from zero.

Signature

There are 4 types of indexOf method in java.

The signature of indexOf methods are given:
No.MethodDescription
1int indexOf(int ch)returns index position for the given char value
2int indexOf(int ch, int fromIndex)returns index position for the given char value and from index
3int indexOf(String substring)returns index position for the given substring
4int indexOf(String substring, int fromIndex)returns index position for the given substring and from index

Parameters

ch: char value i.e. a single character e.g. 'a'
fromIndex: index position from where index of the char value or substring is retured
substring: substring to be searched in this string

Returns

index of the string

Java String indexOf() method example

public class IndexOfExample{  
public static void main(String args[]){  
String s1="this is index of example";  
  //passing substring  
int index1=s1.indexOf("is");  //returns the index of is substring  
int index2=s1.indexOf("index"); //returns the index of index substring  
System.out.println(index1+"  "+index2);  //2 8  
  //passing substring with from index  
int index3=s1.indexOf("is",4);  //returns the index of is substring after 4th index  
System.out.println(index3);  //5 i.e. the index of another is  
 //passing char value  
int index4=s1.indexOf('s'); //returns the index of s char value  
System.out.println(index4); //3  
}}

Output:

2  8
5
3

Java String intern

The java string intern()method returns the interned string. It returns the canonical representation of string.
It can be used to return string from pool memory, if it is created by new keyword.

Signature

The signature of intern method is given:

public String intern()

Returns

interned string

Java String intern() method example

public class InternExample{  
public static void main(String args[]){  
String s1=new String("hello");  
String s2="hello";  
String s3=s1.intern(); //returns string from pool, now it will be same as s2  
System.out.println(s1==s2); //false because reference is different  
System.out.println(s2==s3); //true because reference is same  
}}        

Output:

false
true