Declaring and initializing strings - Java Language Basics

Java examples for Language Basics:String

Introduction

The following statements define and initialize a string variable:

Demo Code

public class Main {
  public static void main(String[] args) {
    String s;/*from  ww w.j  a  v a2  s .  co  m*/
    s = "Hello, World!";

    System.out.println(s);
  }

}

A string declaration can include an initializer.

Demo Code

public class Main {
  public static void main(String[] args) {
    String s = "Hello, World!";

    System.out.println(s);//  ww  w.  j  a v a  2 s . c om
  }

}

To initialize a local string variable to an empty string, use a statement like this:

Demo Code

public class Main {
  public static void main(String[] args) {
    String s = "";

    System.out.println("Empty string:"+s);
  }/*from  w w  w  .  jav a 2 s .c  o m*/

}

Related Tutorials