Tuesday, 23 June 2015

java.lang.Object Class

1.Introduction

The Object class is at the root of all the hierarchies in Java. This class is part of the java.lang package. All classes extend the Object class, either directly or indirectly. Even if you write a simple class (i.e. it is not extending any base-class), it implicitly extends built-in Object class.

Thus the features of this class will be available in all the classes because of inheritance.

2. Important Methods in Object class

The object class defines following methods, which are inherited by all the classes.
  • public int hashCode()
  • public boolean  equals(Object obj)
  • public final Class getClass()
  • public String toString()
  • public protected void finalize() throws Throwable
  • public protected Object clone() throws CloneNotSupportedException
  • public final void wait(long timeout) throws InterruptedException
  • public final void wait(long timeout, int nanos) throws InterruptedException
  • public final void wait() throws InterruptedException
  • public final void notify()
  • public final void notifyAll()

2.1 public int hashCode()

When storing objects in hash tables, this method can be used to get a hash value for an object.

This value is guaranteed to be consistent during the execution of the program. If the objects of a class are to be maintained in hash based collections and maps of the java.util package, the class must provide appropriate implementation of the following methods from class Object:
  • hashCode()
  • equals()

As a general rules for implementing these methods a class that overrides the equals() method must also override the hashCode() method.

General contract of the hashCode() method:

(a) Consistency during execution: Multiple invocations of the hashCode() method on an object must consistently return the same hash code during the execution of an application, provided the object is not modified to affect the results returned by the equals() method.

(b) Object value equality implies hash value equality.

(c) Object value inequality places no restrictions on the hash value. If two objects are unequal according to equals() method, then the hashCode() method need not produce distinct hash code for these objects. It is strongly recommended that the hashCode() method produce unequal hash codes for unequal objects.

Note: The hash contract does not imply that objects with equal hash codes are equal. Not producing unequal hash codes for unequal objects can have an adverse effect on performance, as unequal objects will hash to same bucket, which will result in collision.

2.2 boolean equals(Object obj)

If every object is to be considered unique, then it is not necessary to override the equals() method of the Object class. This method implements object reference equality. It implements the most discriminating equivalence relation possible on objects. Each instance of the class is equal to itself.

The equals() method is usually overridden to provide the semantics of object value equality, as is the case for the wrapper classes and the String class.

2.3 final Class getClass()

Returns the runtime class of the object, which is represented by an object of the class java.lang.Class at runtime.

Example: The following example illustrates that this method can be used to get the Class object corresponding to any java Object. We can then use method of the class Class to get information about the object's class using reflection/introspection.

import java.lang.reflect.Method;

import java.lang.reflect.Field;

class DispClassInfo

{

public static void main(String args[]) throws ClassNotFoundException

{

String s = new String ("Hello");

Class c = s.getClass();

Method m[] = c.getMethods();

int l;

l = m.length;

System.out.println (".........Public Methods (" + l + ")......");

for(int i = 0; i < l; i++)

{

System.out.println (m[i]);

}

Field f[] = c.getFields();

l = f.length;

System.out.println (".........Public Fields (" + l + ")......");

for(int i = 0; i < l; i++)

{

System.out.println (f[i]);

}

m = c.getDeclaredMethods();

l = m.length;

System.out.println ("......... Declared Methods (" + l + ")......");

for(int i = 0; i < l; i++)

{

System.out.println (m[i]);

}

f = c.getDeclaredFields();

l = f.length;

System.out.println (".........Declared Fields (" + l + ")......");

for(int i = 0; i < l; i++)

{

System.out.println (f[i]);

}

}

}

Example: The previous example is modified so as to read the fully qualified class name as command line argument and then display the information about the class's methods and fields using reflection/introspection.

import java.lang.reflect.Method;

import java.lang.reflect.Field;

class DispClassInfo

{

public static void main(String args[]) throws ClassNotFoundException

{

Class c = Class.forName(args[0]);

Method m[] = c.getMethods();

int l;

l = m.length;

System.out.print();

System.out.println (".........Public Methods (" + l + ")......");

for(int i = 0; i < l; i++)

{

System.out.println (m[i]);

}

Field f[] = c.getFields();

l = f.length;

System.out.println (".........Public Fields (" + l + ")......");

for(int i = 0; i < l; i++)

{

System.out.println (f[i]);

}

m = c.getDeclaredMethods();

l = m.length;

System.out.println ("......... Declared Methods (" + l + ")......");

for(int i = 0; i < l; i++)

{

System.out.println (m[i]);

}

f = c.getDeclaredFields();

l = f.length;

System.out.println (".........Declared Fields (" + l + ")......");

for(int i = 0; i < l; i++)

{

System.out.println (f[i]);

}

}

}

2.4 String toString()

If a sub class does not override this method, it returns a textual representation of the object, which has the following format:

“<name of the class>@<hash code value of object>”

The method is usually overridden and used for debugging purposes. The method call System.out.println(Objref) will implicitly convert its argument to a textual representation using toString() method.

Example: This example demonstrates what gets displayed if we try to display object of class Box1. The object is converted to the textual representation using the toString() method of the object class.

class Box1

{ double w, h, d;

Box1(double w, double h, double d)

{ this.w=w; this.h=h; this.d=d;

}

}

class ToStringDemo1

{ public static void main(String args[])

{ Box1 b=new Box1(10,12,14);

String s="Box1 b: "+b; //concatenates box object

System.out.println(b);

System.out.println(s);

}

}

Output:

Box1@82ba41

Box1 b: Box1@82ba41

Example: This example demonstrates that if we override the toString() method in the Box1 class then the overridden method is used to convert the object to its textual representation.

class Box1

{ double w, h, d;

Box1(double w, double h, double d)

{ this.w=w; this.h=h; this.d=d;

}

public String toString()

{ return "Dimensions are "+w+" by "+h+" by "+d+".";

}

}

class ToStringDemo2

{ public static void main(String args[])

{ Box1 b=new Box1(10,12,14);

String s="Box1 b: "+b; //concatenates box object

System.out.println(b);

System.out.println(s);

}

}

Output:

Dimensions are 10.0 by 12.0 by 14.0.

Box1 b: Dimensions are 10.0 by 12.0 by 14.0.

2.5 protected void finalize() throws Throwable

It is called on an object just before it is garbage collected, so that any cleaning up can be done.

However, the default finalize() method in the object class does not do anything useful. This may be useful for releasing non-java resources but not recommended.  It is possible that finalize() method may never be called if enough memory is available and in that case resources may never be released.

2.6 protected Object clone() throws CloneNotSupportedException

New objects that are exactly the same (i.e., have identical states) as the current object can be created by the clone() method, that is, primitive values and reference values are copied. This is called shallow cloning.

A class can override the clone() method to provide its own notion of cloning. For example, cloning a composite object by recursively cloning the constituent objects is called deep cloning.

When overridden, the method in the subclass is usually declared public to allow any client to clone objects of the class.

If overriding clone() method relies on the clone() method in the Object class, then the subclass must implement the Cloneable marker interface to indicate that its objects can be safely cloned. Otherwise, the clone() method in the Object class will throw a checked CloneNotSupportedException.

Using clone() and the Cloneable interface

The clone() method generates a duplicate copy of the object on which it is called.

These are few important faces related to clone() method.

  • Only classes that implement the Cloneable interface can be cloned.
  • The Cloneable interface defines no members. It is used to indicate that a class allows a bit-wise copy ofan object (that is, a clone) to be made. If you try to call clone() on object of a class that does not implement Cloneable interface, CloneNotSupportedException is thrown.
  • Cloneable interface is an empty interface. Such an interface is called marker/tag interface.
  • When a clone is made, the constructor for the object being cloned is not called.
  • A clone is simply an exactly copy of the original. Cloning is potentially a dangerous action, because it can cause unintended side effects. For example, if the object being cloned contains a reference variable called objRef, then when the clone is made the objRef in clone will refer to the same object as does objRef in original. If the clone makes a change to the contents of the object referred to by objRef, then it will be changed for the original object, too.

Example: The following example demonstrate the use of clone() method. The CloneDemo1 class is making clone of the object of class TestClone by indirectly calling the clone method through cloneTest() method because clone() method of the object class is protected.

class TestClone implements Cloneable

{

int a;

double b;

public TestClone cloneTest() throws CloneNotSupportedException

{

}

return (TestClone) clone();

}

class CloneDemo1

{

public static void main(String a[]) throws CloneNotSupportedException

{

TestClone tc1 = new TestClone();

TestClone tc2;

tc1.a = 10;

tc1.b = 3.5;

tc2 = tc1.cloneTest();

System.out.println (tc2.a);

System.out.println (tc2.b);

}

}

Output:

10

3.5

Here, the method cloneTest() calls clone() of Object class and returns the result. Notice that the object returned by clone() must be cast into its appropriate type i.e. TestClone.

Example: In the following example the clone() method is overridden so that it can be called from code outside of its class. To do this, its access modifier must be public.

class TestClone1 implements Cloneable

{

int a;

double b;

public Object clone() throws CloneNotSupportedException

{

}

}

class CloneDemo2

{

public static void main(String a[]) throws CloneNotSupportedException

{

return super.clone();

TestClone1 tc1 = new TestClone1();

TestClone1 tc2;

tc1.a = 10;

tc1.b = 3.5;

tc2 = (TestClone1) tc1.clone();

System.out.println (tc2.a);

System.out.println (tc2.b);

}

}

Output:


10

3.5

Example: In the following example the clone() method is overridden such that it does not make use of the clone() method of the Object class. We are writing our own clone() method.

class TestClone2

{

int a;

double b;

public Object clone()

{

TestClone2 tc = new TestClone2();

tc.a = a;

tc.b = b;

return tc;

}

}

class CloneDemo3

{

public static void main(String a[])

{

TestClone2 tc1 = new TestClone2();

TestClone2 tc2;

tc1.a = 10;

tc1.b = 3.5;

tc2 = (TestClone2) tc1.clone();

System.out.println (tc2.a);

System.out.println (tc2.b);

}

}

Note: You need not declared CloneNotSupportedException and need not implement Cloneable interface if implementing your own clone() method.

Side Effects of Cloning

The side effects caused by cloning are sometimes difficult to see at first. It is easy to think that a class is safe for cloning when it actually is not. In general, you should not implement Cloneable interface for any class without good reason.

Example: This example demonstrates the side effect of cloning.

class TestShallowClone implements Cloneable

{

int a;

double b;

int c[];

public Object clone() throws CloneNotSupportedException

{

}

}

class ShallowCloneDemo

{

public static void main(String a[]) throws CloneNotSupportedException

{

return super.clone();

TestShallowClone tc1 = new TestShallowClone();

TestShallowClone tc2;

tc1.a = 10;

tc1.b = 3.5;

int c[] = new int[4];

for(int i = 0; i < 4; i++)

c[i] = i;

tc1.c = c;

for(int i = 0; i < 4; i++)

System.out.println ("tc1.c["+i+"]="+tc1.c[i]);

tc2 = (TestShallowClone) tc1.clone();

System.out.println ("tc2.a="+tc2.a);

System.out.println ("tc2.b="+tc2.b);

for(int i = 0; i < 4; i++)

System.out.println ("tc2.c["+i+"]="+tc2.c[i]);

for(int i = 0; i < 4; i++)

tc2.c[i] = i+4;;

for(int i = 0; i < 4; i++)

System.out.println ("tc2.c["+i+"]="+tc2.c[i]);

for(int i = 0; i < 4; i++)

System.out.println ("tc1.c["+i+"]="+tc1.c[i]);

}

}

Output:

tc1.c[0]=0

tc1.c[1]=1

tc1.c[2]=2

tc1.c[3]=3

tc2.a=10

tc2.b=3.5

tc2.c[0]=0

tc2.c[1]=1

tc2.c[2]=2

tc2.c[3]=3

tc2.c[0]=4

tc2.c[1]=5

tc2.c[2]=6

tc2.c[3]=7

tc1.c[0]=4

tc1.c[1]=5

tc1.c[2]=6

tc1.c[3]=7

Example: The following code eliminates the problem faced in the previous example by implementing deep cloning.

class TestDeepClone implements Cloneable

{

int a;

double b;

int c[];

public Object clone() throws CloneNotSupportedException

{

TestDeepClone tc = (TestDeepClone) super.clone();

int c[] = new int[4];

for(int i = 0; i < 4; i++)

c[i] = tc.c[i];

return super.clone();

}

}

class DeepCloneDemo

{

public static void main(String a[]) throws CloneNotSupportedException

{

TestDeepClone tc1 = new TestDeepClone();

TestDeepClone tc2;

tc1.a = 10;

tc1.b = 3.5;

int c[] = new int[4];

for(int i = 0; i < 4; i++)

c[i] = i;

tc1.c = c;

for(int i = 0; i < 4; i++)

System.out.println ("tc1.c["+i+"]="+tc1.c[i]);

tc2 = (TestDeepClone) tc1.clone();

System.out.println ("tc2.a="+tc2.a);

System.out.println ("tc2.b="+tc2.b);

for(int i = 0; i < 4; i++)

System.out.println ("tc2.c["+i+"]="+tc2.c[i]);

for(int i = 0; i < 4; i++)

tc2.c[i] = i+4;;

for(int i = 0; i < 4; i++)

System.out.println ("tc2.c["+i+"]="+tc2.c[i]);

for(int i = 0; i < 4; i++)

System.out.println ("tc1.c["+i+"]="+tc1.c[i]);

}

}

Output:

tc1.c[0]=0

tc1.c[1]=1

tc1.c[2]=2

tc1.c[3]=3

tc2.a=10

tc2.b=3.5

tc2.c[0]=0

tc2.c[1]=1

tc2.c[2]=2

tc2.c[3]=3

tc2.c[0]=4

tc2.c[1]=5

tc2.c[2]=6

tc2.c[3]=7

tc1.c[0]=0

tc1.c[1]=1

tc1.c[2]=2

tc1.c[3]=3

2.7 Methods useful in multi-threaded environment

In addition to methods discussed above, Object class provides support for thread communication in synchronized code through the following methods:

final void wait()

Causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

final void wait(long timeout) throws InterruptedException

Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or the specified amount of time has elapsed.

final void wait(long timeout, int nanos) throws InterruptedException


Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or some other thread interrupts the current thread, or the certain amount of time has elapsed.

final void notify()


Wakes up a single thread that is waiting on this object's monitor.

final void notifyAll()

Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait methods.

A thread invokes these methods on the object whose lock it holds. A thread waits for notification by another thread.

Friday, 19 June 2015

Java StringBuffer Class

StringBuffer is a peer class of String that provides much of the functionality of Strings. In contrast to String, StringBuffer represents growable and writeable character sequences.

StringBuffer may have characters and substrings inserted in the middle or appended to the end.

StringBuffer will automatically grow to make room for such additions and often has more characters pre-allocated than are actually needed, to allow room for growth.

Few important point related to StringBuffer class

  • StringBuffer is an Object like String.
  • StringBuffer class is also final like String class.
  • StringBuffer objects are mutable (can be modified) unlike String objects.

Constructors of StringBuffer Class


Methods of StringBuffer Class



Example:

class SBDemo1

{ public static void main(String args[])

{ StringBuffer sb1 = new StringBuffer();

System.out.println("sb1: length: "+sb1.length() + " capacity: " + sb1.capacity());

StringBuffer sb2 = new StringBuffer(100);

System.out.println("sb2: length: "+sb2.length() + " capacity: " + sb2.capacity());

StringBuffer sb3 = new StringBuffer("Hello");

System.out.println("sb3: length: "+sb3.length() + " capacity: " + sb3.capacity());

sb1.ensureCapacity(200);

System.out.println("sb1: length: "+sb1.length() + " capacity: " + sb1.capacity());

sb3.setLength(10);

System.out.println("sb3: length: "+sb3.length() + " capacity: " + sb3.capacity());

System.out.println("sb3: "+sb3);

sb3.setLength(3);

System.out.println("sb3: length: "+sb3.length() + " capacity: " + sb3.capacity());

System.out.println("sb3: "+sb3);

}

}

Output:

sb1: length: 0 capacity: 16

sb2: length: 0 capacity: 100

sb3: length: 5 capacity: 21

sb1: length: 0 capacity: 200

sb3: length: 10 capacity: 21

sb3: Hello

sb3: length: 3 capacity: 21

sb3: Hel

append() Method

It has overloaded versions for all the built-in types and for Object. These are the few of its form:

public StringBuffer append(char c)

public StringBuffer append(String str)

public StringBuffer append(boolean b)

public StringBuffer append(Object obj)

public StringBuffer append(int num)

public StringBuffer append(double

public StringBuffer append(char[] str)

public StringBuffer append(StringBuffer sb)

String.valueOf() method is called for each parameter to obtain its String representation. The result is appended to the current StringBuffer object. The buffer itself is returned by each version of append(). This allows subsequent calls to be chained together.

Note: If null string is appended then “null” gets appended.

insert() Method

The insert() method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings and Objects. Like append() method, it calls String.valueOf() method to obtain the string representation of the argument passed to it. This string is then inserted into the invoking StringBuffer object. These are the few of its form:

public StringBuffer insert(int offset, char c)

public StringBuffer insert(int offset, int c)

public StringBuffer insert(int offset, long l)

public StringBuffer insert(int offset, char[] str)

public StringBuffer insert(int offset, double d)

public StringBuffer insert(int offset, float f)

public StringBuffer insert(int offset, String str)

public StringBuffer insert(int offset, Object obj)

Example: The following example illustrates some of the methods discussed above.

class SBDemo2

{ public static void main(String args[])

{ String s; int a=42;

StringBuffer sb=new StringBuffer(40);

s=sb.append("a= ").append(a).append("!").toString();

System.out.println(s);

StringBuffer sb1=new StringBuffer("I Java!");

sb1.insert(2, "like ");

System.out.println(sb1);

System.out.println("Reverse of "+sb1+" is: "+sb1.reverse());

}

}

Output:

a= 42!

I like Java!

Reverse of I like Java! is: !avaJ ekil I

Monday, 15 June 2015

Java String important methods

Character Extraction Methods

The String class provides a number of ways in which characters can be extracted from a String object. Although the characters that comprise string within a String object cannot be indexed as if they were a character array, many of the String methods employ an index (or offset) into the string for their operation. Like arrays, the string indexes begin at zero.


Example: The following example illustrates the use of character extraction methods discussed above:

class ExtractionDemo

{ public static void main(String args[])

{ String s = "This is a Demo of character extraction methods";

char c = s.charAt(10);

System.out.println("Character at position 10: " + c);

char carray[] = s.toCharArray();

System.out.print("Character Array: ");

for(int i=0; i<carray.length; i++)

System.out.print(carray[i]);

System.out.println();

byte b[] = s.getBytes();

System.out.print("Byte Array: ");

for(int i=0; i<b.length; i++)

System.out.print((char) b[i]);

System.out.println();

int start = 10; int end = 14;

char buf[] - new char[end-start];

s.getChars(start, end, buf, 0);

System.out.println(buf);

}

}

Output:


Character at position 10: D

Character Array: This is a Demo of character extraction methods

Byte Array: This is a Demo of character extraction methods

Demo

String Comparison Methods



The regionMatches() method compares a specific region inside a styring with another specific region in another string. Thre is an overloaded form that allows you to ignore case in such comparisions.

For both versions, startIndex specifies the index at which the region begins within the invoking string object. The string being compared is specified by str2. The index at which the comparison will starts within the str2 is specified by str2StartIndex. The length of the substring being compared is passed in len.

Example: The following example illustrates the use of regionMatches() method.

class Region

{ public static void main(String args[])

{ String s="Yahoo!";

String s2="yahoo.com";

System.out.println(s.regionMatches(0,s2,0,5));

System.out.println(s.regionMatches(true,0,s2,0,5));//ignore case

System.out.println(s.resionMatches(-1,s2,-1,5));

}

}

Output:

false

true

false

Example: The following example illustrates the use of compareTo() method.

class CompareToDemo

{ public static void main(String args[])

{ String s="yahoo!";

String s2="Yahoo!";

String s3="yahoo";

System.out.println(s.compareTo(s2));

System.out.println(s.compareToIgnoreCase(s2));//ignore case

System.out.println(s.compareTo(s3));

}

}

Output:

32

0

1

startsWith( ) and endsWith( )


Example: The following example illustrates the use of startsWith() and endsWith() methods.

class ComparisonDemo

{ public static void main(String args[])

{ String name="Rahul Jain Januthariya";

System.out.println(name.startsWith("Rahul"));

System.out.println(name.startsWith("rahul"));

System.out.println(name.endsWith("Januthariya"));

System.out.println(name.startsWith("Jain",7));

}

}

Output:

true

false

true

true

The equals( ) v/s = =

The equals() method compares the characters inside a String object. The == compares two object references to see whether they refer to the same instance.

String Search Methods

String class provides methods that allow you to search a string for a specified character or substring. In all cases, methods return the index at which the character or substring is found or –1 on failure.


Methods for String Modification

Because String objects are immutable, whenever you want to modify a string, you must either copy it into a StringBuffer or use one of the following string methods, which will construct a new copy of the string with your modifications.





Note: The substring() methods throw IndexOutOfBoundsException if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.




Java Special String operations

1. String Literals

For each String literal in your program java automatically constructs String object. Thus, you can use a string literal to initialize a String object.

String s = “abc”;

Because a String object is created for every string literal, you can use a string literal at any place you can use a String object.

For example, you can call methods directly on a quoted string as it uses an object reference.

System.out.println(“abc”.length());

2. String Concatenation


In general, Java does not allow operators to be applied to String objects. The one exception to this rule is + operator, which concatenates two strings producing a String object as a result.

Example: The reference of the concatenated string “Rahul Jain Januthariya” will be stored in the reference variable name.

String name = “Rahul” + “ ”  +  “Jain”  +  “ ” + “Januthariya”

String Concatenation with other data types

If a string is concatenated with any data of type other than the string, the compiler converts the other operand (non-string) to its string equivalent.

Example:

String s = “four: “+ 2 + 2 ; System.out.println(s);

Output: four:22

String Conversion and toString( )

When Java converts data into its String representation during concatenation, it does so by calling one of the overloaded versions of the String conversion method valueOf() defined by String class. The valueOf() is a static method overloaded for all simple types and for type Object.

For the simple types, valueOf() returns string that contains the human-readable equivalent of the value with which it is called. For objects, valueOf() calls the toString() method on the object.

Every class inherits toString(), because it is defined by the Object class. However, the default implementation of the toString() is seldom sufficient. It displays name of the class followed by symbol “@” and then object-id (e.g. Box@ab1232), which is normally of no use. For most important classes that you create, you will want to override toString() and provide your own string representations.

You can do so by overriding the toString( ) method:

String toString()

Example:

class Box

{ double w, h, d;

Box( double w, double h, double d)

{ this.w=w; this.h=h; this.d=d;

}

public String toString()

{ return "Dimensions are "+w+" by "+h+" by "+d+".";

}

class ToStringDemo1

{ public static void main(String args[])

{ Box b=new Box(10,12,14);

String s="Box b: "+b; //concates box object

System.out.println(b);

System.out.println(s);

}

}

Output:

Dimensions are 10.0 by 12.0 by 14.0.

Box b: Dimensions are 10.0 by 12.0 by 14.0

Note: If toString() is not overridden, the output of this program will be something like:

Box@b8df17

Box b: Box@b8df17

Java String Constructors

The class String supports many constructors to create String objects. The simplest way to

construct a string is to assign a literal value to a String type variable:

String str = "This is a string";

The above statement will create a string object with the specified contents.

Some of the commonly used constructors are described below:

String()


Initializes a newly created String object so that it represents an empty character sequence:

String str = new String();

String (String str)

Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

Examples:

String str = new String("This is a string");

String str1 = new String(str);

The string str1 is a copy of string str. Although contents are same but str and str1 point to different string objects.

String(char[] value)

Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.

Example: String str in the following example will hold “abc”.

char cr[] = { ‘a’,’b’,’c’};

            String str = new String (cr);

String(char value[], int offset, int count)

Allocates a new String that contains characters from a sub-array of the character array argument.

Example: String str in the following example will hold “cde”.

char cr[] = { ‘a’,’b’,’c’,’d’,’e’,’f’ };

            String s = new String (cr,2,3);

String(byte b[])

Constructs a new String by decoding the specified array of bytes using the platform's default charset.

String(byte[]  b, int offset, int length)

Constructs a new String by decoding the specified subarray of bytes using the platform's default charset.

Even though Java's char type uses 16 bits to represent the Unicode character set, the typical format for strings on the Internet uses arrays of 8-bit bytes constructed from the ASCII character set. Because 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array. In each of the above constructors the byte to character
conversion is done by using the default character encoding of the platform.

Example: The following example illustrates the use of the constructors, which convert byte array into string.

class SubStringCons

{ public static void main(String args[])

{ byte ascii[] = { 65,66,67,68,69,70 };

String s = new String (ascii);

System.out.println(s);

String s1 = new String (ascii, 2, 3);

System.out.println(s1);

}

}

Output:

ABCDEF

CDE