Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

String Handling PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

String Handling

The javap command disassembles a class file. The javap command displays information about the
fields,constructors and methods present in a class file.
Syntax: javap fully_class_name
Ex: javap java.lang.Object

javap -c command
You can use the javap -c command to see disassembled code. The code that reflects the java bytecode.
Ex:javap -c java.lang.String

if you use the -verbose option, the bytecodes — plus a ton of other fascinating information about the
innards of the class — are displayed
Ex: javap -verbose java.lang.String

The important options of javap tool are as follows.

Option Description
-help prints the help message.
-l prints line number and local variable
-c disassembles the code
-s prints internal type signature
-sysinfo shows system info (path, size, date, MD5 hash)
-constants shows static final constants
-version shows version information

Object class In java:-


The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that
parent class reference variable can refer the child class object, know as upcasting.

Object class is present in java.lang package. Every class in Java is directly or indirectly derived from
the Object class. If a Class does not extend any other class then it is direct child class of Object and if extends
other class then it is an indirectly derived. Therefore the Object class methods are available to all Java classes.
Hence Object class acts as a root of inheritance hierarchy in any Java Program.
There are methods in Object class:
toString() : toString() provides String representation of an Object and used to convert an object to String.
The default toString() method for class Object returns a string consisting of the name of the class of which
the object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash
code of the object. In other words, it is defined as:
Inetrnal implementation

// Default behavior of toString() is to print class name, then


// @, then unsigned hexadecimal representation of the hash code
// of the object
public String toString()
{
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

It is always recommended to override toString() method to get our own String representation of Object.
For more on override of toString() method refer – Overriding toString() in Java
Note : Whenever we try to print any Object reference, then internally toString() method is called.

hashCode() : For every object, JVM generates a unique number which is hashcode. It returns distinct integers
for distinct objects. A common misconception about this method is that hashCode() method returns the
address of object, which is not correct. It convert the internal address of object to an integer by using an
algorithm. The hashCode() method is native because in Java it is impossible to find address of an object, so
it uses native languages like C/C++ to find address of the object.

Ex: public class Hashcode_Tostring {


static int last_roll = 100;
int roll_no;

// Constructor
Hashcode_Tostring()
{ roll_no = last_roll; last_roll++; }

// Overriding hashCode()
@Override
public int hashCode()
{ return roll_no; }

// Driver code
public static void main(String args[])
{
Hashcode_Tostring s = new Hashcode_Tostring();

// Below two statements are equivalent


System.out.println(s);
System.out.println(s.toString());
}
}
equals(Object obj) : Compares the given object to “this” object (the object on which the method is called).
It gives a generic way to compare objects for equality. It is recommended to override equals(Object obj)
method to get our own equality condition on Objects. For more on override of equals(Object obj) method
refer – Overriding equals method in Java

Note : It is generally necessary to override the hashCode() method whenever this method is overridden, so
as to maintain the general contract for the hashCode method, which states that equal objects must have
equal hash codes.

getClass() : Returns the class object of “this” object and used to get actual runtime class of the object. It can
also be used to get metadata of this class. The returned Class object is the object that is locked by static
synchronized methods of the represented class. As it is final so we don’t override it.

finalize() method : This method is called just before an object is garbage collected. It is called by
the Garbage Collector on an object when garbage collector determines that there are no more references
to the object. We should override finalize() method to dispose system resources, perform clean-up activities
and minimize memory leaks.
For example before destroying Servlet objects web container, always called finalize method to perform
clean-up activities of the session.
Note : finalize method is called just once on an object even though that object is eligible for garbage
collection multiple times.

public class FinalizeTest


{ @Override
protected void finalize()
{System.out.println("finalize method called"); }

public static void main(String[] args)


{ FinalizeTest t = new FinalizeTest();
System.out.println(t.hashCode());
t = null;
// calling garbage collector
System.gc();
System.out.println("end");

Upcasting and Downcasting :-


Assigning the object of subclass or reference variable of subclass to superclass type is known as upcasting

Super calss B ob1 = new B();


A ob2= new B(); (Up casting )
Or
B Sub calss A ob = new B();
Assigning the object of subclass or reference variable of superclass to subclass type is known as up Down
casting .

Super calss

A ob1 = new B();


B ob2 = (B) ob1 ;
B Sub calss

here are 4 classes in the java language to handle String.


I. Java.lang.String
II. Java.lang.Stringbuffer
III. Java.lang.Stringbuilder
IV. Java.util.StringTokenizer

Java.lang.String
String:-
1) String is a final class it is present in java.lang package.
2) String is nothing but a group of characters or character array.
3) Once we are creating String object it is not possible to do the modifications on existing object called
immutability nature.
4) In String class .equals() is used for content comparision.
Constructors:
public java.lang.String();
public java.lang.String(String);
public java.lang.String(char[]);
public java.lang.String(char[], int, int);
public java.lang.String(int[], int, int);
public java.lang.String(byte[], int, int, int);
public java.lang.String(byte[], int);

Use of Different Constructors :-


1) String str=new String(java.lang.String);
This constructor takes the String as a argument.
Ex:-
String str=new String(“rat”);
System.out.println(str);//rat

2) Stirng str=new String(char[]);


This constructor take the array of characters as a argument.
Ex:- char[] ch={'a','b','c','d'};
String str1=new String(ch);
System.out.println(str1); //abcd
3) String str=new String(char[] ,int ,int );
This contructor takes the array of characters with starting index and ending index. First int represent the starting
position Second int represent the ending position.
Ex:- char[] ch={'a','b','c','d'};
String str1=new String(ch,1,3);
System.out.println(str1);//bcd
String objects and their reference variables:-
Note 1:- String str1=”JAVA” ;

JAVA

Note 2:- String str2=str1 ;

JAVA

String str=”JAVA”;
Str.concat(“Class”);

JAVA

JAVAClass
String str=str.concat(“Class”);

Str
JAVA

Str JAVAClass

Good points:-
Without using new operator it is possible to create a object for the classes. such type of classes objects we
can called it as first-class objects .
Ex:-String

Creation of String object:-


To create a object for string class we are having two approaches
1) without using new operator(by using literal)
2) by using new operator

Creating a string object without using new operator(by using literal):-


String str1=”JAVA” ;
String str2=”Class”;
String str3=”Class”;

Whenever we create string literal first jvm goes to SCP(String constant pool ) and check if the string is already present
in the pool or not. If it is available it returns the existing reference from the pool , if it is not available a new String
object is created

Class

JAVA

In the above example two two objects are available


First time JVM will not find any string object with the name “Java” so JVM creates a new object.
Second time JVM will not find any String object with the name “Class” so JVM is creates the new object one more time.

Third time JVM is finding the string object with the content “Class” at this time JVM wont creates any new object just
JVM is return the reference to the same instance.
Advantage of above approach:-
If we are using above approach memory management is very good because duplicate content objects are not
presented in the String constant pool area. The objects which is present in the SCP area are unique objects.

Good points :-
Each and every object is stored in heap area. The heap area is divided into different pools.
1) Referenced pool: In the referenced pool all the objects references maintained.
2) Object pool: In this pool all the objects are located here by using new operator
3) Thread pool: In java we are able to create a thread object which not contains any lock
4) String pool: Without using new operator we are creating objects such type of the objects are located here(ex:-
String object).

Creating a string object by using new operator:-


String str=new String(“JAVA”);
JVM is creates a object and placed into the normal heap area and literal is placed into the string constant pool. So if
we are using above approach the object is created in the two areas heap area String constant pool area.
Ex:-
class Test
{
public static void main(String[] args)
{
String str1=new String("Java");
str1.concat("Imsc");
String str2=str1.concat("Class");
str2.concat("BIT");
System.out.println(str1);
System.out.println(str2);
}
}

String is immutability nature:-


Once we are creating string object it is not possible to do the modifications on the existing object is called immutability
nature.
Ex:-
class Test1
{
public static void main(String[] args)
{
String str="Java";
str.concat("Class");
System.out.println(str);
}
}
class Test2
{
public static void main(String[] args)
{
String str1="Java";
str1.concat("Bit");
String str2=str1.concat("Class");;
String str3=str2;
String str4="Java".concat("Imsc");
String str5=str4;
System.out.println(str2==str3);
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str2==str4);
System.out.println(str5==str4);
}
}

final vs Immutability in Java


final : In Java, final is a modifier which is used for class, method and variable also. When a variable is declared
with final keyword, it’s value can’t be modified, essentially, a constant.

Immutability : In simple terms, immutability means unchanging over time or unable to be changed. In Java,
we know that String objects are immutable means we can’t change anything to the existing String objects.

Differences between final and immutability


final means that you can’t change the object’s reference to point to another reference or another object,
but you can still mutate its state (using setter methods e.g). Whereas immutable means that the object’s
actual value can’t be changed, but you can change its reference to another one.
final modifier is applicable for variable but not for objects, Whereas immutability applicable for an object
but not for variables.
By declaring a reference variable as final, we won’t get any immutability nature, Even though reference
variable is final. We can perform any type of change in the corresponding Object. But we can’t perform
reassignment for that variable.
final ensures that the address of the object remains the same whereas the Immutable suggests that we can’t
change the state of the object once created.

class Geeks {
public static void main(String[] args)
{
final StringBuffer sb = new StringBuffer("Hello");

// Even though reference varibale sb is final


// We can perform any changes
sb.append("GFG");

System.out.println(sb);

// Here we will get Compile time error


// Because reassignment is not possible for final variable
sb = new StringBuffer("Hello World");

System.out.println(sb);
}
}

class Test3
{
public static void main(String[] args)
{
String str1=new String("Java");
String str2=new String("Class");
String str3=new String("Java");
String str4=new String("Java");
System.out.println(str1.compareTo(str2));//+ve
System.out.println(str1.compareTo(str3));//0
System.out.println(str1.compareTo(str4));// -ve
System.out.println(str4.compareTo(str2));//+ve
System.out.println(str1.compareToIgnoreCase("JAVA"));//0
System.out.println("BIT".compareTo(str2));//+ve
}
}

String class Methods:-

object class toString()method is executing .


class Object
{
public String toString()
{
//it is returns getClass@hashCode
}
}
class String extends Object
{
public String toString()
{
// it is returns the String content ;//overriding toString()
}
}
If we are printing the reference variable the string representation of object will be printed. The reference
variable internally calling the toString() method automatically. In the below case Object class toString() got
executed.

class Student
{
String sname;
int rollno;
Student(String sname,int rollno)
{
this.sname=sname;
this.rollno=rollno;
}
public static void main(String[] args)
{
Student s=new Student("JAVA",100);
System.out.println(s);//equal to //System.out.println(s.toString());
}
}

class Test
{
public static void main(String[] args)
{
String str1="JAVA";
str1.concat("Class");
System.out.println(str1);//JAVA
String str2="JAVA";
System.out.println(str1.equals(str2));//String class .equals()
StringBuffer sb=new StringBuffer("Imsc");
sb.append("Phy");
System.out.println(sb);//ImscPhy

User defined toString() is got executed:-


class Student
{
String sname;
int rollno;
Student(String sname,int rollno)
{
this.sname=sname;
this.rollno=rollno;
}
//overriding of the tostring method
public String toString()
{
return sname+"***"+rollno;
}
public static void main(String[] args)
{
Student s=new Student("JAVA",100);
System.out.println(s);
}
}
String class toString() method is executed:-
class Test
{
public static void main(String[] args)
{
String str="JAVA";
System.out.println(str);
System.out.println(str.toString());
}
}

Concat():- Concat() method present in the String class and it is used to combine the two String.
Length():- It is used to find out the length of the string
Difference between langth() method and langth variable:-
length()----method
length--variable
length is available in array to find the length of the array
Ex:-
int [] a={10,20,30};
System.out.println(a.length);//3
length() is method used to find the length of the given string.
Ex:-
String str="Java";
System.out.println(str.length());//4

charAt(int):- By using above method we are able to extract the character from particular index position.
class Test
{
public static void main(String[] args)
{
String str="JAVA";
System.out.println(str.charAt(1));
char ch="BIT".charAt(2);
System.out.println(ch);
}
}

Split(String):- By using split() method we are dividing string into number of tokens.
Ex:-
class Test
{
public static void main(String[] args)
{
String str="hi Java how r u";
String[] str1=str.split(" ");
for (int i=0;i<str1.length ;i++ )
{
System.out.println(str1[i]);
}
}
}
CompareTo(string anotherstring) and compareToIgnoreCase():-
1) By using compareTo() we are comparing two strings character by character such type of checking is
called lexicographically checking or dictionary checking.
2) compareTo() is return three values as outcome
a. zero (if both are equal)
b. positive (first string first character is having big character compare to second string )
c. negative(first string first character small character compare to second String )
3) compareTo() method comparing two string with case sensitive.
4) By using above method we are comparing two strings character by character by ignoring case.

Ex:
class Test
{
public static void main(String... BIT)
{
String str1="JAVA";
String str2="Class";
String str3="JAVA";
String str4="Class";
String str5="JAVA";
System.out.println(str1.compareTo(str2));
System.out.println(str1.compareTo(str4));
System.out.println(str2.compareTo(str4));
System.out.println(str4.compareTo(str2));
System.out.println(str1.compareTo(str3));
System.out.println(str1.compareTo(str5));
System.out.println(str1.compareToIgnoreCase(str5));
System.out.println(str2.compareToIgnoreCase(str4));
System.out.println(str1.compareToIgnoreCase(str3));
}
}

public boolean equals():-


a) String class equals() method is used for content comparison . It returns true of false value after
comparison.
b) The commonly used method to perform comparison.
c) We are comparing total content called deep comparison.
d) At the time of comparison the fallowing possibilities are occur.

True----------
False---------

class Test
{
public static void main(String[] args)
{
Test t1=new Test();
Test t2=new Test();
Test t3=t2;
System.out.println(t1.equals(t2));//false
System.out.println(t1.equals(t3));//false
System.out.println(t3.equals(t2));//true
String str1="Java";
String str2="Class";
String str3="Java";
System.out.println(str1.equals(str2));//false
System.out.println(str1.equals(str3));//true
System.out.println("Class".equals(str2));//true
System.out.println("JAVA".equals("Java"));//false
System.out.println("java".equals("java"));//true
}
}

Public Boolean equalsIgnoreCase():- By using above method we are comparing the strings
class Test
{
public static void main(String[] args)
{
String str1="java";
String str2="Class";
String str3="Java";
System.out.println(str1.equalsIgnoreCase(str2));//false
System.out.println(str1.equalsIgnoreCase(str3));//true
System.out.println("CLASS".equalsIgnoreCase(str2));//true
System.out.println("JAVA".equalsIgnoreCase("java"));//true
System.out.println("java".equalsIgnoreCase("java"));//true
}
}
== operator:-
It is used for reference comparison. Hence we can call shallow comparison.
Ex:-
class Test
{
public static void main(String[] args)
{
String s1=new String("Imsc");
String s2=new String("Phy/Chem");
String s3=new String("Imsc");
String s4=s1;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1==s3);
System.out.println(s1==s4);
}
}

Ex:-2
class Test
{
public static void main(String[] args)

{
String str1=new String("BIT");
String str2=new String("BIT");
System.out.println(str1==str2);//false
String str3="PHY";
String str4="PHY";
System.out.println(str3==str4);//false
}
}
Ex :-
class Test
{
Test(int i)
{
System.out.println("0 arg cons");
System.out.println(i);
}
public static void main(String[] args)
{
Test t1=new Test(10);
Test t2=new Test(10);
Test t3=new Test(10);
Test t4=t1;
System.out.println(t1==t2);//false
System.out.println(t2==t3);//false
System.out.println(t3==t1);//false
System.out.println(t1==t4);//true
}
}

getBytes():-By using this method we are converting String into the byte[] .the main aim of the converting
String into the byte[] format is some of the networks are supporting to transfer the data in the form of bytes
only at that situation is conversion is mandatory.

class Test
{
public static void main(String[] args)
{String str="JAVA";
byte[] b=str.getBytes();
System.out.println(b);
String str1=new String(b);
System.out.println(str1);
}
}

trim():- 1) trim() is used to remove the trail and leading spaces


2) this method always used for memory saver

Ex:-
class Test
{
public static void main(String[] args)
{
String str=" JAVA ";
System.out.println(str.length());
System.out.println(str.trim());
System.out.println(str.trim().length());
System.out.println(" BIT ".trim());
}
}
toUpperCase() and toLowerCase():-
The above methods are used to convert the lower case to the uppercase and uppercase to lowercase
character.
Ex:-
class Test
{
public static void main(String[] args)
{
String str="JAVA HOW R U";
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
System.out.println("JAVA".toLowerCase());
System.out.println("imsc".toUpperCase());
}
}
Java.lang.String.endsWith() and Java.lang.String.startsWith():-
endsWith() is used to find out if the string is ending with particular character/string or not.
startsWith() used to find out the particular String starting with particular character/string or not.
class Test
{
public static void main(String[] args)
{
String str="JAVA how r u";
System.out.println(str.endsWith("u"));//true
System.out.println(str.endsWith("how"));//false
System.out.println(str.startsWith("d"));//false
System.out.println(str.startsWith("r"));//true
}
}
substring(int startingposition) & substring(int startingposition,int endingposition ):-
By using above method we are getting substring from the whole String.
In the above methods
starting position parameter value is including
ending position parameter value is excluding
class Test
{
public static void main(String[] args)
{
String str="JAVA how r u";
System.out.println(str.substring(2));//VA how r u
System.out.println(str.substring(1,7));//AVA h
System.out.println(" JAVA ".substring(2,5));//AVA
} }
replace(char oldchar,char newchar) replace(Stirng oldString,String newString):-
by using above method we are replacing the particular character of the String. And particular portion of the
string.

Ex:-
class Test
{
public static void main(String[] args)
{
String str="Java how r u";
System.out.println(str.replace('a','A'));//JAvA
System.out.println(str.replace("how","who"));//Java who r u
}
}

Java.lang.Stringbuffer Class:-
1) String Buffer is a class present in the java.lang package.
2) StringBuffer is a final class so it can’t be inherited.
3) StringBuffer is a mutable class so it is possible to change the content in the same location.
4) StringBuffer .equals() method is used for reference comparison.

Constructors:-
1) StringBuffer sb=new StringBuffer();
2) StringBuffer sb1=new StringBuffer(int capacity);
3) StringBuffer sb2=new StringBuffer(String str);

Ex:-
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default capacity 16
StringBuffer sb1=new StringBuffer(5);
System.out.println(sb1.capacity());//your provided capacity
StringBuffer sb2=new StringBuffer("Java");
System.out.println(sb2.capacity());//initial capacity+provided
string length 24
System.out.println(sb2.length()); //8
}
}

StinrgBuffer is mutable:- Once we are creating a StringBuffer Object it is possible to the modification on
existing object is called mutability nature.

Ex:-
class Test
{
public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("JAVA");
s1.append("Class");//mutability
System.out.println(s1);
StringBuffer s2=new StringBuffer("BIT");
StringBuffer s3=s1;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1==s2);
System.out.println(s1==s3);
}
}
class Test
{
public static void main(String[] args)
{
Test t1=new Test();
Test t2=t1;
Test t3=new Test();
System.out.println(t1.equals(t2));//true
System.out.println(t1.equals(t3));//false
String str1="JAVA";
String str2="JAVA";
System.out.println(str1.equals(str2));//true
StringBuffer sb1=new StringBuffer("BIT");
StringBuffer sb2=new StringBuffer("BIT");
StringBuffer sb3=sb2;
System.out.println(sb1.equals(sb2));//flase
System.out.println(sb2.equals(sb3));//true
}
}

Note 1:- it is possible to change the content of StringBuffer Object


Note2:- StringBuffer .equals() is used for reference comparison(address comparision)
Note 3:- == operator is used for reference comparison (address comparison)

reverse():-
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("JAVA");
System.out.println(sb);
System.out.println(sb.delete(1,3));
System.out.println(sb);
System.out.println(sb.deleteCharAt(1));
System.out.println(sb.reverse());
}
}

Append():-
By using this method we can append the any values at the end of the string.
Ex:-
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("JAVA");
String str=" Class ";
int a=30000;
sb.append(str);
sb.append(a);
System.out.println(sb);
}
}
Insert():-
By using above method we are able to insert the string any location of the existing string.
Ex:-
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("JAVA");
sb.insert(0,"hi ");
System.out.println(sb);
}
}

indexOf() and lastIndexOf():-


Ex:-
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("hi java hi");
int i;
i=sb.indexOf("hi");
System.out.println(i);
i=sb.lastIndexOf("hi");
System.out.println(i);
}
}

replace():-
class Test
{
public static void main(String[] args)
{
StringBuffer sb=new StringBuffer("hi JAVA hi");
sb.replace(0,2,"oy");
System.out.println("after replaceing the string:-"+sb);
}
}

Ex:-2
class Test
{
public static void main(String[] args)
{
StringBuffer sb1=new StringBuffer("JavaClass");
StringBuffer sb2=new StringBuffer("Java");
StringBuffer sb3=new StringBuffer("Java");
StringBuffer sb4=sb3;
System.out.println(sb1.equals(sb2));//false
System.out.println(sb1.equals(sb3));//flase
System.out.println(sb1.equals(sb4));//false
System.out.println(sb2.equals(sb3));//false
System.out.println(sb3.equals(sb4));//true
System.out.println(sb1==sb2);//flase
System.out.println(sb3==sb4);//true
System.out.println(sb2==sb3);//false
}
}

Java.lang.StringBuilder Class
1) Introduced in jdk1.5 version.
2) StringBuilder is identical to StringBuffer except for one important difference.
3) Every method present in the StringBuilder is not Synchronized means that is not thread safe.
4) multiple threads are allow to operate on StringBuilder methods hence the performance of the
application is increased.

Cloneable:-
1) The process of creating exactly duplicate object is called cloning.
2) We can create a duplicate object only for the cloneable classes .
3) We can create cloned object by using clone()
4) The main purpose of the cloning is to maintain backup.

class Test implements Cloneable


{
int a=10;
int b=20;
public static void main(String[] args)throws
CloneNotSupportedException
{
Test t1=new Test();
Test t2=(Test)t1.clone();
t1.a=100;
t1.b=200;
System.out.println(t1.a+"----"+t1.b);
System.out.println(t2.a+"----"+t2.b);
}
}

Synchronized :-
 Synchronized modifier is the modifier applicable for methods but not for classes and variables.
 If a method or a block declared as synchronized then at a time only one Thread is allowed to operate
on the given object.
 The main advantage of synchronized modifier is we can resolve data inconsistency problems.
 But the main disadvantage of synchronized modifier is it increases the waiting time of the Thread and
effects performance of the system .Hence if there is no specific requirement it is never recommended
to use.
 The main purpose of this modifier is to reduce the data inconsistence problems.
Non-synchronized
Wrapper classes
1) Represent primitive data types as a Object form we required some classes these classes are called wrapper
classes.
2) All wrapper classes present in the java.lang package.
3) Int , byte…. Acts as a primitives we can make the primitives into the objects is called wrapper classes the
wrapper classes are Integer,Short, Float…
4) We are having 8 primitive data types hence SUN microsystem people providing 8 wrapper classes.

5) Data types and corresponding wrapper classes:-


byte ----- Byte
short ----- Short
int ----- Integer
long ----- Long
float ----- Float
double ----- Double
boolean ----- Boolean
char ------ Character
6) Byte,Short,Integer,Long,Float,Double these are child classes of Number class.
Constructors of wrapper classes:-
All most all wrapper classes contain two constructors:-
1. Integer i=new Integer(10);
2. Integer i=new Integer(“10”);
Primitives Wrapper classes Fallowing constructor arguments

byte Byte Byte or String


short Short Short or String
int Integer Int or String
long Long Long or String
float Float Float or double or String
double Double double or String
char Character Char
Boolean Boolean Boolean or String

Byte is taking two arguments:-


Maximum wrapper class taking String as a argument at that situation frequently we are getting
NumberFormatException.
class Test
{
public static void main(String[] args)
{
float f=10.7f;
Float f1=new Float(f);
System.out.println(f1);
Float f2=new Float("10");
System.out.println(f2);
Float f3=new Float("ten");
System.out.println(f3);//NumberFormatException
Integer i1=new Integer(2);
System.out.println(i1);
Integer i2=new Integer("two");
System.out.println(i2);//NumberFormatException
}
}
Ex:2
class Test
{
public static void main(String[] args)
{
int a=10;//primitive variable
System.out.println(a);
System.out.println(a.toString());//CE:-int cant be
dereferenced
Integer i=new Integer("100");//reference variable
System.out.println(i);
System.out.println(i.toString());
}
}
The main importance of wrapper classes:-
1. To convert a data types into the object means we are giving object from data types by using constructor.
2. To convert String into the data types by using parsexxx() method

Utility methods:-
1. valueOf()
2. xxxValue()
3. parsexxx()
4. toString()

1) valueOf():-
By using valueof() we are creating wrapper object and it is a alternative to the constructor.
Ex:
class Test
{
public static void main(String[] args)
{
//by using constructor converting String/primitive to wrapper object
Integer i=new Integer(10);
System.out.println(i);
//by using valueOf() converting String/primitive to the wrapper object
Boolean b=Boolean.valueOf("true");
System.out.println(b);
}
}

2) XxxValue():-
by using XXXValue() method we are converting wrapper objects into the corresponding primitive values.

Ex:
class Test
{
public static void main(String[] args)
{
Integer i=Integer.valueOf(150);
System.out.println("byte value :"+i.byteValue());//-106
System.out.println("short value :"+i.shortValue());//150
System.out.println("int value :"+i.intValue());//150
System.out.println("long value :"+i.longValue());//150
System.out.println("float value :"+i.floatValue());//150.0
System.out.println("double value :"+i.doubleValue());//150.0
Character c=new Character('s');
char ch=c.charValue();
System.out.println(ch);
Boolean b=new Boolean(false);
boolean bb=b.booleanValue();
System.out.println(bb);
}
}
parseXXX():-
by using above method we are converting String into the corresponding primitive.

Ex:1
class Test
{
public static void main(String[] args)
{
String str1="10";
String str2="20";
System.out.println(str1+str2);//1020
int a=Integer.parseInt(str1);
float f=Float.parseFloat(str2);
System.out.println(a+f);//30.0
}
}
toString():-

class Object
{
Public string toString()
{
return getClass@hashcode;
}
};
class WrapperClasses extends Object
{
//overriding the toString()
Public string toString()
{
return the corresponding value
}
}

Ex :-
class Test
{
public static void main(String[] args)
{
Integer i=new Integer(10);
System.out.println(i.toString());
Float f=new Float(10.7);
System.out.println(f.toString());
}
}
Autoboxing and Autounboxing:-(introduced in the 1.5 version)
Until 1.4 version we are not allowed to place primitive in the palc wrapper and wrapper in the place of
primitive. The programmer is responsible person to do the explicit conversion primitive to the wrapper and
wrapper to the primitive.

Autoboxing:-
Integer i=10;
System.out.println(i);

The above statement does not work on the 1.4 and below versions. The auto conversion of the primitive into the
Wrapper object is called the autoboxing these conversions done by compiler at the time of compilation.

Autounboxing:-
int a=new Integer(100);
System.out.println(a);
The auto conversion of the wrapper object to the primitive value is called auto unboxing and these conversions are
done by compiler at the time of compilation.

class Test
{
static Integer i=10;//i is wrapper object
static int j;//j is primitive variable
static void print(int i)
{
j=i;
System.out.println(j);
}
public static void main(String[] args)
{
print(i);
System.out.println(j);
}
}

You might also like