Java String type

Introduction

Java String type declares string variables.

A double-quoted string constant can be assigned to a String variable.

A variable of type String can be assigned to another variable of type String.

You can use String type variable as an argument to println().

For example, consider the following fragment:

String str = "this is a test";                                                                          
System.out.println(str);                                                                                

Here, str is an object of type String.

It is assigned the string "this is a test".

This string is displayed by the println() statement.

Class String is used to represent strings in Java.

Class String provides constructors for initializing String objects.


// String class constructors.

public class Main 
{
   public static void main(String[] args)
   {// w  w  w.  java 2 s.  c  om
      char[] charArray = {'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y'};
      String s = new String("hello");

      // use String constructors
      String s1 = new String();
      String s2 = new String(s);
      String s3 = new String(charArray);
      String s4 = new String(charArray, 6, 3);

      System.out.printf(
         "s1 = %s\ns2 = %s\ns3 = %s\ns4 = %s\n", s1, s2, s3, s4); 
   } 
}



PreviousNext

Related