Wrapper Classes in java

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 6:- Wrapper Classes in java

In Java, wrapper classes are used to convert primitive data types into objects, allowing them to be treated as objects. Each primitive data type has a corresponding wrapper class, and these classes are part of the java.lang package, so you don't need to import them explicitly.

The following are the primitive data types and their corresponding wrapper classes:

  1. byte - Byte
  2. short - Short
  3. int - Integer
  4. long - Long
  5. float - Float
  6. double - Double
  7. char - Character
  8. boolean - Boolean

Wrapper classes are particularly useful in scenarios where you need to use objects instead of primitive data types. For example, when working with collections like ArrayList or when using Java generics, as generics don't support primitive data types.

Here are some examples of using wrapper classes:

  1. Autoboxing (converting primitive to wrapper):

javaCopy code

int age = 25; Integer ageObj = age; // Autoboxing: converting int to Integer

  1. Unboxing (converting wrapper to primitive):

javaCopy code

Double heightObj = 1.75; double height = heightObj; // Unboxing: converting Double to double

  1. Parsing strings to primitive data types using wrapper classes:

javaCopy code

String numberStr = "123"; int number = Integer.parseInt(numberStr); // Converts string to int using Integer wrapper class

  1. Converting primitive to string using wrapper classes:

javaCopy code

double price = 19.99; String priceStr = Double.toString(price); // Converts double to string using Double wrapper class

Wrapper classes also provide useful utility methods, such as converting strings to numbers, comparing values, etc. When using wrapper classes, be cautious of possible null values as they can cause NullPointerExceptions. In Java 8 and above, you can use Optional to handle null values more safely.

2. Variable And Data Types

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support