Java - How to declare a String in Java?


IncludeHelp 22 September 2016

In this code snippet/program we will learn how to declare a String variable/ String Object in Java programming language?

Here we will learn declaration of String variables in java programming language by using different method, but firstly you have to know about Java Strings.

Java Code Snippet/Program - String Declaration using Different Methods

What is String in Java?

In Java programming language, String is an object that contains sequence of characters in other words we can say String is a character array. But character array and Strings are quite different in Java, declarations, operations and usages are different.

In Java programming language String is a built in class which can be used by importing java.util.String class, but we can directly use the String in our Java program.

How to declare a String Object in Java?

There are many ways to declare a String Object in Java programming language.

1) First way to declare a String Object

String string_name;
public class StringDecExample{
     public static void main(String []args){
        String str;
        str="Hello World!";
        System.out.println("String is: " + str);
     }
}

    String is: Hello World!

2) Second way to declare a String Object

String string_name=new String();
public class StringDecExample{
     public static void main(String []args){
        String str=new String("Hello World!");
        System.out.println("String is: " + str);
     }
}
    
    String is: Hello World!

3) First way to Declaration of Multiple String Variables

public class StringDecExample{
     public static void main(String []args){
        String str1="Hello World!", str2="How are you?", str3="I'm fine!";
        
        System.out.println("str1: " + str1);
        System.out.println("str2: " + str2);
        System.out.println("str3: " + str3);
     }
}
    
    str1: Hello World!
    str2: How are you?
    str3: I'm fine! 

4) Second way to Declaration of Multiple String Variables

public class StringDecExample{
     public static void main(String []args){
        String  str1=new String("Hello World!"), 
                str2=new String("How are you?"), 
                str3=new String("I'm fine!");
        
        System.out.println("str1: " + str1);
        System.out.println("str2: " + str2);
        System.out.println("str3: " + str3);
     }
}
    
    str1: Hello World!
    str2: How are you?
    str3: I'm fine! 

5) String declaration through Character Array

public class StringDecExample{
     public static void main(String []args){
         char chArr[]={'H','e','l','l','o',' ','W','o','r','l','d','!','\0'};
         String str=new String(chArr);
        
        System.out.println("String is: " + str);
     }
}
    
    String is: Hello World!

Reference: http://www.javatpoint.com/java-string



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.