Alphalearningschool
        

<<< Prev

Next >>>

Up
Java String

In java sequence of char is string. In java string is treated as object. An array of characters works same as java string.

For example: char[] ch={‘a’,’l’,’p’,’h’,’a’};

                                String s=new String(ch);        or we can write,    String s=”alpha”; 

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces. 

                          

CharSequence Interface:- The CharSequence interface is used to represent sequence of characters. We can create string in java by using three classes.              

 

What is String in java?

Sequence of character is called string. But in java, string is an object. To create string object we used java.lang.String class.

Way to create String object:

  1. By new keyword.
  2. By String literal.

1.By new keyword – whenever we use new keyword to create string jvm creates a new string object in heap memory. See pictorial representation to clear this concept. 

 

 

*Duplicate is not allowed in string constant pool                .

Examples: -    String s=”alpha”;

                       String s1=”alpha”;

                       String str2=new String (“alpha”);

2.By String literal- we can create String literal by using double quotes.

Ex-String s=”alphalearning”;

Whenever you create a String literal, jvm checks the string constant pool first. If the String already exists in the pool, a reference to the pooled instance is returned. If string does not exist in the pool, a new string instance is created .

Ex: - String s=”alpha”;

String s2=”alpha”;        //  Here we can see that when we use string literal to create a string it first creates a string in string constant pool, again when we create second string with same string it will first check the string if it will be there than it will point to the same string.

Note: - Concept of literal is to make java more efficient. Because no new objects are created if it exists already in string constant pool.

Immutable String in java: - String objects are immutable means we cannot change it. Once we created string it cannot be changed but new string object is created.

Let’s try to understand with an example.

Class a {
Public static void main (String args[]){
String s="alpha";  // it will go to string constant pool.
s.concat("learning"); //concat() method is used to add string at end.
System.out.println(s); //it will print alpha only. Because strings are immutable.

Pictorial representation: -

Pictorial representation: -

 

Note: - String objects are immutable in java because java uses the concept of string literal. If 10 reference variables refer to one object “alpha”. If one reference variable changes the value of the object, it will effect to all the reference variables. So objects are immutable in java.

Java String Compare: -

In java we generally use content and reference to compare String.

There are three ways to compare String in java:

  1. By equals() method.
  2. By == operator.
  3. By compareTo() method.

1.String compare by equals() method-

It compares the original content of the string and values of the String for equality. 

 

Example:
Class a{
public static void main(String args[]){
String s="alpha";
String s1="alpha";
String s2=new String ("alpha");
String s3="alphe";
String s4="ALPHA";
//output is written in comment.
System.out.println(s.equals(s1)); //true
System.out.println(s.equals(s2)); //true
System.out.println(s.equals(s3)); //false
System.out.println(s.equals(s4)); //false
System.out.println(s.equalsIgnoreCase(s4)); //true
}
}

 

2.String compare by == operator: -

The == operator compares references not values.

 

Example:
class a{
public static void main(String args[]{
String s="alpha";
String s1="alpha";
String s2=new String ("alpha");
System.out.println(s==s1); //true (same instance both are referring)
System.out.println(s==s2); //false (s3 refers to instance created in non-pool)
}
}

 

3.String compare by compareTo() method:-

The method compareTo() is used for comparing two strings lexicographically. Each character of both the strings is converted to a Unicode value for comparison. If both the strings are equal, then this method return 0 else it returns positive or negative value. The result is positive if the first string is lexicographically greater than the second string else the result would be negative.

Like   s==s1    //0   

s>s1   //positive value.

s<s1   //negative value.

Program example:

 class A{  
 public static void main(String args[]){  
   String s1="alpha";  
   String s2="alpha";  
   String s3="beta";  
   System.out.println(s.compareTo(s1)); //0  
   System.out.println(s.compareTo(s2)); //1(because s>s2)  
   System.out.println(s2.compareTo(s)); //-1(because s2 < s)  
 }  
}  

String Concatenation in Java : String concatenation is used for to form new string by combination of multiple string.There are two ways to merge string .

1.By +  operator.

2.By  concat() method.

1.By +  operator.

lets check this examples to clear all doubt.

class A{  
 public static void main(String args[]){  
   String s="alpha"+" learning";  
   String s=10+20+"alpha"+30+40;
System.out.println(s);//alphalearning    
   System.out.println(s);//30alpha3040
   
 }  
}  

 

Note:- String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its append method. String concatenation operator produces a new string by appending the second operand onto the end of the first operand. The string concatenation operator can concat not only string but primitive values also.

  1. String Concatenation by concat() method :-

The String concat() method concatenates the specified string to the end of current string. 

class A{  
 public static void main(String args[]){  
   String s1="alpha ";  
   String s2="learning";  
   String s3=s1.concat(s2);  
   System.out.println(s3);//alphalearning 
  }  
}  

 

Lets understand with examples:-

public class A{  
 public static void main(String args[]){  
   String s="alphalearning";  
   System.out.println(s.substring(4));         //learning   (startIndex : inclusive)
   System.out.println(s.substring(0,4));     //alpha   (endIndex :  exclusive)
 }  
}  

 

Java String class methods : In this class java provides lots of methods to do operations on strings. By using these methods we can performs operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.it is very important concept because many data from forms we get in the form of string. We can do operations on it and can use according to need.

Lets see some examples:-

   Java String toUpperCase() and toLowerCase() method – it converts uppercase letter to lowercase letter.

String s="Alpha";  
System.out.println(s.toUpperCase());//ALPHA 
System.out.println(s.toLowerCase());//alpha
System.out.println(s);//Alpha(no change in original)

Java String trim() method – trim() method is used to eliminates the whitespaces before and after string.

  1. String s="  alpha  ";  
  2. out.println(s);//  alpha 
  3. out.println(s.trim());//alpha

Java String startsWith() and endsWith() method – with this method we can check starting and ending character of string.

  1. String s="Alpha";  
  2. out.println(s.startsWith("Al"));//true
  3. out.println(s.endsWith("a"));//true 

Java String charAt() method - The string charAt() method returns a character at specified index.

Examples:-

  1. String s="Alpha";  
  2. out.println(s.charAt(0));//A
  3. out.println(s.charAt(3));//h 

Java String intern() method –String class is privately maintained when a pool of strings, initially empty.

When the intern method is invoked,if the pool already contains a string equal to this string object as determined by the equals(objects) method, then the string from the pool is returned.else,this string object is added to the pool and a reference of this string object is returned. 

Example:

String s=new String("Alpha"); 

String s2=s.intern(); 

System.out.println(s2);//Alpha 

Java String valueOf() method :

It converts the given type like int,float,double Boolean, char and char array into string.

int a=100; 

String s=String.valueOf(a); 

System.out.println(s+10);//10010 

Java String replace() method –  it is used to replaces all occurrence of first sequence of character with second sequence of character. 

String s1="alpha learning is for those who want to learn and explore";   

String replaceString=s1.replace("alpha","beta");    //replaces all occurrences of "alpha" to "beta"   

System.out.println(replaceString);  // beta learning is for those who want to learn and explore.

Java StringBuffer class

 java stringBuffer class is same as string class but it is mutable means we can change or modify.StringBuffer class is thread safe.(at a time only one thread can access.it is synchronized.) 

What is mutable string.

A string that can be modify or change is called mutable string. StringBuilder and StringBuffer classes are used for creating mutable class. 

  • StringBuffer append() method :- This method concatenates the string with the given string.

Examples : -

class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Alpha ");  
sb.append("beta");             //now original string is changed  
System.out.println(sb);    //prints Alphabeta  
}  
}  

 

2. StringBuffer insert() method :-it is used to insert string in given position of string. 

class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Alpha");  
sb.insert(1,"beta");                       //now original string is changed  
System.out.println(sb);       //prints   Abetalpha
}  
} 

 

3. StringBuffer replace() method :- This method is used for replace string from initialindex to endindex. 

Examples :-  class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Alpha");  
sb.replace(1,3,"beta");  
System.out.println(sb);                //prints  Abetaha
}  
}

 

4) StringBuffer delete() method :- this method is used to delete string from a specified initialindex to endindex.

Example:-

class B{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Alpha");  
sb.delete(1,3);  
System.out.println(sb);//		prints Aha 
}  
} 

 

5) StringBuffer reverse() method :- This method is used to reverse the string.

Example:-

class A{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Alpha");  
sb.reverse();  
System.out.println(sb);//prints ahplA 
}  
} 

 

6) StringBuffer capacity() method :- The capacity() method of StringBuffer class returns the current capacity of the buffer.The default capacity of String is 16.If you increase your character than it will increase like (16*2)+2.example if you increased your limit it will increase (16*2)+2=34.

Let’s see with examples for better understand.

class B{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer();  
System.out.println(sb.capacity());//default 16  
sb.append("Hello");  
System.out.println(sb.capacity());//now 16  
sb.append("Technology can change our life");  
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
}  
} 

 

7) StringBuffer ensureCapacity() method :- This  method of StringBuffer class ensures that the given capacity is the minimum to the current capacity. If it is greater than the current capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

class C{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer();  
System.out.println(sb.capacity());//default 16  
sb.append("welcome");  
System.out.println(sb.capacity());//now 16  
sb.append("Welcome to our website alphalearningschool");  
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2  
sb.ensureCapacity(10);//now no change  
System.out.println(sb.capacity());//now 34  
sb.ensureCapacity(50);//now (34*2)+2  
System.out.println(sb.capacity());//now 70  
}  
}  

 

Note : Java StringBuilder and java StringBuffer both are same except StringBuffer Class is synchronized(only one can access at a time).From jdk 1.5 it is available.

 

Comparison between String, StringBuffer, StringBuilder.

String

StringBuffer

StringBuilder

1. String is immutable. Means we cannot Change it.

1.StringBuffer is mutable. Means we can change.

1.StringBuilder is mutable

2.String is fast as compare to String Buffer.

2.StringBuffer is  very slow.

2.StringBuilder is fastest.

3.String class override the equals() method of an objects.

3. StringBuffer has reverse() method.

3. StringBuilder has reverse() method.

4.String Storage area is Constant String pool.

4. StringBuffer Storage area is Heap.

4. StringBuilder Storage area is Heap

5.Thread Safe.

5.Thread Safe.

5.Not Thread Safe.

How to create Immutable class?

Immutable means once we created an object we cannot change or modify. In java all wrapper class (classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc.) and string class are immutable. We can create our own class as immutable.

  1. Using final keyword like final class. (no one will get access.).
  2. Declare data member in the class to final. (No one can change the value.).
  3. There is no setter methods i.e. we have no option to change the value of the instance variable.
  4. A parameterized constructor.
  5. Getter method for all the variables in it.

How to create Immutable class?

Immutable means once we created an object we cannot change or modify. In java all wrapper class (classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc.) and string class are immutable. We can create our own class as immutable.

  1. Using final keyword like final class. (no one will get access.).
  2. Declare data member in the class to final. (No one can change the value.).
  3. There is no setter methods i.e. we have no option to change the value of the instance variable.
  4. A parameterized constructor.
  5. Getter method for all the variables in it.
Examples:-
// An immutable class
public final class Student
{
    final String name;
    final int rollno;
 
    public Student(String name, int rollno)
    {
        this.name = name;
        this.rollno = rollno;
    }
    public String getName()
    {
        return name;
    }
    public int getRollNo()
    {
        return rollno;
    }
}
 
// Driver class
class A
{
    public static void main(String args[])
    {
        Student s = new Student("ABC", 10);
        System.out.println(s.name);//output ABC
        System.out.println(s.rollno);//output 10
 
        // Uncommenting below line causes error
        // s.regNo = 11;//can not change.
    }
}

 

Java toString() method :-ToString() method is used to represent an object as a string.If you want to print any object java internally invoke to print toString() method.If you will not override toString() java jump to object class and give some hashcode values.

Let’s see one example how we use toString() method.

class Student{  
 int Cust_id;  
 String name;  
 String city;  
  
 Student(int Cust_id, String name, String city){  
 this.Cust_id=Cust_id;  
 this.name=name;  
 this.city=city;  
 }  
public String toString(){
//overriding the toString() method . comment and try you will get.
  return Cust_id+" "+name+" "+city;  
}  
 public static void main(String args[]){  Student s1=new Student(10,"Ram","Delhi");  
   Student s2=new Student(12,"Shyam","Bengalore");  
System.out.println(s1);//compiler writes here s1.toString()  System.out.println(s2);//compiler writes here s2.toString()  
 }  
} 

 

StringTokenizer in Java :It is used to break string into tocken.It is in java.utility package It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.

public class A {
	public static void main(String args[]) {
    StringTokenizer st = new StringTokenizer("Welcome to this site", " "); 
// Output:-Welcome
		while (st.hasMoreTokens()) {
			System.out.println(st.nextToken());
		}
	}
}

 

Example of nextToken(String delim) method of StringTokenizer class :

public class Test {  
   public static void main(String[] args) {  
       StringTokenizer st = new StringTokenizer("Welcome to our site");  
        
      // printing next token  
       System.out.println("Next token is : " + st.nextToken(","));  
   }      
}  

Java String Metods

There are many methods let’s see one by one to get how they are working.

  1. Java String charAt() -The Java String charAt() method returns a char value at the given index number.The index no. starts from 0 to (n-1)where n=String. If index no. will exceed the limit or for negative value it will returns StringIndexOutOfBoundsException.

Let’s see examples: -

public class CharAtExample{  
public static void main(String args[]){  
String name="alpha";  
char ch=name.charAt(4);//returns the char value at the 4th index  
//char ch1=name.charAt(10);  //uncomment and check.
System.out.println(ch);  //a
System.out.println(ch1);  //error StringIndexOutOfBoundsException.
   }
}  

 

Note : for more programs go to interview questions. There you can see all programs related to string.

  1. Java String compareTo() : The method compareTo() is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns positive or negative value. The result is positive if the first string is lexicographically greater than the second string else the result would be negative.

if s1 > s2, it returns positive number 

if s1 < s2, it returns negative number 

if s1 == s2, it returns 0 

Example  : -

public class CompareToExample{  
public static void main(String args[]){  
String s1="beta";  
String s2="beta";  
String s3="alpha";  
String s4="ceta";  
String s5="fun";
String s6="WELCOME";  
String s7="";  
String s8="alpha";
System.out.println(s1.compareTo(s2));//0 because both are equal  
System.out.println(s1.compareTo(s3));//-1 
System.out.println(s1.compareTo(s4));//-1 
System.out.println(s1.compareTo(s5));//4 
System.out.println(s6.compareTo(s7));  //7
System.out.println(s7.compareTo(s8));
//-5 first string is empty so the result is negative.
}
}
  1. Java String concat : - this method is used to combine two strings at the end of string. It is same as appending an string.

Example:

public class A {  
    public static void main(String[] args) {      
        String str1 = "Alpaha";  
        String str2 = "Learning";  
        String str3 = "School";  
        // Concatenating one string   
        String str4 = str1.concat(str2);          
        System.out.println(str4);  
        // Concatenating multiple strings  
        String str5 = str1.concat(str2).concat(str3);  
        System.out.println(str5);  
    }  
}

 

4.Java String contains() :- The java string contains() method searches the sequence of characters in this string. It returns true if sequence of char values are found in this string otherwise returns false.

Example:-

class A{  
public static void main(String args[]){  
String name="java is a programing language";  
System.out.println(name.contains("is a"));  //true
System.out.println(name.contains("language"));  //true
System.out.println(name.contains("Java"));  //false (case sensitive)
  }
} 

 

5.Java String endsWith():- This method checks (string ends with given suffix)the string which is ending with the same  string if it is same than it return true else it return false. It is case sensitive (caps and small characters matters.).

Example:- 

public class A{  
public static void main(String args[]){  
String s1="java is programing language";  
System.out.println(s1.endsWith("e"));  //true
System.out.println(s1.endsWith("language"));  //true
System.out.println(s1.endsWith("java"));  //false.

  }
} 

 

Java String equals() :- This method compares based on the content of the string. It is case sensitive. If any character will not match it will return false, else return true. The String equals() method overrides the equals() method of Object class.

Example :-

public class A{  
public static void main(String args[]){  
String s1="alphalearning";  
String s2="alphalearning";  
String s3="ALPHALEARNING";  
String s4="beta";  
System.out.println(s1.equals(s2));//true because content and case is same  
System.out.println(s1.equals(s3));//false because case is not same  
System.out.println(s1.equals(s4));//false because content is not same  
  }
} 

Java String equalsIgnoreCase() : -This method is same as equal() method only the difference is it will ignore case sensitive it will check only content not caps letter or small letter.

Example:-

public class A{  
public static void main(String args[]){  
String s1="alphalearning";  
String s2="alphalearning";  
String s3="ALPHALEARNING";  
String s4="beta";  
System.out.println(s1.equalsIgnoreCase(s2));
//true because content and case both are same  
System.out.println(s1.equalsIgnoreCase(s3));
//true because case is ignored  
System.out.println(s1.equalsIgnoreCase(s4));
//false because content is not same  
 }
}

 

Java String format() :- The java string format() method returns a formatted string using the given locale, specified format string and arguments.We can concatenate the strings using this method and at the same time, we can format the output concatenated string. 

 Table Java String Format Specifiers :-

Format Specifier

Data Type

Output

%a

floating point (except BigDecimal)

Returns Hex output of floating point number.

%b

Any type

"true" if non-null, "false" if null

%c

Character

Unicode character

%d

integer (incl. byte, short, int, long, bigint)

Decimal Integer

%e

floating point

decimal number in scientific notation

%f

floating point

decimal number

%g

floating point

decimal number, possibly in scientific notation depending on the precision and value.

%h

any type

Hex String of value from hashCode() method.

%n

None

Platform-specific line separator.

%o

integer (incl. byte, short, int, long, bigint)

Octal number

%s

any type

String value

%t

Date/Time (incl. long, Calendar, Date and TemporalAccessor)

%t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.

%x

integer (incl. byte, short, int, long, bigint)

Hex string.



Example:-

public class A {  
    public static void main(String[] args) {  
        String str1 = String.format("%d", 100);          // Integer value  
        String str2 = String.format("%s", "Neel"); // String value  
        String str3 = String.format("%f", 100.00);       // Float value  
        String str4 = String.format("%x", 100);          // Hexadecimal value  
        String str5 = String.format("%c", 'n');          // Char value  
        System.out.println(str1);  //100
        System.out.println(str2);  //Neel
        System.out.println(str3);  //100.000000
        System.out.println(str4);  //64
        System.out.println(str5);  //n
    }  
}  

 

Java String getBytes() :- This method return the byte array of the string or sequence of bytes.

Example:- 

public class A{  
public static void main(String args[]){  
String s1="ABCDEFG";  
byte[] b=s1.getBytes();  
for(int i=0;i<b.length;i++){  
System.out.println(b[i]);
}    
String s2 = new String(s1);  
        System.out.println(s2);  
}
} 

 

Java String getChars() :-This method copies the content of this string into specified char array.It does not return any value. It throws StringIndexOutOfBoundsException if beginIndex is greater than endIndex.

Example:-

: public class A{  
public static void main(String args[]){  
 String str = new String("hello world");  
      char[] ch = new char[10];  
      try{  
         str.getChars(6, 10, ch, 0);  
         System.out.println(ch);  
      }catch(Exception ex){System.out.println(ex);}  
   }
} 

 

Java String indexOf() :- This method return the index of character value or substring. If it is not found than it will return -1 value. Index counter starts from 0.

Example :-

public class A{  
public static void main(String args[]){  
String s1="this is my index";  
//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  
int index5=s1.indexOf("my",11);
System.out.println(index5);//no index found so -1 returning.
}
}

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 memory, if it is created by new keyword. It creates exact copy of heap string object in string constant pool.

Example :- 

public class A {  
    public static void main(String[] args) {          
        String s1 = "Alpha";  
        String s2 = s1.intern();  
        String s3 = new String("Alpha");  
        String s4 = s3.intern();          
        System.out.println(s1==s2); // True  
        System.out.println(s1==s3); // False  
        System.out.println(s1==s4); // True       
        System.out.println(s2==s3); // False  
        System.out.println(s2==s4); // True        
        System.out.println(s3==s4); // False          
    }  
}

 

Java String isEmpty() : -This method is used to check that string is empty or not, If it is empty than it return true else return false.

Example: -

public class A{  
public static void main(String args[]){  
String s1="";  
String s2="Alpha";  
  
System.out.println(s1.isEmpty());  //true
System.out.println(s2.isEmpty());  //false
  }
} 

 

Java String join() :- The java.lang.string.join() method concatenates the given elements with the delimiter and returns the concatenated string.Note that if an element is null, then null is added.The join() method is included in java string since JDK 1.8.

Example:- 

public class A {  
    public static void main(String[] args) {          
        String date = String.join("/","01","01","2018");    
        System.out.print(date);    //01/01/2018
        String time = String.join(":", "01","01","18");  
        System.out.println(" "+time);  //01:01:18
    }  
}

 

Java String lastIndexOf() :- This method returns last index of substring or given character value. If it is not available than -1 it will return. Index start from 0.

Example:

public class A{  
public static void main(String args[]){  
String s1="example of last index";//there are 2 's' characters in this sentence  
 int index = s1.lastIndexOf('s',5);  
 System.out.println(index); //not found so return -1.     
 int index2 = s1.lastIndexOf("of", 15);  
  System.out.println(index2);// 8 
int index1=s1.lastIndexOf('s');//returns last index of 's' char value  
System.out.println(index1);//6  
  }
}

 

Java String length() :- This method is used to count the no of the characters in string. It returns total no. of characters. It is same as the Unicode units of the string.

Example:

public class LengthExample{  
public static void main(String args[]){  
String s1="Alpha";  
String s2="beta";  
System.out.println("string length is: "+s1.length());
// 5is the length of Alpha string  
System.out.println("string length is: "+s2.length());
// 4is the length of beta string  
   }
}

 

Java String replace() : -From java 1.5 replace() method is introduced. With this method we can replace old character or a string we can replace. It is case sensitive.

Example:-

public class A{  
public static void main(String args[]){  
String s="This is alpha Learning school ";  
String replaceString=s.replace('a','e');
//replaces all occurrences of 'a' to 'e'  
System.out.println(replaceString);  
String replaceString1=s.replace("is","was");
//replaces all occurrences of "is" to "was"  
System.out.println(replaceString1);
  }
}

 

Java String replaceAll(): It is same as replace() method. It uses regex pattern.

Example:-

public class A{  
public static void main(String args[]){  
String s1="This is one example. This is 2nd.";  
String replaceString=s1.replaceAll("\\s","    ");  
//If we will replace ReplaceAll() to Replace() it will not work.
System.out.println(replaceString);  
  }
}

 

Java String split() :- This method breaks a given string around matches of the given regular expression.

Example:-

public class A{  
public static void main(String args[]){  
String s1="java string split method by javatpoint";  
String[] words=s1.split("\\s");//splits the string based on whitespace  
//using java foreach loop to print elements of string array  
for(String word:words){  
System.out.println(word);  
     }  
   }
}  

 

Java String startsWith() :- This method is used to checks if the string is starting with given prefix. If yes than it return true else return false.

Example: -

public class StartsWithExample2 {  
    public static void main(String[] args) {  
        String str = "Alpha";  
        System.out.println(str.startsWith("A")); // True  
        System.out.println(str.startsWith("b")); // False  
        System.out.println(str.startsWith("l",1)); // True  
    }  
} 

 

Java String substring():- This method returns the part of the string.It works on the concept of inclusive and exclusive like

Inclusive (6)-it will print after the 5th position character including.

Exclusive(5):-It will print before the 5th position of character excluding.

Example: -

public class A {  
    public static void main(String[] args) {  
        String s1="Alphalearning";    
        String substr = s1.substring(0); // Starts with 0 and goes to end  
        System.out.println(substr);// Alphalearning
        String substr2 = s1.substring(5,10); // Starts from 5 and goes to 10  
        System.out.println(substr2);    //learn
        String substr3 = s1.substring(5,15); // Returns Exception  
    }  
} 

 

Java String toCharArray() :- This method is used to convert string to character array.It will create new character array with same string length.

Example:-

public class A{  
    public static void main(String[] args) {  
String s1 = "Welcome to Alphalearningschool";
        char[] ch = s1.toCharArray();  
        int len = ch.length;  
        System.out.println("Char Array length: " + len);  //30
        for (int i = 0; i < len; i++) {  
            System.out.println(ch[i]);  //  Welcome /n  to /n  alphalearningschool .
        }  
    }  
}  

 

Java String toLowerCase() :- This method is used to convert your String to lower case.

Example:-

public class A{  
public static void main(String args[]){  
String s1="ALPHAlearning";  
String s1lower=s1.toLowerCase();  
System.out.println(s1lower);  //alphalearning
  }
} 

Java String toUpperCase():- This method is used to convert all character into upper case.

Example:-

public class A{  
public static void main(String args[]){  
String s1="Alphalearning";  
String s1upper=s1.toUpperCase();  
System.out.println(s1upper);  //ALPHALEARNING
 }
} 

 

Java String trim() :- This method is used to remove whitespaces before String and after string.It will not remove the spaces between the strings.

Example:

public class A {  
    public static void main(String[] args) {  
        String s1 ="  Alpha Learning   ";  
        System.out.println(s1.length());  //19
        System.out.println(s1); //Without trim()  Alpha Learning
        String tr = s1.trim();  
        System.out.println(tr.length());  //14
        System.out.println(tr); //With trim()  Alpha learning
    }  
} 

 

Java String valueOf() :- This method is used to convert any data types to string. Like int to string, long to string etc.

Example:- 

public class A {  
    public static void main(String[] args) {  
        boolean b1=true;  
        byte b2=11;    
        short sh = 12;  
        int i = 13;  
        long l = 14L;  
        float f = 15.5f;  
        double d = 16.5d;  
        char chr[]={'j','a','v','a'};  
        A obj=new A();  
        String s1 = String.valueOf(b1);    
        String s2 = String.valueOf(b2);    
        String s3 = String.valueOf(sh);    
        String s4 = String.valueOf(i);    
        String s5 = String.valueOf(l);    
        String s6 = String.valueOf(f);    
        String s7 = String.valueOf(d);    
        String s8 = String.valueOf(chr);    
        String s9 = String.valueOf(obj);    
        System.out.println(s1);  //true
        System.out.println(s2);  //11
        System.out.println(s3);  //12
        System.out.println(s4);  //13
        System.out.println(s5);  //14
        System.out.println(s6);  //15.5
        System.out.println(s7);  //16.5
        System.out.println(s8);  //java
        System.out.println(s9);  //A@2a139a55
    }  
}

 

Note :- For more programming practice go to interview question section. We try to solve your doubt still you are facing problem you can go to interview question. There you will get extra programs.