0% found this document useful (0 votes)
9 views36 pages

Varargs and Wrapper Classes

The document explains the concept of varargs in Java, which allows methods to accept a variable number of arguments, simplifying method definitions and improving code readability. It also covers wrapper classes that encapsulate primitive types, detailing autoboxing and auto-unboxing features introduced in JDK 5 that streamline the process of converting between primitive types and their corresponding wrapper objects. Additionally, the document includes examples and important considerations regarding the use of varargs and wrapper classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views36 pages

Varargs and Wrapper Classes

The document explains the concept of varargs in Java, which allows methods to accept a variable number of arguments, simplifying method definitions and improving code readability. It also covers wrapper classes that encapsulate primitive types, detailing autoboxing and auto-unboxing features introduced in JDK 5 that streamline the process of converting between primitive types and their corresponding wrapper objects. Additionally, the document includes examples and important considerations regarding the use of varargs and wrapper classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Varargs

Varargs, short for variable arguments, is a feature


introduced in Java 1.5 that allows methods to accept an
arbitrary number of arguments. This is particularly useful
when the number of arguments is not known in advance.
Before varargs, developers had to use overloaded
methods or arrays, which could lead to maintenance
issues and more complex code
Syntax and Usage
The syntax for varargs is straightforward. You use three
dot
(...) after the data type in the method's parameter list.
Here is
an example:
public static void display(String... values) {
System.out.println("display method invoked");
for (String value : values) {
System.out.println(value);
}
}

public static void main(String[] args) {


display(); // zero arguments
display("my", "name", "is", "varargs"); // multiple arguments
• }
Rules for Varargs
When using varargs, there are some important rules to
follow:
1. Only one varargs parameter: A method can have
only one
varargs parameter.
2. Last parameter: The varargs parameter must be the
last
parameter in the method's parameter list.
void method(String... a, int... b) {} // Compile-time error
void method(int... a, String b) {} // Compile-time error
Advantages of Varargs
Simplifies method definitions: No need to overload
methods for
different numbers of arguments.
Improves readability: Makes the code cleaner and
easier to
understand
public class VarargExample {
public int sumNumbers(int... args) {
int sum = 0;
for (int num : args) {
sum += num;
}
return sum;
}

public static void main(String[] args) {


VarargExample example = new VarargExample();
System.out.println("Sum: " + example.sumNumbers(1, 2, 3)); // Output: Sum: 6
System.out.println("Sum: " + example.sumNumbers(4, 5)); // Output: Sum: 9
}
}
Important Considerations
Overloading: Varargs methods can be overloaded, but it
may
lead to ambiguity. For example, if you have two
methods test(int... vargs) and test(int n,
int...
vargs), the compiler may get confused when
calling test(1)

Performance: While varargs are convenient, if you know


the
exact number of arguments, method overloading might
be a
better choice for performance reasons
Wrapper classes
Wrapper classes
• primitive types, such as int or double hold the
basic data types supported by the language.

• Many of the standard data structures


implemented by Java operate on objects.

• Wrappers are classes that encapsulate a primitive


type within an object.
Wrapper classes
• The type wrappers are Double, Float, Long,
Integer, Short, Byte, Character, and
Boolean.

• Offer many methods.


Wrapper classes
Primitive datatypes can be converted into object types by using
wrapper classes .

Simple Type Wrapper class


-------------- ------------------
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
Wrapper classes
Character
Character is a wrapper around a char.

Character(char ch)
Here, ch specifies the character that will be wrapped by the Character object being
created.

To obtain the char value contained in a Character object :

char charValue( )
Wrapper classes
Boolean
Boolean is a wrapper around boolean values.
Boolean(boolean boolValue)
Boolean(String boolString)
In the first version, boolValue must be either true or false.
In the second version, if boolString contains the string “true” (in uppercase or lowercase),
then the new Boolean object will be true. Otherwise, it will be false.

To obtain a boolean value from a Boolean object :

boolean booleanValue( )
Wrapper classes
The Numeric Type Wrappers
The most commonly used type wrappers are those that represent numeric
values.
These are Byte, Short, Integer, Long, Float, and Double.

All of the numeric type wrappers inherit the abstract class Number.
Number declares methods that return the value of an object in each of the different number
formats. These methods are :
byte byteValue( )
short shortValue( )
int intValue( )
int longValue()
float floatValue()
double doubleValue( )

These methods are implemented by each of the numeric type wrappers.


Wrapper classes
• All of the numeric type wrappers define constructors that allow an
object to be constructed from a given value, or a string representation
of that value.

• the constructors defined for Integer:


Integer(int num)
Integer(String str)

• If str does not contain a valid numeric value, then a


NumberFormatException is thrown.
Wrapper classes
// Demonstrate a type wrapper.
class Wrap
{
public static void main(String args[])
{

Integer iOb = new Integer(100);

int i = iOb.intValue();

System.out.println(i + " " + iOb); // displays 100 100


}
}
Wrapper classes
boxing : The process of encapsulating a value within an
object.

Below line boxes the value 100 into an Integer:

Integer iOb = new Integer(100);

unboxing : The process of extracting a value from a type


wrapper.

Below line unboxes the value in iOb.

int i = iOb.intValue();
Wrapper classes
autoboxing and auto-unboxing

• Beginning with JDK 5, Java added two important features: autoboxing


and auto-unboxing.

• Autoboxing : the process by which a primitive type is automatically


encapsulated (boxed) into its equivalent type wrapper.
• There is no need to explicitly construct an object.

• Auto-unboxing : the process by which the value of a boxed object is


automatically extracted (unboxed) from a type wrapper when its
value is needed.

• There is no need to call a method such as intValue( ) or


doubleValue( ).
Wrapper classes

• autoboxing and auto-unboxing streamlines the coding of several


algorithms, removing the tedium of manually boxing and unboxing
values.

• It also helps prevent errors.

• It is very important to generics, which operates only on objects.

• autoboxing makes working with the Collections Framework much


easier.
Wrapper classes
• With autoboxing it is no longer necessary to manually
construct an object in order to wrap a primitive type.

• We need only assign that value to a type-wrapper


reference.

• Java automatically constructs the object.

Below way to construct an Integer object that has the value 100:

Integer iOb = 100; // autobox an int

Note : no object is explicitly created through the use of new. Java handles this automatically.
Wrapper classes

To unbox an object, simply assign that object reference to a primitive-


type variable.

to unbox iOb, we can use this line:

int i = iOb; // auto-unbox


Wrapper classes
// Demonstrate autoboxing/unboxing.
class AutoBox
{
public static void main(String args[])
{
Integer iOb = 100; // autobox an int
int i = iOb; // auto-unbox
System.out.println(i + " " + iOb); // displays 100 100
}
}
Wrapper classes

autoboxing and methods

• autoboxing/unboxing might occur when an argument is passed to a


method, or when a value is returned by a method.
Wrapper classes
class AutoBox2
{
static int m(Integer v)
{ return v ; // auto-unbox to int
}

public static void main(String args[])


{

Integer iOb = m(100);


System.out.println(iOb);
}
}
Wrapper classes

• Here m( ) specifies an Integer parameter and returns an int result.

• Inside main( ), m( ) is passed the value 100. Because m( ) is expecting an


Integer, this value is automatically boxed.

• Then, m( ) returns the int equivalent of its argument.

• This causes v to be auto-unboxed.

• Next, this int value is assigned to iOb in main( ), which causes the int return
value to be autoboxed.
Wrapper classes

Autoboxing/Unboxing Occurs in
Expressions

• autoboxing and unboxing also applies to expressions.

• Within an expression, a numeric object is automatically unboxed.

• The outcome of the expression is reboxed, if necessary.


Wrapper classes
class AutoBox3
{ public static void main(String args[])
{ Integer iOb, iOb2;
int i;
iOb = 100;
System.out.println("Original value of iOb: " + iOb);
++iOb;
System.out.println("After ++iOb: " + iOb);
iOb2 = iOb + (iOb / 3);
System.out.println("iOb2 after expression: " + iOb2);
i = iOb + (iOb / 3);
System.out.println("i after expression: " + i);
}}
Wrapper classes

++iOb;

This causes the value in iOb to be incremented.

Here iOb is unboxed, the value is incremented, and the result is


reboxed.
Wrapper classes
Auto-unboxing allows to mix different types of numeric objects in an
expression.
Once the values are unboxed, the standard type conversions are
applied.
The result is reboxed and stored in dOb.

class AutoBox4
{ public static void main(String args[])
{ Integer iOb = 100;
Double dOb = 98.6;
dOb = dOb + iOb;
System.out.println("dOb after expression: " + dOb);
}
}
Wrapper classes
Because of auto-unboxing, we can use integer numeric objects to
control a switch statement.
For example, consider this fragment:

Integer iOb = 2;
switch(iOb)
{
case 1: System.out.println("one");
break;
case 2: System.out.println("two");
break;
default: System.out.println("error");
}
Wrapper classes
Autoboxing/Unboxing Boolean and Character Values

class AutoBox5
{ public static void main(String args[])
{
// Autobox/unbox a boolean.
Boolean b = true;
// b is auto-unboxed.
if(b) System.out.println("b is true");

// Autobox/unbox a char.
Character ch = 'x'; // box a char
char ch2 = ch; // unbox a char
System.out.println("ch2 is " + ch2);
}}
Wrapper classes

• Because of auto-unboxing, a Boolean object can now also be used to


control loop statements.
• When a Boolean is used as the conditional expression of a while,
for, or do/while, it is automatically unboxed into its boolean
equivalent.

Boolean b;
// ...
while(b) { // ... }
Method calling Conversion action

st = Integer.toString(i); primitive integer to string.


st = Float.toString(f); primitive float to string.
st = Double.toString(d); primitive double to string.
st = Long.toString(l); primitive long to string.
method calling conversion action

int i = Integer.parseInt(st) Converts string to primitive integer

long l = Long.parseLong(st) Converts string to primitive long


Converts string to primitive double
Double d =
Double.parseDouble(st)
Converts string to primitive float
Float f = Float.parseFloat(st)
Method calling Conversion action

obj = Converting string to double


Double.valueOf(st) object
obj = Float.valueOf(st) Converting string to float object
obj = Converting string to integer
Integer.valueOf(st) object
obj = Long.valueOf(st) Converting string to long object

You might also like