Core Java Tutorial

 
 

Java Strings

String is defined as a sequence of charecters.In java String is a object and String is denoted in between double quotes(" ").Strings are immutable because once if they are initialized with some value then we can't change the value.if you want to change the value then either you can use StringBuffer and StringBuilder classes.

   Heirarchy:
               java.lang.Object;
                     java.lang.String;   

       Ex1:     String name="Java"; // This is String literal 
       Ex2:      char data[] = {'J','a','v','a'};
                 String string = new String(data); // this is String Object
       Above two examples will give the both String values(i.e Java).

String Concatanation

String concatanation is achieved by using "+" operator.Concatanation operator is used to join(add) more than one String values and also you can join variable and String by using concatanation operator.

  Ex:
          class Demo{
             void addStr(){
              String name1="Hello";
              String name="Java";
               // here i am joining string and variables.
              System.out.println("Concatanation of above two variables is :"+name+name1);
                 }
              
              public static void main(String[] args){
               Demo demo = new Demo();
               demo.addStr(); 
  }
}
Output:Concatanation of above two variables is :JavaHello

Length of String

You can find the length of a String by using length() method.

  Ex:
     public class StrDemo {
	public static void main(String[] args) {
		String name="Hello Java";
		int lengthOfStringIs=name.length();
		System.out.println("Length Of String Is: "+lengthOfStringIs);
	}
}
Output: Length Of String Is: 10

substring in java

Substring in java is used to get some part of string.

 Ex1:
           String  name="Hello java";
            name.substring(6,10);// substring(start index,end index)
            // here substring value is from 6-9(i.e 6th position is included and 10th position is excluded).
      Ex2:
        
           public class StrDemo {
	public static void main(String[] args) {
		String name="Hello Java";
		//String lengthOfStringIs=name.intern();
		System.out.println("Length Of String Is: "+name.substring(6));
	}
}
Output:some part of String Is: Java
Note: These are some of the methods you are seeing here,but we do have more methods for strings in java, For more information about methods in string, please go and visit Oracle Java String documentation.