Java is an object-oriented programming language that is widely used for developing applications. It provides a set of primitive data types such as int, float, double, etc. However, there are situations where we need to treat these primitive data types as objects. This is where Java Wrapper Classes come into play.
Java Wrapper Classes are a set of classes that provide a way to convert primitive data types into objects and vice versa. They are used to wrap the primitive data types and provide additional functionality such as conversion, comparison, and manipulation of data.
The Java Wrapper Classes are:
Each of these classes provides a set of methods that can be used to manipulate the data. For example, the Integer class provides methods to convert an integer to a string, compare two integers, and perform arithmetic operations on integers.
Here are some code examples that demonstrate the use of Java Wrapper Classes:
int num = 10; Integer obj = new Integer(num);
In this example, we are converting the primitive data type int to an object of the Integer class.
Integer obj = new Integer(10); int num = obj.intValue();
In this example, we are converting an object of the Integer class to a primitive data type int.
Integer obj1 = new Integer(10); Integer obj2 = new Integer(20); int result = obj1.compareTo(obj2);
In this example, we are comparing two objects of the Integer class using the compareTo() method.
String str = "10"; Integer obj = Integer.valueOf(str);
In this example, we are converting a string to an object of the Integer class using the valueOf() method.
Integer obj = new Integer(10); String str = obj.toString();
In this example, we are converting an object of the Integer class to a string using the toString() method.
Java Wrapper Classes provide a way to treat primitive data types as objects and provide additional functionality. They are used extensively in Java programming and are an important concept to understand.