Java String Constructors

Introduction

To create an empty String, call the default constructor. For example,

String s = new String(); 

To create a String initialized by an array of characters, use the constructor shown here:

String(char chars[ ]) 

Here is an example:

char chars[] = { 'a', 'b', 'c' };  
String s = new String(chars); 

This constructor initializes s with the string "abc".

To specify a subrange of a character array as an initializer:

String(char chars[ ], int startIndex, int numChars) 

startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use.

char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };  
String s = new String(chars, 2, 3); 

This initializes s with the characters cde.

To construct a String object from another String object using this constructor:

String(String strObj) 

Here, strObj is a String object.

// Construct one String from another.  
public class Main {  
  public static void main(String args[]) {  
    char c[] = {'J', 'a', 'v', 'a'};   
    String s1 = new String(c);  
    String s2 = new String(s1);  
  
    System.out.println(s1);  //from w ww.  j a  v a2s .com
    System.out.println(s2);  
  }  
} 

String class has constructors that initialize a string when given a byte array.

Two forms are shown here:

String(byte chrs[])  
String(byte chrs[], int startIndex, int numChars)     

The following program illustrates these constructors:

// Construct string from subset of char array.  
public class Main {  
  public static void main(String args[]) {  
    byte ascii[] = {65, 66, 67, 68, 69, 70 };  
  
    String s1 = new String(ascii);  
    System.out.println(s1);  //  w w w .j  a  v  a2s .  co m
  
    String s2 = new String(ascii, 2, 3);  
    System.out.println(s2);  
  }  
} 



PreviousNext

Related