Menu Bar

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Tuesday, 31 January 2017

String Class Constructors In Java

String class provides various constructor .To create empty constructor we call default constructor as String s = new String(); Here we will discuss each and every constructor one by one. In below program we have discussed each constructor in detail.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class StringConstructors {

 public static void main(String[] args) throws UnsupportedEncodingException {
  //Default Constructor
  String s1 = new String();

  //Constructor with char array 
  char[] charArr = {'j','a','v','a'};
  String s2 = new String(charArr);
  System.out.println("S2 : "+s2);
  
  //Constructor with byte array
  String original = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
  String s3 = new String(original.getBytes());
  System.out.println("S3 : "+s3);
  
  //Constructor with String
  String s4 = new String("Java Identifiers");
  System.out.println("S4 : "+s4);
  
  //Constructor with StringBuffer
  String s5 = new String(new StringBuffer("Java"));
  System.out.println("S5 : "+s5);
  
  //Constructor with StringBuilder
  String s6 = new String(new StringBuilder("Java"));
  System.out.println("S6 : "+s6);  
  
  //Constructor with Bytes and character encoding
  byte[] utf8Bytes = original.getBytes("UTF8");
  String s7 = new String(utf8Bytes, "UTF8");
  System.out.println("S7 : "+s7);  
  
  //Constructor with Bytes and Charset class
  String s8 = new String(utf8Bytes,Charset.defaultCharset());
  System.out.println("S8 : "+s8);
  
  //Constructor with char array, offset and count
  String s9 = new String(charArr,0,2);
  System.out.println("S9 : "+s9);
  
  //Constructor with ASCII array
  byte ascii[] = {65, 66, 67, 68, 69, 70 }; 
  String s10 = new String(ascii);
  System.out.println("S10 : "+s10);
 }

}

Output:

S2 : java
S3 : AêñüC
S4 : Java Identifiers
S5 : Java
S6 : Java
S7 : AêñüC
S8 : AêñüC
S9 : ja
S10 : ABCDEF



      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Share this Blog with yours Friends !!

No comments:

Post a Comment