0% found this document useful (0 votes)
99 views10 pages

Java Wrapper Classes and Methods Explained

Uploaded by

Ilesh Shah
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views10 pages

Java Wrapper Classes and Methods Explained

Uploaded by

Ilesh Shah
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Chapter 5

Using Library Classes

Class 10 - Sumita Arora ICSE Computer Applications with BlueJ

Objective Type Questions

Question 1

Which of these is a wrapper for data type int ?

1. Integer

2. Long

3. Byte

4. Double

Answer

Integer

Reason — Integer is a wrapper class for int data type.

Question 2

Which of these is wrapper for simple data type char?

1. Float

2. Character

3. String

4. Integer

Answer

Character

Reason — Character is wrapper for simple data type char.

Question 3

Which following method of wrapper Integer will convert the value of an object into int?

1. bytevalue( )

2. int intValue( )

3. Bytevalue( )

4. Byte Bytevalue()

Answer
int intValue( )

Reason — int intValue( ) function returns the value of the invoking object as an int.

Question 4

Which of the following is/are not valid wrapper classes?

1. Integer

2. Float

3. integer

4. character

5. Character

Answer

integer, character

Reason — All the names of wrapper classes begin with capital letters. Thus, Integer, Float and
Character are valid wrapper classes.

Question 5

The Wrapper class objects' value is comparable to primitive type values. True/false ?

Answer

True

Reason — With Autoboxing/unboxing feature, we can use the wrapper class object in the same way
as we use a primitive type data. Thus, the Wrapper class objects' value is comparable to primitive
type values.

Question 6

Write the return data type of the following functions :

1. startsWith( )

2. random( )

Answer

1. boolean

2. double

Question 7

Which of the following statements are true ?

1. The Integer class has a String- and an int-constructor.

2. The Integer has a floatValue( ) method.

3. The wrapper classes are contained in the [Link] package.


4. The Double class has constructors for type double and float.

Answer

The Integer class has a String- and an int-constructor.


The Integer has a floatValue( ) method.
The Double class has constructors for type double and float.

Reason — The Integer class has a String- and an int-constructor as we can create Integer objects by
passing String and int type values at the time of object creation.

The Integer has a floatValue( ) method. The method float floatValue( ) returns the value of the
invoking object as a float primitive type.

The Double class has constructors for type double and float as we can create Double objects by
passing double and float type values at the time of object creation.

Question 8

What is the output of this program?

class Output {

public static void main(String args[])

Integer i = new Integer(257);

byte x = [Link]();

[Link](x);

1. 0

2. 1

3. 256

4. 257

Answer

Reason — The byte datatype stores values in the range 0..255 and if we try to convert an integer
value bigger than 255 using byteValue( ) method then, the byte data type will convert the value into
the range of 0...255 in cyclic fashion. Thus, integer value 256 and 257 will be converted to byte
value 0 and 1 respectively.

Question 9

What is the output of this program ?

class Output
{

public static void main(String args[])

Integer i = new Integer(514);

float x = [Link]();

[Link](x);

1. 0

2. 1

3. 257

4. 514.0

Answer

514.0

Reason — The float data type stores decimal/floating point numbers. Thus, Integer object 514 will be
converted and stored as float value 514.0.

Assignment Questions

Question 1

What are wrapper classes?

Answer

Wrapper classes are specially designed classes that act as wrappers to primitive data types so that
primitive values can be accessed as objects.

For example, Integer is a wrapper class for int data type and Float is a wrapper class for float data
type.

Question 2

Name the numeric wrapper classes in Java.

Answer

The numeric wrapper classes in Java are:

1. Byte for byte data type

2. Short for short data type

3. Integer for int data type

4. Float for float data type


5. Long for long data type

6. Double for double data type

Question 3

What is the need of wrapper classes when there are primitive datatypes ?

Answer

The need of wrapper classes when there are primitive data types are as follows:

1. Java is an object oriented language where everything is used as objects. The wrapper classes
enable a primitive value to be used as objects. As objects, they can be used with all types of
classes and their methods.

2. Wrapper classes provide many ready-to-use utility methods such as converting a string
having primitive type value to equivalent primitive form. For example, "10" can be converted
to integer 10 using a wrapper class method.

3. Primitive data types are passed by value, but objects are passed by reference. Wrapper
classes facilitate passing primitives by reference, as an argument to a method, if so required.

Question 4

When do the numeric wrapper class constructors raise NumberFormatException ?

Answer

The numeric wrapper class constructors may raise NumberFormatException at the time of
conversion of String arguments to primitive data types. The exception is raised when the String
argument cannot be converted to the desired data type.

For example,

int val = [Link]("A");

Here, the String argument "A" cannot be converted to int type and therefore,
NumberFormatException is thrown.

Question 5

Name some methods that are commonly available in all wrapper classes and in all numeric wrapper
classes.

Answer

Methods available in all wrapper classes are:

1. toString()

2. valueOf()

Methods commonly available in all numeric wrapper classes are:

1. xxxValue() methods — byteValue(), shortValue(), intValue(), longValue(), floatValue(),


doubleValue().
2. parseXXX methods — parseByte(), parseShort(), parseInt(), parseFloat(), parseLong(),
parseDouble().

Question 6

What is autoboxing ? What is auto-unboxing ? How are these useful ?

Answer

The automatic conversion of primitive data type into an object of its equivalent wrapper class is
known as Autoboxing.

The automatic conversion of an object of wrapper class into primitive data type is known as Auto-
unboxing.

These are useful as:

1. Autoboxing/auto-unboxing let us use primitive types and wrapper class objects


interchangeably.

2. It simplifies the process of converting between primitive types and their corresponding
wrapper classes as the compiler does it automatically.

Question 7

Which methods return primitive values from Wrapper class objects?

Answer

The methods which return primitive values from Wrapper class objects are as follows:

1. xxxValue() methods — byteValue(), shortValue(), intValue(), longValue(), floatValue(),


doubleValue().

2. parseXXX methods — parseByte(), parseShort(), parseInt(), parseFloat(), parseLong(),


parseDouble().

Question 8

Which methods return Wrapper class objects from primitive values ?

Answer

The methods which return Wrapper class objects from primitive values are as follows:

1. [Link]()

2. [Link]()

3. [Link]()

4. [Link]()

5. [Link]()

6. [Link]()

Question 9
Predict the output.

int res = [Link]("100").compareTo(new Integer(100));

[Link](res);

Answer

Output

Explanation

Here, [Link]("100") returns an Integer object storing 100 and new Integer(100) creates a
new Integer object with the value 100.

[Link]() compares two Integer objects numerically, after auto-unboxing is performed by


the compiler and the Integer objects are converted to integer type values. The function compareTo()
returns 0 as primitive values of both the objects are equal.

Question 10

Find the error:

Integer obj = new Integer("A");

[Link](obj);

Answer

Integer obj = new Integer("A"); statement will generate NumberFormatException at the time of
conversion of String argument "A" to Integer object. The exception is raised because "A" is not a valid
string representation of a numeric value, therefore it cannot be converted to Integer object.

Question 11

Find the error :

double n2 = [Link]("2");

double n3 = [Link]("OCA");

[Link](n2 + " " + n3);

Answer

double n3 = [Link]("OCA"); statement will generate NumberFormatException at the


time of conversion of String argument "OCA" to double data type. The exception is raised because
"OCA" is not a valid string representation of a numeric value, therefore it cannot be converted to
Integer object.

Question 12

Predict the output :

double n1 = [Link]("8.0");

double n2 = [Link]("2");
[Link](n1 + " " + n2);

Answer

Output

8.0 2.0

Explanation

parseDouble() converts String arguments passed to it into double data type. Thus, 8.0 will be
assigned to n1 and 2.0 will be assigned to n2.

The values of n1 and n2 will be printed with a space " " between them.

Question 13

What important is automatically happening in following code ?

long a = 124235L;

Long b = new Long(a);

long c = [Link]();

[Link](c);

Answer

Long b = new Long(a);

This statement boxes long type a into a Long object b, boxing a primitive type into a Wrapper class
object.

long c = [Link]();

This statement unboxes Long object b and stores it in long variable c, converting a Wrapper class
object into a primitive data type.

Question 14

Predict the output :

Integer c = 155;

Integer d = 155;

[Link](c == d);

[Link]([Link](d));

Answer

Output

false

true

Explanation
c == d compares two Integer objects and returns false because when we compare two objects using
the operator "==", Java compares their reference i.e., their memory address and not their value.
Since these are two different objects stored at two different locations in memory, Java produces
result false

[Link](d) method compares the values of the Integer objects after they are auto-unboxed by the
compiler and converted to primitive data types. The function returns true as both the primitive type
values are equal.

Question 15

In the following code, identify the statement where autoboxing is taking place :

Integer i = new Integer(10);

if (i < 100)

[Link](i);

else

[Link](i + 10);

Answer

Autoboxing is not taking place in this code as in the statement Integer i = new Integer(10);, we are
explicitly making an Integer object.

if(i < 100)

Auto-unboxing is taking place in this statement, as the value of an object cannot be compared to a
numeric value 100 directly but a primitive integer type value can be compared. So, unboxing takes
place before the value of i gets compared to 100.

[Link](i);

Auto-unboxing is happening in this statement as directly an object cannot be printed but a primitive
value can be printed. So, unboxing occurred before the value of i gets printed.

[Link](i + 10);

Auto-unboxing is taking place in this statement, as the value of an object cannot be used
with + operator like a primitive integer type value. Thus, i gets auto-unboxed to a primitive type value
and the value of i gets modified by the + operator.

Question 16

From the following code, do the following :

(i) find its output.

(ii) find out the statements where autoboxing is taking place.

(iii) find out the statements where auto-unboxing is taking place.

Short age = [Link]("35");

Integer salary = [Link]("2400");


Float height = [Link]("1.78"); // in meters

Double weight = [Link] ("72.6");

double b = weight / (height * height);

[Link](age + "takes home" + salary);

[Link]("bmi : " + b);

Answer

(i)

Output

35takes home2400

bmi : 22.913774881799036

(ii) Autoboxing is not happening in this code as the valueOf() method returns the Wrapper class
object. Thus, we are explicitly boxing the primitive type values to Wrapper objects in the following
statements:

Short age = [Link]("35");

Integer salary = [Link]("2400");

Float height = [Link]("1.78"); // in meters

Double weight = [Link] ("72.6");

(iii) Auto-unboxing is taking place in the following statements:

1. double b = weight / (height * height);


The Wrapper class objects weight and height are being auto-unboxed before mathematical
operations can be performed on them.

2. [Link](age + "takes home" + salary);


The Wrapper class objects age and salary are being auto-unboxed before they can be printed
as objects cannot be printed directly like primitive data type values.

Common questions

Powered by AI

The line 'double n3 = Double.parseDouble("OCA");' will throw a NumberFormatException because "OCA" is not a parsable number. The Double.parseDouble() method expects a String that represents a valid floating-point number. To avoid this error, input validation should be used to ensure that Strings intended for numeric conversion are valid. This can involve using regular expressions to verify numeric format or using a try-catch block to handle exceptions when invalid data is met, thereby maintaining program robustness .

The result '0' in the statement 'Integer.valueOf("100").compareTo(new Integer(100));' signifies that both Integer objects hold equivalent values. The compareTo() method in Java compares two Integer objects numerically and returns a zero if they are equal, positive if the caller is greater, and negative if less. Despite different methods of instantiation, the resulting Integer objects encapsulate identical primitive values, leading to an equal comparison result upon evaluation, showcasing the equivalence of numeric-value representation across different Object instantiation methods .

Autoboxing in Java is the automatic conversion of primitive data types into their corresponding wrapper class objects, such as converting an int to an Integer object. Auto-unboxing is the reverse process, where a wrapper class object is converted into its corresponding primitive type. These features are significant because they simplify coding, allowing developers to use primitive types and their wrapper classes interchangeably without manual conversion. This automation helps in reducing boilerplate code and avoids errors that might arise from manual conversions, thus enhancing code readability and efficiency .

When comparing two Integer objects in Java, using '==' checks for reference equality, meaning it compares whether the two objects point to the same memory location. This can lead to false when comparing two different Integer objects with the same value because they may reside in different memory locations. In contrast, the '.equals()' method evaluates the content equality of the two Integer objects, meaning it compares the actual value stored within each object. Using '.equals()' will return true if the values are the same, regardless of the objects' memory addresses .

Wrapper classes in Java enable primitive values to be used as objects, facilitating their use with object-oriented features. Java is object-oriented, meaning that operations are typically performed on objects. Wrapper classes convert primitive values into corresponding objects, allowing them to interact with other objects and methods. For instance, Integer is the wrapper class for the primitive data type int. Using wrapper classes, methods that require objects can accept primitives as they can be converted into objects automatically. Autoboxing simplifies this process by automatically converting primitives to wrapper objects when needed .

Numeric wrapper classes in Java provide a robust way to handle parsing exceptions like NumberFormatException. These exceptions occur during conversion operations where a String cannot be converted into a number type. Constructors or methods such as Integer.parseInt() or Double.parseDouble() can throw a NumberFormatException if the provided String does not contain a parsable number. Wrapper classes encapsulate these operations into methods that can easily manage and report such errors, making them crucial for input validation and exception handling in Java programs .

The 'parseInt()' and 'valueOf()' methods in Java's wrapper classes serve different purposes. 'parseInt()' is a method that converts a String into a primitive int, thus providing a way to parse numeric Strings directly into primitive types. It is useful for applications needing pure numeric data from textual sources. In contrast, 'valueOf()' returns an object instance of the wrapper class with the value of the specified String. This method serves when object manipulation or operation with additional object utility methods is required. While both convert Strings with numeric values to corresponding numerical representations, 'parseInt()' yields a primitive, and 'valueOf()' yields an object .

Understanding numeric ranges is essential when using methods like 'byteValue()' because improper handling can lead to unexpected results due to overflow. The 'byteValue()' method converts an Integer to a byte, which has a range of -128 to 127. If an Integer lies outside this range, it will be wrapped within the specified byte range, possibly altering its intended value. For instance, an Integer value of 257, when converted to a byte, results in 1 due to wrap-around. This understanding helps developers predict and manage such behavior, ensuring that operations on data types do not lead to incorrect values within applications .

The statement 'Integer obj = new Integer("A");' throws a NumberFormatException because it attempts to convert the String "A" into an Integer. Since "A" is not a numeric value, the conversion cannot occur, leading to this exception. To handle this, input validation should be performed prior to conversion to ensure that the String contains a valid number representation. One way is to use a try-catch block to catch the exception and manage it gracefully by informing the user or attempting corrective measures, such as prompting for a different input .

The statement is accurate. Wrapper classes allow primitive data types to be treated as objects, thus enabling their use with classes and methods that require objects as parameters or operands. This ability is vital in Java, which is an object-oriented language prioritizing operations via objects. Through autoboxing, primitive types can be automatically converted to wrapper objects whenever necessary, integrating seamlessly with Java's object-oriented frameworks and APIs. This feature enhances flexibility and consistency within code ecosystems that demand object utilization or offer extended functionality via object methods .

You might also like