0% found this document useful (0 votes)
5 views

Lecture 8 Wrapper Classes, Arrays

Uploaded by

Abcd Efgh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 8 Wrapper Classes, Arrays

Uploaded by

Abcd Efgh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Maharaja Agrasen Institute of Technology

CIC-212
Java Programming

Lecture
Java’s Wrapper Classes for the Primitives Types,
Arrays and Collections
Primitives & Wrappers

Java has a wrapper class for each of the eight primitive data types.
Wrapper classes are available in java.lang package

Primitive Wrapper Primitive Wrapper


Type Class Type Class
boolean Boolean float Float
byte Byte int Integer
char Character long Long
double Double short Short
Use of the Wrapper Classes
BOXING: Converting primitive data types into object is called boxing, and this is taken care by the
compiler. Therefore, while using a wrapper class you just need to pass the value of the primitive data
type to the constructor of the Wrapper class.

UNBOXING: Wrapper object will be converted back to a primitive data type, and this process is
called unboxing. The Number class is part of the java.lang package.
public class Test
{
public static void main(String args[])
Integer i=new Integer(10); {
Integer x = 5; // boxes int to an
Integer object
int a=i.intValue(); x = x + 10; // unboxes the Integer to
a int
System.out.println(x);
}
}
Use of the Wrapper Classes
1. Primitive data types are passed by value. Objects are passed
by reference. Wrapper classes facilitate passing primitives by
reference, as an argument to a method.
2. Wrapper classes provide many ready to use utility methods.
3. The classes in java.util package handles only objects and
hence wrapper classes help in this case also.
4. Data structures in the Collection framework, such as
ArrayList, HashMap and Vector, store only objects (reference
types) and not primitive types.
5. An object is needed to support synchronization in
multithreading.
Converting String/value to
Objects
Wrapper.valueOf() takes a value (or string)
and returns an object of that class:

Integer i1 = Integer.valueOf(42);
Integer i2 = Integer.valueOf(“42”);

Boolean b1 = Boolean .valueOf(true);


Boolean b2 = Boolean .valueOf(“true”);

Long n1 = Long.valueOf(42000000L);
Long n1 = Long.valueOf(“42000000L”);
Accessing values from the Objects

Each wrapper class Type has a method typeValue to obtain the


object’s value:

int i = i1.intValue();
boolean b = b1.booleanValue();
long l = l1.longValue();

42
false
42000000
Converting String to Primitive type

The Wrapper class for each primitive type has a method parseType() to
parse a string representation & return the literal value.

int i = Integer.parseInt(“42”) => 42


boolean b = Boolean.parseBoolean(“true”) => true
double d = Double.parseDouble(“2.71”) => 2.71
//…

• Common use: Parsing the arguments to a program:


Converting Numbers to String

The Wrapper class has a static method toString() to convert numbers


to String.

String str = Integer.toString(i);


String str = Float. toString(f);
String str = Double. toString(d);
String str = Long. toString(l);
//…
Wrapper has a
MAX_VALUE constant:
byteObj = new Byte(Byte.MAX_VALUE); =>
shortObj = new Short(Short.MAX_VALUE); Byte:127
intObj = new Integer(Integer.MAX_VALUE); Short:32767
longObj = new Long(Long.MAX_VALUE); Integer:2147483647
floatObj = new Float(Float.MAX_VALUE); Long:9223372036854775807
doubleObj = new Float:3.4028235E38
Double(Double.MAX_VALUE);
Double:1.7976931348623157E308
printNumValues("MAXIMUM NUMBER
VALUES:");
Many useful utility methods for Integer:
int hashCode()
static int numberOfLeadingZeros(int i)
static int numberOfTrailingZeros(int i)
static int reverse(int i)
static int reverseBytes(int i)
static int rotateLeft(int i, int distance)
static int rotateRight(int i, int distance)
static String toBinaryString(int i)
static String toHexString(int i)
static String toOctalString(int i)
static String toString(int i, int radix)
Many useful utility methods for
char ch = 'a'; Characters:
// Unicode for uppercase Greek
omega
Character C1= Character.valueOf(ch);

public class CharacterTest {

public static void main(String[] args) {

System.out.println("Is '#' an alphabetic character? "+Character.isAlphabetic('#'));


System.out.println("Is 'g' an alphabetic character? "+Character.isAlphabetic('g'));
System.out.println("Is 'म' is defined in Unicode? "+Character.isDefined('म'));
System.out.println("Is 'r' is a digit? "+Character.isDigit('r'));
System.out.println("Is '7' is a digit? "+Character.isDigit('7'));
System.out.println("Change 'g' to upper case: "+Character.toUpperCase('g'));
System.out.println("Change 'G' to lower case: "+Character.toLowerCase('G'));
}
}
Many useful utility methods for
Characters:
Sr.No. Method & Description
1 isLetter() Determines whether the specified char value is a letter.
2 isDigit() Determines whether the specified char value is a digit.
3 isWhitespace() Determines whether the specified char value is white space.
4 isUpperCase() Determines whether the specified char value is uppercase.
5 isLowerCase() Determines whether the specified char value is lowercase.
6 toUpperCase() Returns the uppercase form of the specified char value.
7 toLowerCase() Returns the lowercase form of the specified char value.
8 toString() Returns a String object representing the specified character value that is, a one-
character string.
Double & Float: Utilities for Arithmetic Operations:
• Constants POSITIVE_INFINITY & NEGATIVE_INFINITY
• Constant NaN = Not-a-Number (NaN) value.
• Methods isNaN(), isInfinite()

Although the Wrapper classes provide needed functionality but Java


code is sometimes overly complicated due to the necessary
conversions between the primitive and wrapper versions of data
being manipulated.
Array and Collections
Java Arrays – The Basics

Declaring an array
int[] myArray;
int[] myArray = new int[5];
String[] stringArray = new String[10];
String[] strings = new String[] {“one”, “two”};

Looping over an array


Checking an arrays length
for(int I=0; I<myArray.length; i++)
int arrayLength = myArray.length;
{
String s = myArray[i];
}
Java Arrays – Bounds
Bounds Checking
checking
• Java does this automatically.
• It is
public class impossible
TestArray { to go beyond the end of an array (unlike C/C++)
public static void main(String[]
• Automatically generatesargs)
an ArrayIndexOutOfBoundsException
{
double[] myList = {1.9, 2.9, 3.4, 3.5}; // Finding the largest element
// Print all the array elements double max = myList[0];
for (int i = 0; i < myList.length; i+ for (int i = 1; i <
+) myList.length; i++)
{ {
System.out.println(myList[i] + " "); } if (myList[i] > max)
// Summing all elements max = myList[i];
}
double total = 0; System.out.println("Max is " +
for (int i = 0; i < max);
myList.length; i++) }
{ total += myList[i]; }
}
System.out.println("Total is
Java Arrays – Copying
Don’t copy arrays “by hand” by looping over the array
The System class has an arrayCopy method to do this efficiently

int array1[] = new int[10];


int array2[] = new int[10];
//assume we add items to array1

//copy array1 into array2


System.arrayCopy(array1, 0, array2, 0, 10);

//copy last 5 elements in array1 into first 5 of array2


System.arrayCopy(array1, 5, array2, 0, 5);
Java Arrays Class
The java.util.Arrays class contains a static factory that allows arrays to be viewed as lists.
Following are the important points about Arrays −

• This class contains various methods for manipulating arrays (such as sorting and
searching).

• The methods in this class throw a NullPointerException if the specified array reference is
null.
static int binarySearch(byte[] a, byte key) This method searches the specified array of bytes
for the specified value using the binary search algorithm.
static boolean equals(long[] a, long[] a2) This method returns true if the two specified arrays
of longs are equal to one another.
static int hashCode(byte[] a) This method returns a hash code based on the contents of the
specified array.
static void sort(char[] a) This method sorts the specified array of chars into ascending
numerical order.
Around 105 methods defined in Arrays class to do different operations on arrays.
Java Arrays – Sorting

Again no need to do this “by hand”.


The java.util.Arrays class has methods to sort different kinds
of arrays

int myArray[] = new int[] {5, 4, 3, 2, 1};


java.util.Arrays.sort(myArray);
//myArray now holds 1, 2, 3, 4, 5

Sorting arrays of objects is involves some extra work, as we’ll


see later…
Java
Collections
What are they?
• A number of pre-packaged implementations of common ‘container’
classes, such as LinkedLists, Sets, etc.
• Part of the java.util package.

Advantages
• Very flexible, can hold any kind of object

Disadvantages
• Not as efficient as arrays (for some uses)
• Not type-safe. Store references to Object
Java Collections

Two Types of Containers


• Collections
• Group of objects, which may restricted or
manipulated in some way
• E.g. an ordered to make a List or LinkedList
• E.g. a Set, an unordered group which can only contain
one of each item
• Maps
• Associative array, Dictionary, Lookup Table, Hash
• A group of name-value pairs
Java Collections
• Maps
• HashMap, SortedMap
• Lists
• ArrayList, LinkedList
• Sets
• HashSet, SortedSet, Treeset
• Dictionary
• Stack
Array and Arraylist in Java

Array: Simple fixed sized arrays that we create in


Java, like below
int arr[] = new int[10];

ArrayList : Dynamic sized arrays in Java that


implement List interface.
ArrayList<Type> arrL = new ArrayList<Type>();
Here Type is the type of elements in ArrayList to be created
Array and Arraylist in Java
An Array is basic functionality provided by Java. ArrayList is part of
collection framework in Java. Therefore array members are accessed
using [ ], while ArrayList has a set of methods to access elements
and modify them.
// A Java program to demonstrate /*............ArrayList..............*/
differences between array and // Create an arrayList with initial
ArrayList capacity 2
import java.util.ArrayList; ArrayList<Integer> arrL = new
import java.util.Arrays; ArrayList<Integer>(2);
class Test
{ // Add elements to ArrayList
public static void main(String arrL.add(1);
args[]) arrL.add(2);
{
/* ........... Normal // Access elements of ArrayList
Array............. */ System.out.println(arrL.get(0));
int[] arr = new int[2]; }
arr[0] = 1; }
arr[1] = 2;
System.out.println(arr[0]);
Array and Arraylist in Java
Array is a fixed size data structure while ArrayList is not. One need not to mention the size of
Arraylist while creating its object. Even if we specify some initial capacity, we can add more
elements.

// A Java program to demonstrate


/*............ArrayList..............*/
differences between array and
ArrayList
// Need not to specify size
import java.util.ArrayList; ArrayList<Integer> arrL = new
import java.util.Arrays; ArrayList<Integer>();
class Test arrL.add(1);
{ arrL.add(2);
public static void main(String arrL.add(3);
args[]) arrL.add(4);
{ // We can add more elements to arrL
/* ........... Normal Array.............
*/
// Need to specify the size for System.out.println(arrL);
array System.out.println(Arrays.toString(arr));
int[] arr = new int[3]; }
arr[0] = 1; }
arr[1] = 2;
arr[2] = 3;
// We cannot add more elements
Array and Arraylist in Java
Array can contain both primitive data types as well as objects of a class depending on the
definition of the array. However, ArrayList only supports object entries, not the primitive data
types.
import java.util.ArrayList;
class Test // not allowed (Uncommenting below line
{ causes compiler error)
public static void main(String // ArrayList<char> arrL = new
args[]) ArrayList<char>();
{
// allowed // Allowed
int[] array = new int[3]; ArrayList<Integer> arrL1 = new
ArrayList<>();
// allowed, however, need to be ArrayList<String> arrL2 = new
intialized ArrayList<>();
Test[] array1 = new Test[3]; ArrayList<Object> arrL3 = new
ArrayList<>();
}
}
Java Collections – The Basics
List myList = new ArrayList();
List otherList = new ArrayList(5);
Map database = new HashMap();
Set things = new HashSet(); Copying a list - Very easy, just use
addAll()
For Collections, use add() List myList = new ArrayList();
List myList = new ArrayList();
//assume we add items to the list
myList.add(“A String”);
myList.add(“Other String”);
List otherList = new ArrayList();
For Maps, use put() otherList.addAll(myList);
Map myMap = new HashMap();
myMap.put(“google”, “http://www.google.com”);
mpMap.put(“yahoo”, “http://www.yahoo.com”);
Collections – Getting Individual Items

Use get()
Note that we have to cast the object to its original
type.
• Collections…
String s = (String)myList.get(1); //get first element
String s2 = (String)myList.get(10); //get tenth element

• Maps…
String s = (String)myMap.get(“google”);
String s2 = (String)mpMap.get(“yahoo”);
Collections – Getting all
items
For Lists, we could use a for loop, and loop through the list to
get() each item.

But this doesn’t work for Maps.

To allow generic handling of collections, Java defines an object


called an Iterator.
An object whose function is to walk through a Collection of objects and
provide access to each object in sequence.
Collections – Getting all items
Get an iterator using the iterator() method

Iterator objects have three methods:


next() – gets the next item in the collection
hasNext() – tests whether it has reached the end
remove() – removes the item just returned

Basic iterators only go forwards


Lists objects have a ListIterator that can go forward and
backward
Collections – Getting all
items
Simple example:
List myList = new ArrayList();
//we add items

Iterator iterator = myList.iterator();


while (iterator.hasNext())
{
String s = (String)iterator.next();
//do something with it
}
Stack Class in java.util
package
import java.util.Stack;
// Throws EmptyStackException if the
public class StackExample
stack is empty
{ public static void main(String[] args)
System.out.println("Stack.pop() => " +
{
cardAtTop);
// Creating a Stack
System.out.println("Current Stack => " +
Stack stackOfCards = new Stack();
stackOfCards);
// Pushing new items to the Stack
System.out.println();
stackOfCards.push("Jack");
// Get the item at the top of the stack
stackOfCards.push("Queen");
without removing it
stackOfCards.push("King");
cardAtTop = stackOfCards.peek();
stackOfCards.push("Ace");
System.out.println("Stack.peek() => " +
System.out.println("Stack => " +
cardAtTop);
stackOfCards);
System.out.println("Current Stack => " +
System.out.println();
stackOfCards);
// Popping items from the Stack
}
String cardAtTop = stackOfCards.pop();
}
Stack Class in java.util
package
Methods in Stack class

1.Object push(Object element) : Pushes an element on the top of the


stack.
2.Object pop() : Removes and returns the top element of the stack. An
‘EmptyStackException’ exception is thrown if we call pop() when the
invoking stack is empty.
3.Object peek() : Returns the element on the top of the stack, but does not
remove it.
4.boolean empty() : It returns true if nothing is on the top of the stack.
Else, returns false.
5.int search(Object element) : It determines whether an object exists in
the stack. If the element is found, it returns the position of the element
from the top of the stack. Else, it returns -1.
Queue Class in java.util
package
import java.util.*;
class TestCollection12{ Iterator itr=queue.iterator();
public static void main(String args[]){ while(itr.hasNext())
PriorityQueue queue=new PriorityQueue( {
); System.out.println(itr.next());
queue.add("Amit"); }
queue.add("Vijay"); queue.remove();
queue.add("Karan"); queue.poll();
queue.add("Jai"); System.out.println("after removing two el
queue.add("Rahul"); ements:");
System.out.println("head:"+queue.eleme Iterator<String> itr2=queue.iterator();
nt()); while(itr2.hasNext()){
System.out.println("head:"+queue.peek() System.out.println(itr2.next());
); }
System.out.println("iterating the queue e }
lements:"); }
Queue Class in java.util
package
Output:
head:Amit
head:Amit
iterating the queue
elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two
elements:
Karan
Rahul
Vijay
Queue Class in java.util package

Method Description
boolean add(object) It is used to insert the specified element into this queue
and return true upon success.

boolean offer(object) It is used to insert the specified element into this


queue.
Object remove() It is used to retrieves and removes the head of this
queue.
Object poll() It is used to retrieves and removes the head of this
queue, or returns null if this queue is empty.

Object element() It is used to retrieves, but does not remove, the head of
this queue.
Object peek() It is used to retrieves, but does not remove, the head of
this queue, or returns null if this queue is empty.

You might also like