Java Training Material v1.0 - Day 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

Collections in Java – Day 2

Java
Collection in JAVA – Day 2

Version: 1.0
Last Modified On: Jun 02 / 2016

1
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

Table of Contents
1. JAVA COLLECTIONS ............................................................................................4
2. ARRAYLIST CLASS ..............................................................................................5
2.1. Java ArrayList class ...................................................................................................5
2.2. Java Non-generic Vs Generic Collection.........................................................................5
2.3. Two ways to iterate the elements of collection in java .....................................................6
2.3.1. Iterating the elements of Collection by iterator interface ........................................................ 6

2.3.2. Iterating the elements of Collection by for-each loop ............................................................. 6

2.4. User-defined class objects in Java ArrayList ...................................................................7


3. LINKEDLIST CLASS...........................................................................................10
4. ARRAYLIST VS LINKEDLIST..............................................................................11
4.1. Difference between ArrayList and LinkedList ................................................................ 11
5. LISTITERATOR INTERFACE ...............................................................................13
5.1. Commonly used methods of List Interface: .................................................................. 13
5.2. Java ListIterator Interface ........................................................................................ 13
5.2.1. Commonly used methods of ListIterator Interface: ...............................................................13

6. HASHSET CLASS ...............................................................................................15


6.1. Difference between List and Set: ............................................................................... 15
6.2. Hierarchy of HashSet class: ...................................................................................... 15

7. HASHMAP CLASS ..............................................................................................17


7.1. Hierarchy of HashMap class: ..................................................................................... 17

8. HASHTABLE CLASS ...........................................................................................18


9. HASHMAP VS HASHTABLE CLASS .....................................................................19
10.RECAP SESSION: ..............................................................................................20
10.1. Inheritance ........................................................................................................ 20
10.2. Interface ........................................................................................................... 20
10.3. Abstract ............................................................................................................ 20
10.4. Exception Handling ............................................................................................. 20
10.4.1. Exception Hierarchy: ..................................................................................................20

10.4.2. Try ...........................................................................................................................21


10.4.3. Exceptions Methods: ..................................................................................................21

10.4.4. Catching Exceptions: ..................................................................................................22


10.4.5. Multiple catch Blocks: .................................................................................................23

10.4.6. Nested Try Block ........................................................................................................25


10.4.7. The throws/throw Keywords: .......................................................................................26
10.4.8. The finally block .........................................................................................................28
10.4.9. User-defined Exceptions: ............................................................................................32

10.4.10. Common Exceptions: ..................................................................................................35

11.THIS AND SUPER KEYWORD .............................................................................36


2
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11.1. this keyword ...................................................................................................... 36


11.1.1. Usage of java this keyword .........................................................................................36
11.1.2. The this keyword can be used to refer current class instance variable. ..............................37

11.1.3. this() can be used to invoked current class constructor. ..................................................39


11.1.4. The this keyword can be used to invoke current class method (implicitly). ........................42
11.1.5. this keyword can be passed as an argument in the method. ............................................43
11.1.6. The this keyword can be passed as argument in the constructor call. ...............................44
11.1.7. The this keyword can be used to return current class instance. ........................................45

11.2. super Keyword ................................................................................................... 46


11.2.1. Usage of java super Keyword ......................................................................................46
11.2.2. super is used to refer immediate parent class instance variable. ......................................47
11.2.3. super is used to invoke parent class constructor. ...........................................................48

11.2.4. super can be used to invoke parent class method ..........................................................50

12.HAND-ON / WORKING WITH PROGRAMS .........................................................52


13.START ENHANCING MINI PROJECT ..................................................................52

3
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

1. JAVA COLLECTIONS

Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.

All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

4
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

2. ARRAYLIST CLASS

2.1. Java ArrayList class


o Java ArrayList class uses a dynamic array for storing the elements.It extends
AbstractList class and implements List interface.
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.

2.2. Java Non-generic Vs Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in collection. Now it is
type safe so typecasting is not required at run time.

Let's see the old non-generic example of creating java collection.


ArrayList al=new ArrayList();//creating old non-generic arraylist
Let's see the new generic example of creating java collection.
ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist
In generic collection, we specify the type in angular braces. Now ArrayList is forced to have
only specified type of objects in it. If you try to add another type of object, it gives compile
time error.

Example of Java ArrayList class


import java.util.*;
class TestCollection1{
public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();//creating arraylist


al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements


while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ravi
Vijay
Ravi

5
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

Ajay

2.3. Two ways to iterate the elements of collection in java


1. By Iterator interface.
2. By for-each loop.

In the above example, we have seen traversing ArrayList by Iterator. Let's see the example
to traverse ArrayList elements using for-each loop.

2.3.1. Iterating the elements of Collection by iterator interface


import java.util.*;
class TestCollection1{
public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();//creating arraylist


al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements


while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ravi
Vijay
Ravi
Ajay

2.3.2. Iterating the elements of Collection by for-each loop

import java.util.*;
class TestCollection2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
for(String obj:al)
System.out.println(obj);
}
}

Ravi
Vijay
6
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

Ravi
Ajay

2.4. User-defined class objects in Java ArrayList


class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}

import java.util.*;
public class TestCollection3{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);

ArrayList<Student> al=new ArrayList<Student>();//creating arraylist


al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);

Iterator itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
101 Sonoo 23
102 Ravi 21
103 Hanumat 25

Example of addAll(Collection c) method


import java.util.*;
class TestCollection4{
public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ajay");

7
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

ArrayList<String> al2=new ArrayList<String>();


al2.add("Sonoo");
al2.add("Hanumat");

al.addAll(al2);

Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ravi
Vijay
Ajay
Sonoo
Hanumat

Example of removeAll() method


import java.util.*;
class TestCollection5{
public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ajay");

ArrayList<String> al2=new ArrayList<String>();


al2.add("Ravi");
al2.add("Hanumat");

al.removeAll(al2);

System.out.println("iterating the elements after removing the elements of al2...");


Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}

}
}
iterating the elements after removing the elements of al2...
Vijay
Ajay

Example of retainAll() method


import java.util.*;

8
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

class TestCollection6{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");

al.retainAll(al2);

System.out.println("iterating the elements after retaining the elements of al2...");


Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
iterating the elements after retaining the elements of al2...
Ravi

9
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

3. LINKEDLIST CLASS

o Java LinkedList class uses doubly linked list to store the elements. It extends the
AbstractList class and implements List and Deque interfaces.
o Java LinkedList class can contain duplicate elements.
o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
o Java LinkedList class can be used as list, stack or queue.

Java LinkedList Example


import java.util.*;
public class TestCollection7{
public static void main(String args[]){

LinkedList<String> al=new LinkedList<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

Output:
Ravi
Vijay
Ravi
Ajay

10
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

4. ARRAYLIST VS LINKEDLIST

4.1. Difference between ArrayList and LinkedList

ArrayList and LinkedList both implements List interface and maintains insertion order. Both
are non-synchronized classes.

But there are many differences between ArrayList and LinkedList classes that are given below.

ArrayList LinkedList

ArrayList internally uses dynamic array to LinkedList internally uses doubly linked list to store
store the elements. the elements.

Manipulation with ArrayList is slow because Manipulation with LinkedList is faster than ArrayList
it internally uses array. If any element is because it uses doubly linked list so no bit shifting is
removed from the array, all the bits are required in memory.
shifted in memory.

ArrayList class can act as a list only LinkedList class can act as a list and queue both
because it implements List only. because it implements List and Deque interfaces.

ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.

Example of ArrayList and LinkedList in Java


Let's see a simple example where we are using ArrayList and LinkedList both.

import java.util.*;
class TestArrayLinked{
public static void main(String args[]){

List<String> al=new ArrayList<String>();//creating arraylist


al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

List<String> al2=new LinkedList<String>();//creating linkedlist


al2.add("James");//adding object in linkedlist
al2.add("Serena");
al2.add("Swati");
al2.add("Junaid");

System.out.println("arraylist: "+al);
System.out.println("linkedlist: "+al2);
}

11
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

Output:
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]

12
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

5. LISTITERATOR INTERFACE

List Interface is the subinterface of Collection. It contains methods to insert and delete
elements in index basis. It is a factory of ListIterator interface.

5.1. Commonly used methods of List Interface:


1. public void add(int index,Object element);
2. public boolean addAll(int index,Collection c);
3. public object get(int Index position);
4. public object set(int index,Object element);
5. public object remove(int index);
6. public ListIterator listIterator();
7. public ListIterator listIterator(int i);

5.2. Java ListIterator Interface

ListIterator Interface is used to traverse the element in backward and forward direction.

5.2.1. Commonly used methods of ListIterator Interface:


1. public boolean hasNext();
2. public Object next();
3. public boolean hasPrevious();
4. public Object previous();

Example of ListIterator Interface:


import java.util.*;
public class TestCollection8{
public static void main(String args[]){

ArrayList<String> al=new ArrayList<String>();


al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");

System.out.println("element at 2nd position: "+al.get(2));

ListIterator<String> itr=al.listIterator();

System.out.println("traversing elements in forward direction...");


while(itr.hasNext()){
System.out.println(itr.next());
}

System.out.println("traversing elements in backward direction...");


while(itr.hasPrevious()){
System.out.println(itr.previous());
}
}
13
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

Output: element at 2nd position: Vijay


traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit

14
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

6. HASHSET CLASS

o Uses hashtable to store the elements. It extends AbstractSet class and implements
Set interface.
o Contains unique elements only.

Difference between List and Set:


List can contain duplicate elements whereas Set contains unique elements only.

6.1. Hierarchy of HashSet class:

Example of HashSet class:


import java.util.*;
class TestCollection9{
public static void main(String args[]){

HashSet<String> al=new HashSet<String>();


al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");

Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
15
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

}
}

Output:Ajay
Vijay
Ravi

16
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

7. HASHMAP CLASS

o A HashMap contains values based on the key. It implements the Map interface and
extends AbstractMap class.
o It contains only unique elements.
o It may have one null key and multiple null values.
o It maintains no order.

7.1. Hierarchy of HashMap class:

Example of HashMap class:


import java.util.*;
class TestCollection13{
public static void main(String args[]){

HashMap<Integer,String> hm=new HashMap<Integer,String>();

hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Output:102 Rahul
100 Amit
101 Vijay

What is difference between HashSet and HashMap?


HashSet contains only values whereas HashMap contains entry(key and value).

17
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

8. HASHTABLE CLASS

o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket
is identified by calling the hashcode() method. A Hashtable contains values based on
the key. It implements the Map interface and extends Dictionary class.
o It contains only unique elements.
o It may have not have any null key or value.
o It is synchronized.

Example of Hashtable:
import java.util.*;
class TestCollection16{
public static void main(String args[]){

Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");

for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}

Output: 103 Rahul


102 Ravi
101 Vijay
100 Amit

18
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

9. HASHMAP VS HASHTABLE CLASS

HashMap and Hashtable both are used to store data in key and value form. Both are using
hashing technique to store unique keys.

But there are many differences between HashMap and Hashtable classes that are given below.

HashMap Hashtable

HashMap is non synchronized. It is not-thread Hashtable is synchronized. It is thread-safe


safe and can't be shared between many threads and can be shared with many threads.
without proper synchronization code.

HashMap allows one null key and multiple null Hashtable doesn't allow any null key or
values. value.

HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.

HashMap is fast. Hashtable is slow.

We can make the HashMap as synchronized by Hashtable is internally synchronized and can't
calling this code be unsynchronized.
Map m = Collections.synchronizedMap(hashMap);

HashMap is traversed by Iterator. Hashtable is traversed by Enumerator and


Iterator.

Iterator in HashMap is fail-fast. Enumerator in Hashtable is not fail-fast.

HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.

19
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

10. RECAP SESSION:

10.1. Inheritance

10.2. Interface

10.3. Abstract

10.4. Exception Handling

10.4.1. Exception Hierarchy:


All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass
called Error which is derived from the Throwable class.
Errors are abnormal conditions that happen in case of severe failures, these are not handled
by the java programs. Errors are generated to indicate errors generated by the runtime
environment. Example: JVM is out of Memory. Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.

Here is a list of most common checked and unchecked Java's Built-in Exceptions.

20
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

10.4.2. Try

Java try block is used to enclose the code that might throw an exception. It must be used
within the method.

Java try block must be followed by either catch or finally block.

Syntax of java try-catch


try{
//code that may throw exception
}catch(Exception_class_Name ref){}

Syntax of try-finally block


try{
//code that may throw exception
}finally{}

10.4.3. Exceptions Methods:


Following is the list of important methods available in the Throwable class.

Methods with Description

public String getMessage()


Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.

public Throwable getCause()


Returns the cause of the exception as represented by a Throwable object.

public String toString()


Returns the name of the class concatenated with the result of getMessage()

public void printStackTrace()


Prints the result of toString() along with the stack trace to System.err, the error output
stream.

public StackTraceElement [] getStackTrace()


Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the method
at the bottom of the call stack.

21
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

public Throwable fillInStackTrace()


Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.

10.4.4. Catching Exceptions:


A method catches an exception using a combination of the try and catch keywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch
block is referred to as protected code, and the syntax for using try/catch looks like the
following:

try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

The code which is prone to exceptions is placed in the try block, when an exception occurs,
that exception occurred is handled by catch block associated with it. Every try block should
be immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.
Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.

// File Name : ExcepTest.java


import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
22
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

System.out.println("Out of the block");


}}

This would produce the following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


Out of the block

10.4.5. Multiple catch Blocks:


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks
looks like the following:

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}

The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is thrown
to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.

Example:
Here is code segment showing how to use multiple try/catch statements.

try

23
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}

Catching multiple type of exceptions


Since Java 7 you can handle more than one exceptions using a single catch block, this feature
simplifies the code. Below given is the syntax of writing

catch (IOException|FileNotFoundException ex) {


logger.log(ex);
throw ex;

24
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

10.4.6. Nested Try Block

The try block within a try block is known as nested try block in java.
Why use nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
...
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....

Java nested try example


Let's see a simple example of java nested try block.

class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}

25
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

10.4.7. The throws/throw Keywords:


If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword.

Try to understand the difference between throws and throw keywords, throws is used to
postpone the handling of a checked exception and throw is used to invoke an exception
explicitly.
The following method declares that it throws a RemoteException:

import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}

A method can declare that it throws more than one exception, in which case the exceptions
are declared in a list separated by commas. For example, the following method declares that
it throws a RemoteException and an InsufficientFundsException:

import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}

26
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

No. throw throws

1. Java throw keyword is used to Java throws keyword is used to declare an exception.
explicitly throw an exception.

2. Checked exception cannot be Checked exception can be propagated with throws.


propagated using throw only.

3. Throw is followed by an Throws is followed by class.


instance.

4. Throw is used within the Throws is used with the method signature.
method.

5. You cannot throw multiple You can declare multiple exceptions e.g.
exceptions. public void method()throws IOException,SQLException.

27
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

10.4.8. The finally block


The finally block follows a try block or a catch block. A finally block of code always executes,
irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute,
no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:

try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}

Example:

public class ExcepTest{

public static void main(String args[]){


int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}
This would produce the following result:
28
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


First element value: 6
The finally statement is executed

Difference between final, finally and finalize

There are many differences between final, finally and finalize.

No. final finally finalize

1. Final is used to apply Finally is used to place Finalize is used to


restrictions on class, method important code, it will perform clean up
and variable. Final class can't be executed whether processing just before
be inherited, final method can't exception is handled or object is garbage
be overridden and final variable not. collected.
value can't be changed.

2. Final is a keyword. Finally is a block. Finalize is a method.

Note the following:


 A catch clause cannot exist without a try statement.

 It is not compulsory to have finally clauses whenever a try/catch block is present.

 The try block cannot be present without either catch clause or finally clause.

 Any code cannot be present in between the try, catch, finally blocks.

The try-with-resources
Generally when we use any resources like streams, connections etc... We have to close them
explicitly using finally block. In the program given below we are reading data from a file using
FileReader and we are closing it using finally block.

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadData_Demo {
public static void main(String args[]){

29
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

FileReader fr=null;
try{
File file=new File("file.txt");
fr = new FileReader(file); char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
}catch(IOException e){
e.printStackTrace();
}
finally{
try{
fr.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}

}
try-with-resources, also referred as automatic resource management is a new
exception handling mechanism that was introduced in Java7, which automatically closes the
resources used within the try catch block.

To use this statement you simply need to declare the required resources within the
parenthesis, the created resource will be closed automatically at the end of the block, below
given is the syntax of try-with-resources statement.

try(FileReader fr=new FileReader("file path"))


{
//use the resource
}catch(){
//body of catch
} }

Below given is the program that reads the data in a file using try-with-resources statement.

import java.io.FileReader;
import java.io.IOException;

public class Try_withDemo {

public static void main(String args[]){

try(FileReader fr=new FileReader("E://file.txt")){


char [] a = new char[50];
fr.read(a); // reads the contentto the array
for(char c : a)
System.out.print(c); //prints the characters one by one
}catch(IOException e){
e.printStackTrace();

30
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

}
}
}
Following points are to be kept in mind while working with try-with resources statement.

 To use a class with try-with-resources statement it should implement AutoCloseable interface


and the close() method of it gets invoked automatically at runtime.

 You can declare more than one class in try-with-resources statement.

 while you declare multiple classes in the try block of try-with-resources statement these
classes are closed in reverse order.

 Except the deceleration of resources within the parenthesis every thing is same as normal
try/catch block of a try block.

 The resource declared in try gets instantiated just before the start of the try-block.

 The resource declared at the try block is implicitly declared as final.

31
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

10.4.9. User-defined Exceptions:


You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes:

 All exceptions must be a child of Throwable.

 If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.

 If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below:

class MyException extends Exception{


}

You just need to extend the predefined Exception class to create your own Exception. These
are considered to be checked exceptions. The following InsufficientFundsException class
is a user-defined exception that extends the Exception class, making it a checked exception.
An exception class is like any other class, containing useful fields and methods.

Example:

// File Name InsufficientFundsException.java


import java.io.*;

public class InsufficientFundsException extends Exception


{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
To demonstrate using our user-defined exception, the following CheckingAccount class
contains a withdraw() method that throws an InsufficientFundsException.

// File Name CheckingAccount.java


import java.io.*;

public class CheckingAccount


{
private double balance;
private int number;

32
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

public CheckingAccount(int number)


{
this.number = number;
}

public void deposit(double amount)


{
balance += amount;
}

public void withdraw(double amount) throws InsufficientFundsException


{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}

public double getBalance()


{
return balance;
}

public int getNumber()


{
return number;
}
}
The following BankDemo program demonstrates invoking the deposit() and withdraw()
methods of CheckingAccount.

// File Name BankDemo.java


public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);

try
{
33
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}

Compile all the above three files and run BankDemo, this would produce the following result:

Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)

34
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

10.4.10. Common Exceptions:


In Java, it is possible to define two catergories of Exceptions and Errors.

 JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the
JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException,

 Programmatic exceptions: - These exceptions are thrown explicitly by the application or the
API programmers Examples: IllegalArgumentException, IllegalStateException.

35
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11. THIS AND SUPER KEYWORD

There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.

11.1. this keyword

11.1.1. Usage of java this keyword

Here is given the 6 usage of java this keyword.


1. this keyword can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.

Suggestion: If you are beginner to java, lookup only two usage of this keyword.

36
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11.1.2. The this keyword can be used to refer current class instance variable.

If there is ambiguity between the instance variable and parameter, this keyword resolves
the problem of ambiguity.

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the example given below:

class Student10{
int id;
String name;

Student10(int id,String name){


id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
}
}

Output:
0 null
0 null

In the above example, parameter (formal arguments) and instance variables are same that
is why we are using this keyword to distinguish between local variable and instance variable.

Program where this keyword is required


//example of this keyword
class Student11{
int id;
String name;

Student11(int id,String name){


this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
37
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

Output
111 Karan
222 Aryan

If local variables (formal arguments) and instance variables are different, there is no need to
use this keyword like in the following program:

Program where this keyword is not required


class Student12{
int id;
String name;

Student12(int i,String n){


id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student12 e1 = new Student12(111,"karan");
Student12 e2 = new Student12(222,"Aryan");
e1.display();
e2.display();
}
}
Output:
111 Karan
222 Aryan

38
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11.1.3. this() can be used to invoked current class constructor.

The this() constructor call can be used to invoke the current class constructor (constructor
chaining). This approach is better if you have many constructors in the class and want to
reuse that constructor.

//Program of this() constructor call (constructor chaining)


class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}

Student13(int id,String name){


this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}
}

Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan

Where to use this() constructor call?


The this() constructor call should be used to reuse the constructor in the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's
see the example given below that displays the actual use of this keyword.

class Student14{
int id;
String name;
String city;

Student14(int id,String name){

39
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

this.id = id;
this.name = name;
}
Student14(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}

public static void main(String args[]){


Student14 e1 = new Student14(111,"karan");
Student14 e2 = new Student14(222,"Aryan","delhi");
e1.display();
e2.display();
}
}

Output:
111 Karan null
222 Aryan delhi

Rule: Call to this() must be the first statement in constructor.

class Student15{
int id;
String name;
Student15(){System.out.println("default constructor is invoked");}

Student15(int id,String name){


id = id;
name = name;
this ();//must be the first statement
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student15 e1 = new Student15(111,"karan");
Student15 e2 = new Student15(222,"Aryan");
e1.display();
e2.display();
}
}

Output: Compile Time Error

Rule: Call to this() must be the first statement in constructor.

40
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

class Student15{
int id;
String name;
Student15(){System.out.println("default constructor is invoked");}

Student15(int id,String name){


id = id;
name = name;
this ();//must be the first statement
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student15 e1 = new Student15(111,"karan");
Student15 e2 = new Student15(222,"Aryan");
e1.display();
e2.display();
}
}

Output: Compile Time Error

41
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11.1.4. The this keyword can be used to invoke current class method
(implicitly).
You may invoke the method of the current class by using the this keyword. If you don't use
the this keyword, compiler automatically adds this keyword while invoking the method. Let's
see the example

class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}

Output: method is invoked

42
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11.1.5. this keyword can be passed as an argument in the method.

The this keyword can also be passed as an argument in the method. It is mainly used in the
event handling. Let's see the example:

class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}

public static void main(String args[]){


S2 s1 = new S2();
s1.p();
}
}

Output:method is invoked

Application of this that can be passed as an argument:


In event handling (or) in a situation where we have to provide reference of a class to
another one.

43
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11.1.6. The this keyword can be passed as argument in the constructor call.

We can pass the this keyword in the constructor also. It is useful if we have to use one object
in multiple classes. Let's see the example:

class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}

class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}

Output:10

44
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11.1.7. The this keyword can be used to return current class instance.

We can return the this keyword as an statement from the method. In such case, return type
of the method must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement


return_type method_name(){
return this;
}
Example of this keyword that you return as a statement from the method
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}

class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}

Output:Hello java

Proving this keyword


Let's prove that this keyword refers to the current class instance variable. In this program,
we are printing the reference variable and this, output of both variables are same.

class A5{
void m(){
System.out.println(this);//prints same reference ID
}

public static void main(String args[]){


A5 obj=new A5();
System.out.println(obj);//prints the reference ID

obj.m();
}
}

output:A5@22b3ea59
A5@22b3ea59

45
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11.2. super Keyword

The super keyword in java is a reference variable that is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.

11.2.1. Usage of java super Keyword


1. super is used to refer immediate parent class instance variable.
2. super() is used to invoke immediate parent class constructor.
3. super is used to invoke immediate parent class method.

46
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11.2.2. super is used to refer immediate parent class instance variable.


Problem without super keyword
class Vehicle{
int speed=50;
}
class Bike3 extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]){
Bike3 b=new Bike3();
b.display();
}
}
Output: 100
In the above example Vehicle and Bike both class have a common property speed. Instance
variable of current class is referred by instance bydefault, but I have to refer parent class
instance variable that is why we use super keyword to distinguish between parent class
instance variable and current class instance variable.

Solution by super keyword


//example of super keyword
class Vehicle{
int speed=50;
}

class Bike4 extends Vehicle{


int speed=100;

void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();

}
}

Output: 50

47
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11.2.3. super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor as given below:

class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}

class Bike5 extends Vehicle{


Bike5(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();

}
}
Output: Vehicle is created
Bike is created

11.2.3.1. Note: super() is added in each class constructor automatically by compiler.

As we know well that default constructor is provided by compiler automatically but it also
adds super() for the first statement. If you are creating your own constructor and you don't
have either this() or super() as the first statement, compiler will provide super() as the first
statement of the constructor.

48
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

Another example of super keyword where super() is provided by the compiler


implicitly.

class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}

class Bike6 extends Vehicle{


int speed;
Bike6(int speed){
this.speed=speed;
System.out.println(speed);
}
public static void main(String args[]){
Bike6 b=new Bike6(10);
}
}
Output: Vehicle is created
10

49
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

11.2.4. super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used in case
subclass contains the same method as parent class as in the example given below:

class Person{
void message(){System.out.println("welcome");}
}

class Student16 extends Person{


void message(){System.out.println("welcome to java");}

void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}

public static void main(String args[]){


Student16 s=new Student16();
s.display();
}
}
Output: welcome to java
Welcome

In the above example Student and Person both classes have message() method if we call
message() method from Student class, it will call the message() method of Student class not
of Person class because priority is given to local.

In case there is no method in subclass as parent, there is no need to use super. In the
example given below message() method is invoked from Student class but Student class does
not have message() method, so you can directly call message() method.

50
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

Program in case super is not required


class Person{
void message(){System.out.println("welcome");}
}

class Student17 extends Person{

void display(){
message();//will invoke parent class message() method
}

public static void main(String args[]){


Student17 s=new Student17();
s.display();
}
}
Output: welcome

51
Cognizant Proprietary Information – CONFIDENTIAL
Collections in Java – Day 2

12. HAND-ON / WORKING WITH PROGRAMS

1. Write a program to create a HASHSET and write values to it.


2. Write a program to enter duplicate values and null values in a existing HASHSET and display
it.
3. Write a program to sort an array and search an element based on index value.
4. Write a program to create an array of elements and reverse it.
5. Write a program to create list of names and remove the first element in the arraylist.
6. Write a program to swap two elements in arraylist.
7. Write a program to add element at first position in the linkedlist.
8. Write a program to create a linked list and display all the elements in it.
9. Write a program to create a Hashtable and add key and value pair to Hashtable and print them.
10. Write a program to get all keys from already existing Hashtable.

13. START ENHANCING MINI PROJECT

52
Cognizant Proprietary Information – CONFIDENTIAL

You might also like