Java Java Tutorial Java Methods Java Classes Java File Handling Java Reference



Java Wrapper Classes

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:

  • Byte
  • Short
  • Integer
  • Long
  • Float
  • Double
  • Boolean
  • Character

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.

Code Examples

Here are some code examples that demonstrate the use of Java Wrapper Classes:

Example 1: Converting a primitive data type to an object

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.

Example 2: Converting an object to a primitive data type

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.

Example 3: Comparing two objects

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.

Example 4: Converting a string to an object

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.

Example 5: Converting an object to a string

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.

Conclusion

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.

References

Activity