Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Strings


A String is a collection of letters/alphabets. It can be a word or a sentence.


The Data Type for String is String.


Note : String in an immutable class. i.e. Once the values are assigned to a String object, it cannot be modified or changed.

Declaring a String with Double Quotes ("")


When Java finds data inside Double Quotes (""). It creates a String type variable for that value.


var x = "Hello World";

var is independent of data type. i.e. The above variable x can accept a value of any data type.


Example :



public class MyApplication {
    public static void main(String[] args) {
    
     	var x = "Hello World";
   		System.out.println(x);
    }
}


Output :



  Hello World

And that's all! You have a String in place.


Well! There are other ways using which you can create a String.


Declaring a String with String data type


Example :



public class MyApplication {
    public static void main(String[] args) {
    
     	String x = "Hello World";
   		System.out.println(x);
    }
}	


Output :



  Hello World

So, in the above code, we have declared a variable x of String type.


String x = "Hello World";

So that it would not accept any values other than a String.


Also one more advantage of declaring using a String type is that you can assign the value to the String variable later.


Let us understand with the below code.


Example :



public class MyApplication {
    public static void main(String[] args) {
    
        String x;
   	    x = "Hello World";
   	    System.out.println(x);
    }
}	


Output :



  Hello World

Just note that we have not initialised the variable x. We have just declared it.


String x;

So that an empty variable x would be created that would only hold a String.

Spring_Boot

Then in the next line, we have assigned the value Hello World to the variable x.


x = "Hello World";
Spring_Boot


Well! We have declared a String type variable and assigned it later.


But the below code won't work, if we do not specify a data type.


Example :



public class MyApplication
{
    public static void main(String[] args)
    {
        var x;
   	    x = "Hello World";
   	    System.out.println(x);
    }
}	


Output :



  java: cannot infer type for local variable x
  (cannot use 'var' on variable without initializer)

And if you take a look at the below output, the above code didn't work because we haven't specified any data type.


var x;

How to find the length of a String?


length()


length() method is used to return the length of a String.


Example :



public class MyApplication
{
    public static void main(String[] args)
    {
       	String x = "Hello";
        System.out.println("The length of the String is : "+x.length());
    }
}


Output :



  The length of the String is : 5