0% found this document useful (0 votes)
32 views95 pages

Unit 1

Uploaded by

Sirisha Rokkam
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)
32 views95 pages

Unit 1

Uploaded by

Sirisha Rokkam
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
You are on page 1/ 95

Unit 1

Introduction

Initially it was called Oak, in honor of the tree outside James Gosling's window; its
name was changed to Java because there was already a language called Oak.
Java is based upon the concept “Write once, run anywhere”. The idea is that the same
software should run on different kinds of computers, consumer gadgets, and the other
devices.
Unlike most programming languages that generates executable code upon
compilation; the JVM generates byte codes as a result of compilation. Java byte codes
are form of instructions understood by Java Virtual Machine and usually generated as a
result of compiling Java languages source code.

Windows

Java

Java Source Java Bytecode,


Code Unix
Compiler

recognized by JVM

Solaris

Java Programs are basically of two types:

(I)Applications- Applications are the java programs that are designed to run on the local
systemand do not need any web browser to execute.

(II)Applets– Applets are the java programs that are created specially to work over internet
and areexecuted in a java enabled Web browsers (i.e. Internet Explorer, Mozilla Firefox,
Google Chrome and Netscape etc).

Java’s Magic: the Byte Code


Bytecode is a highly optimized set of instructions designed to be executed by the Java
run-time system, which is called the Java Virtual Machine (JVM).
Translating a Java program into bytecode helps makes it much easier to run a program
in a wide variety of environments i.e. Windows, Unix, Solaris etc. The reason is
straightforward: only the JVM needs to be implemented for each platform.

Java Virtual Machine


The JVM or Java Virtual Machine has an interpreter component that enables
communication between Java Byte Code and a computer’s operating system. Using a
JVM we can run a java code on any platform such as windoxxp, windox 98, unix etc.
JVM normally reads and execute java statements once at a time.
However a JVM can include JIT (Just in Time) compiler within it. A JIT compiler converts
all programs to byte code and is thus faster than a conventional JVM.

What makes Java, most powerful language……….Java Buzz Words


(i) Simple
Java was designed to be easy for the professional programmer to learn and use effectively.
Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most
programmers have little trouble learning Java. Also, some of the more confusing concepts
from C++ are either left out of Java or implemented in a cleaner, more approachable manner.
In Java, there are a small number of clearly defined ways to accomplish a given task.

(ii) Security
When we use a Java-compatible Web browser, we can safely download Java applets without
fear of viral infection or malicious intent. Java achieves this protection by confining a Java
program to the Java execution environment (sand box area) and not allowing it access to other
parts of the computer. This control is exercised by JVM.

(iii) Portability
Many types of computers and operating systems are in use throughout the world and many are
connected to the Internet. For programs to be dynamically downloaded to various types of
platforms connected to the Internet, some portable executable code is needed that can run on
any environment i.e. the Byte Code.
(iv) Object-Oriented
Like C++ , java uses all the OOP concepts like encapsulation, inheritance and polymorphism
etc. Java is called a purely object oriented language as everything we write inside class in a java
program.

(v) Robust
The multiplatform environment of the Web places extraordinary demands on a program,
because the program must execute reliably in a variety of systems. Thus, the ability to create
robust programs was given a high priority in the design of Java. To gain reliability, Java restricts
us in a few key areas, to force you to find our mistakes early in program development.

(vi) Multithreaded
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows us to
write programs that do many things simultaneously. The Java run-time system comes with an
elegant yet sophisticated solution for multiprocess synchronization that enables us to
construct smoothly running interactive systems.

(vii) Architecture-Neutral
A central issue for the Java designers was that of code longevity and portability. One of the
main problems facing programmers is that no guarantee exists that if you write a program
today, it will run tomorrow, even on the same machine. Operating system upgrades, processor
upgrades, and changes in core system resources can all combine to make a program
malfunction. The Java designers made several hard decisions in the Java language and the Java
Virtual Machine in an attempt to alter this situation. Their goal was “write once; run anywhere,
anytime, forever.” To a great extent, this goal was accomplished.

(viii) Distributed
Java is designed for the distributed environment of the Internet, because it handles TCP/IP
protocols. In fact, accessing a resource using a URL is not much different from accessing a file.
The original version of Java (Oak) included features for intra address- space messaging. This
allowed objects on two different computers to execute procedures remotely.

(ix) Dynamic
Java programs carry with them substantial amounts of run-time type information that is used
to verify and resolve accesses to objects at run time. This makes it possible to dynamically link
code in a safe and expedient manner. This is crucial to the robustness of the applet
environment, in which small fragments of byte code may be dynamically updated on a running
system.
First Java Program

Program 1.1 WAP to print a message “Welcome to Java


World”.
Solution:
class
Example
{
public static void main (String args[])
{

System.out.println ("Welcome to Java World");


}
}
Output:
Welcome to Java World

How to compile the above program:


To compile the Example program, execute the compiler, javac, specifying the name of the
source file on the command line, as shown here:
C:\>javac Example.java
The javac compiler creates a file called Example.class that contains the byte code version of
the program. As discussed earlier, the Java byte code is the intermediate representation of our
program that contains instructions the Java interpreter will execute. Thus, the output of javac
is not code that can be directly executed. To actually run the program, we must use the Java
interpreter, called java. To do so, pass the class name Example as a command-line argument,
as shown here:
C:\>java Example
When the program is run, the following output is
displayed: Welcome to Java World
Explanation of above program
public static void main(String args[])
All Java applications begin execution from main ( ) function. (This is just like C/C++.)
The public keyword is an access specifier, which allows the programmer to control the
visibility of class members. When a class member is preceded by public, then that
member may be accessed by code outside the class in which it is declared.
The keyword static allows main ( ) to be called without having to instantiate a particular
instance of the class.
The keyword void simply tells the compiler that main ( ) does not return a value.
As stated, main ( ) is the method called when a Java application begins. Keep in mind
that Java is case-sensitive. Thus, Main is different from main.
String args[ ] declares a parameter named args, which is an array of instances of the
classString. (Arrays are collections of similar objects.) Objects of type String store
character strings. In this case, args receives any command-line arguments present
when the program is executed.

System.out.println ("This is a simple Java program.");


This line outputs the string “This is a simple Java program.” followed by a new line on the
screen. Output is actually accomplished by the built-in println( ) method. In this case, println( )
displays the string which is passed to it.

Program 1.2
WAP to initialize an integer variable num to 100, then display the value of num
and num × 2.
Solution
: class
Test
{
public static void main(String args[])
{
int num;
num =
100;
System.out.println("This is num: " +
num); num = num * 2;
System.out.print("The value of num * 2
is "); System.out.println(num);
}
}
Output:
This is num: 100
The value of num * 2 is 200
Note: Here this program must saved with the file name Test.java

Data Types

Java defines eight simple types of data: byte, short, int, long, float, double and Boolean. These
can beput in four groups:
■ Integers: This group includes byte, short, int, and long, which are for whole valued signed
numbers.
■ Floating-point numbers: This group includes float and double, which represent numbers
with
fractional precision.
■ Characters: This group includes char, which represents symbols in a character set, like
letters andnumbers.
■ Boolean: This group includesboolean, which is a special type for representing true/false
values.

Sl No Name Size Range Type

1 byte 1 byte -28 to 28-1


2 short 2 byte -216 to 216-1 Integer
3 int 4 byte -232 to 232-1
4 long 8 byte -264 to 264-1
5 float 4 byte -232 to 232-1 Floating Point
6 double 8 byte -264 to 264-1
7 char 2 byte -216 to 216-1 Character
8 boolean 1 byte (Holds either T or F) -28 to 28-1 Boolean

Why Char in Java is not same as char in C/C++?


Java uses Unicode to represent characters. Unicode defines fully international character set
that can represent all of the characters found in human languages.

How to get input from user in Java

Java Scanner Class

Java Scanner class allows the user to take input from the console. It belongs to java.util package.
It is used to read the input of primitive types like int, double, long, short, float, and byte. It is the
easiest way to read input in Java program.

Syntax

1. Scanner sc=new Scanner(System.in);  

The above statement creates a constructor of the Scanner class having System.inM as an


argument. It means it is going to read from the standard input stream of the program.
The java.util package should be import while using Scanner class.
Method Description

int nextInt() It is used to scan the next token of the input as


an integer.

float nextFloat() It is used to scan the next token of the input as


a float.

double nextDouble() It is used to scan the next token of the input as


a double.

byte nextByte() It is used to scan the next token of the input as


a byte.

String nextLine() Advances this scanner past the current line.

booleannextBoolean() It is used to scan the next token of the input


into a boolean value.

long nextLong() It is used to scan the next token of the input as


a long.

short nextShort() It is used to scan the next token of the input as


a Short.

BigIntegernextBigInteger() It is used to scan the next token of the input as


a BigInteger.

BigDecimalnextBigDecimal() It is used to scan the next token of the input as


a BigDecimal.

It also converts the Bytes (from the input stream) into characters using the platform's default
charset.

Methods of Java Scanner Class

Java Scanner class provides the following methods to read different primitives types:

Example of integer input from user


The following example allows user to read an integer form the System.in.

1. import java.util.*;  
2. class UserInputDemo   
3. {  
4. public static void main(String[] args)  
5. {  
6. Scanner sc= new Scanner(System.in);    //System.in is a standard input stream  
7. System.out.print("Enter first number- ");  
8. int a= sc.nextInt();  
9. System.out.print("Enter second number- ");  
10. int b= sc.nextInt();  
11. System.out.print("Enter third number- ");  
12. int c= sc.nextInt();  
13. int d=a+b+c;  
14. System.out.println("Total= " +d);  
15. }  
16. }  

Output:

Example of String Input from user

Let's see another example, in which we have taken string input.

1. import java.util.*;  
2. class UserInputDemo1  
3. {  
4. public static void main(String[] args)  
5. {  
6. Scanner sc= new Scanner(System.in); //System.in is a standard input stream  
7. System.out.print("Enter a string: ");  
8. String str= sc.nextLine();              //reads string  
9. System.out.print("You have entered: "+str);             
10. }  
11. }  

Output:

importjava.util.Scanner;

classMain{

publicstaticvoidmain(String[]args){

ScannermyObj=newScanner(System.in);

System.out.println("Enter name, age and salary:");

// String input

String name =myObj.nextLine();

// Numerical input
int age =myObj.nextInt();

double salary =myObj.nextDouble();

// Output input by user

System.out.println("Name: "+ name);

System.out.println("Age: "+ age);

System.out.println("Salary: "+ salary);

What is Garbage Collection in Java?

Garbage Collection in Java is a process by which the programs perform memory management
automatically. The Garbage Collector(GC) finds the unused objects and deletes them to reclaim
the memory. In Java, dynamic memory allocation of objects is achieved using the new operator
that uses some memory and the memory remains allocated until there are references for the use
of the object.

When there are no references to an object, it is assumed to be no longer needed, and the
memory, occupied by the object can be reclaimed. There is no explicit need to destroy an object
as Java handles the de-allocation automatically.

The technique that accomplishes this is known as Garbage Collection. Programs that do not de-
allocate memory can eventually crash when there is no memory left in the system to allocate.
These programs are said to have memory leaks.

Garbage collection in Java happens automatically during the lifetime of the program,


eliminating the need to de-allocate memory and thereby avoiding memory leaks.

In C language, it is the programmer’s responsibility to de-allocate memory allocated dynamically


using free() function. This is where Java memory management leads.

Note: All objects are created in Heap Section of memory. More on this in a later tutorial.
Example: To Learn Garbage Collector Mechanism in Java

Step 1) Copy the following code into an editor.

class Student{

int a;

int b;

public void setData(int c,int d)

a=c;

b=d;

public void showData(){

System.out.println("Value of a = "+a);

System.out.println("Value of b = "+b);

public static void main(String args[]){

Student s1 = new Student();

Student s2 = new Student();

s1.setData(1,2);

s2.setData(3,4);

s1.showData();

s2.showData();

//Student s3;
//s3=s2;

//s3.showData();

//s2=null;

//s3.showData();

//s3=null;

//s3.showData();

Step 2) Save, Compile and Run the code. As shown in the diagram, two objects and two
reference variables are created.

Step 3) Uncomment line # 20,21,22. Save, compile & run the code.

Step 4) As shown in the diagram below, two reference variables are pointing to the same object.
Step 5) Uncomment line # 23 & 24. Compile, Save & Run the code

Step 6) As show in diagram below, s2 becomes null, but s3 is still pointing to the object and is not
eligible for java garbage collection.

Step 7) Uncomment line # 25 & 26. Save, Compile & Run the Code

Step 8) At this point there are no references pointing to the object and becomes eligible for
garbage collection. It will be removed from memory, and there is no way of retrieving it back.

How to delete an object in Java?

1) If you want to make your object eligible for Garbage Collection, assign its reference variable to
null.

2) Primitive types are not objects. They cannot be assigned null.


Constructors in Java
. Types of constructors
. Default Constructor
. Parameterized Constructor
. Constructor Overloading
. Does constructor return any value?
. Copying the values of one object into another
. Does constructor perform other tasks instead of the initialization

In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It is
not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use  access modifiers  while declaring a constructor. It controls the object creation.
In other words, we can have private, protected, public or default constructor in Java.

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


1. <class_name>(){}  

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of obje

1. //Java Program to create and call a default constructor  
2. class Bike1{  
3. //creating a default constructor  
4. Bike1()
5. {
6. System.out.println("Bike is created");
7. }  
8. //main method  
9. public static void main(String args[]){  
10. //calling a default constructor  
11. Bike1 x=new Bike1(10);
12.   
13. }  
14. }  
Test it Now

Output:

Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.

Example of default constructor that displays the default values

1. //Let us see another example of default constructor  
2. //which displays the default values  
3. class Student3{  
4. int id;  
5. String name;  
6. //method to display the value of id and name  
7. void display()
8. {
9. System.out.println(id+" "+name);
10. }  
11.   
12. public static void main(String args[]){  
13. //creating objects  
14. Student3 s1=new Student3();  
15. Student3 s2=new Student3();  
16. //displaying values of the object  
17. s1.display();  
18. s2.display();  
19. }  
20. }  
Test it Now

Output:

0 null

0 null

Explanation:In the above class,you are not creating any constructor so compiler provides you a
default constructor. Here 0 and null values are provided by default constructor.

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.

1. //Java Program to demonstrate the use of the parameterized constructor.  
2. class Student4{  
3.     int id;  
4.     String name;  
5.     //creating a parameterized constructor  
6. Student4(int i,String n)
7. {  
8.      id = i;  
9.      name = n;  
10.
11. }  
12.     //method to display the values  
13. void display()
14. {
15. System.out.println(id+" "+name);
16. }  
17.    
18.     public static void main(String args[]){  
19.     //creating objects and passing values  
20.     Student4 s1 = new Student4(111,"Karan");  
21.     Student4 s2 = new Student4(222,"Aryan");  
22.     //calling method to display the values of object  
23.     s1.display();  
24.     s2.display();  
25.    }  
26. }  
Test it Now

Output:

111 Karan
222 Aryan

Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They
are differentiated by the compiler by the number of parameters in the list and their types.

Example of Constructor Overloading

1. //Java program to overload constructors  
2. class Student5{  
3.     int id;  
4.     String name;  
5.     int age;  
6.     //creating two arg constructor  
7.     Student5(int i,String n){  
8.     id = i;  
9.     name = n;  
10.     }  
11.     //creating three arg constructor  
12.     Student5(int i,String n,int a){  
13.     id = i;  
14.     name = n;  
15.     age=a;  
16.     }  
17.     void display(){System.out.println(id+" "+name+" "+age);}  
18.    
19.     public static void main(String args[]){  
20.     Student5 s1 = new Student5(111,"Karan");  
21.     Student5 s2 = new Student5(222,"Aryan",25);  
22.     s1.display();  
23.     s2.display();  
24.    }  
25. }  
Test it Now

Output:

111 Karan 0
222 Aryan 25

Java static keyword

The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to the
class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class

1) Java static variable

If you declare any variable as static, it is known as a static variable.


o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
o The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable

1. class Student{  
2.      int rollno;  
3.      String name;  
4.      String college="ITS";  
5. }  

Suppose there are 500 students in my college, now all instance data members will get memory
each time when the object is created. All students have its unique rollno and name, so instance
data member is good in such case. Here, "college" refers to the common property of all objects. If
we make it static, this field will get the memory only once.

Java static property is shared to all objects.


Example of static variable

1. //Java Program to demonstrate the use of static variable  
2. class Student{  
3.    int rollno;//instance variable  
4.    String name;  
5.    static String college ="ITS";//static variable  
6.    //constructor  
7.    Student(int r, String n){  
8.    rollno = r;  
9.    name = n;  
10.    }  
11.    //method to display the values  
12.    void display (){System.out.println(rollno+" "+name+" "+college);}  
13. }  
14. //Test class to show the values of objects  
15. public class TestStaticVariable1{  
16.  public static void main(String args[]){  
17.  Student s1 = new Student(111,"Karan");  
18.  Student s2 = new Student(222,"Aryan");  
19.  //we can change the college of all objects by the single line of code  
20.  //Student.college="BBDIT";  
21.  s1.display();  
22.  s2.display();  
23.  }  
24. }  
Test it Now

Output:

111 Karan ITS


222 Aryan ITS
Program of the counter without static variable

In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object
will have the copy of the instance variable. If it is incremented, it won't reflect other objects. So
each object will have the value 1 in the count variable.

1. //Java Program to demonstrate the use of an instance variable  
2. //which get memory each time when we create an object of the class.  
3. class Counter{  
4. int count=0;//will get memory each time when the instance is created  
5.   
6. Counter(){  
7. count++;//incrementing value  
8. System.out.println(count);  
9. }  
10.   
11. public static void main(String args[]){  
12. //Creating objects  
13. Counter c1=new Counter();  
14. Counter c2=new Counter();  
15. Counter c3=new Counter();  
16. }  
17. }  
Test it Now

Output:

1
1
1

Program of counter by static variable

As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.

1. //Java Program to illustrate the use of static variable which  
2. //is shared with all objects.  
3. class Counter2{  
4. static int count=0;//will get memory only once and retain its value  
5.   
6. Counter2(){  
7. count++;//incrementing the value of static variable  
8. System.out.println(count);  
9. }  
10.   
11. public static void main(String args[]){  
12. //creating objects  
13. Counter2 c1=new Counter2();  
14. Counter2 c2=new Counter2();  
15. Counter2 c3=new Counter2();  
16. }  
17. }  
Test it Now

Output:

1
2
3

2) Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

Example of static method

1. //Java Program to demonstrate the use of a static method.  
2. class Student{  
3.      int rollno;  
4.      String name;  
5.      static String college = "ITS";  
6.      //static method to change the value of static variable  
7.      static void change(){  
8.      college = "BBDIT";  
9.      }  
10.      //constructor to initialize the variable  
11.      Student(int r, String n){  
12.      rollno = r;  
13.      name = n;  
14.      }  
15.      //method to display values  
16.      void display(){System.out.println(rollno+" "+name+" "+college);}  
17. }  
18. //Test class to create and display the values of object  
19. public class TestStaticMethod{  
20.     public static void main(String args[]){  
21.     Student.change();//calling change method  
22.     //creating objects  
23.     Student s1 = new Student(111,"Karan");  
24.     Student s2 = new Student(222,"Aryan");  
25.     Student s3 = new Student(333,"Sonoo");  
26.     //calling display method  
27.     s1.display();  
28.     s2.display();  
29.     s3.display();  
30.     }  
31. }  
Test it Now
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

3) Java static block


o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.

Example of static block

1. class A2{  
2.   static{System.out.println("static block is invoked");}  
3.   public static void main(String args[]){  
4.    System.out.println("Hello main");  
5.   }  
6. }  
Test it Now
Output:static block is invoked
Hello main

Q) Can we execute a program without main() method?

Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is
not possible to execute a Java class without the main method.

1. class A3{  
2.   static{  
3.   System.out.println("static block is invoked");  
4.   System.exit(0);  
5.   }  
6. }  
Test it Now

Output:

static block is invoked

Since JDK 1.7 and above, output would be:


Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

this keyword in java

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

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
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 can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usage of this keyword.
1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, 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:

1. class Student{  
2. int rollno;  
3. String name;  
4. float fee;  
5. Student(int r,String n,floatf)  Rollno 111
6. {   Name ankit
7. rollno=r;   sumi 6000 Fee 5000
222
8. name=n;  
9. fee=f;  
10. }  
11. void display(){System.out.println(rollno+" "+name+" "+fee);}   s1
12. }  
13. class TestThis1{   Rollno 222

14. public static void main(String args[]){   Name sumit

15. Student s1=new Student(111,"ankit",5000f);   Fee 6000

16. Student s2=new Student(112,"sumit",6000f);  
17. s1.display();  
18. s2.display();  
19. }}   s2
Test it Now

Output:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword

rollno 112
1. name sumit
2. fee6000
3. class Student{  
4. int rollno;  
5. String name;  
6. float fee;  
7. Student(int rollno,String name,float fee){  
8. this.rollno=rollno;   sumi 6000
112
9. this.name=name;  rollno name fee
rollno=111
10. this.fee=fee;  
name =ankit
11. }  
fee=5000
12. void display(){System.out.println(rollno+" "+name+" "+fee);}  
13. }  
14.   
15. class TestThis2{   s1
16. public static void main(String args[]){  
17. Student s1=new Student(111,"ankit",5000f);   rollno=112
18. Student s2=new Student(112,"sumit",6000f);  
name =sumit
19. s1.display();  
fee=6000
20. s2.display();  
21. }}  
Test it Now

Output: s2

111 ankit 5000


112 sumit 6000

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

1. class Student{  
2. int rollno;  
3. String name;  
4. float fee;  
5. Student(int r,String n,float f){  
6. rollno=r;  
7. name=n;  
8. fee=f;  
9. }  
10. void display(){System.out.println(rollno+" "+name+" "+fee);}  
11. }  
12.   
13. class TestThis3{  
14. public static void main(String args[]){  
15. Student s1=new Student(111,"ankit",5000f);  
16. Student s2=new Student(112,"sumit",6000f);  
17. s1.display();  
18. s2.display();  
19. }}  
Test it Now

Output:

111 ankit 5000


112 sumit 6000
It is better approach to use meaningful names for variables. So we use same name for instance
variables and parameters in real time, and always use this keyword.
2) this: to invoke current class method

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
1. class A{  
2. void m()
3. {
4. System.out.println("hello m");
5. }  
6. void n()
7. {  
8. System.out.println("hello n");  
9. m();
10. }  
11. }  
12. class TestThis4{  
13. public static void main(String args[]){  
14. A a=new A();  
15. a.n();  
16. }}  
Test it Now

Output:

hello n
hello m
3) this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

1. class A{  
2. A()
3. {
4. System.out.println("hello a");
5. }  
6. A(int x)
7. {  
this ();  
8. System.out.println(x);  
9. }  
10. }  
11. class TestThis5{  
12. public static void main(String args[]){  
13. A a=new A(10);  
14. }}  
Test it Now

Output:

hello a
10

Calling parameterized constructor from default constructor:

1.
2.
3. class A{  
4. A(){  
5. this(5);  
6. System.out.println("this");  
7.
8. }  
9. A(int x){  
10. System.out.println(x);  
11. }  
12. }  
13. class TestThis6{  
14. public static void main(String args[]){  
15. A a=new A(); 
16. }}  
Test it Now

Output:

5
hello a
Unit 2
Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in Java in case of class?

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.
The syntax of Java Inheritance
1. class Subclass-name extends Superclass-name  
2. {  
3.    //methods and fields  
4. }  

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new
class is called child or subclass.

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer
is a type of Employee.

1. class Employee{  
2.  float salary=40000;  
3. }  
4. class Programmer extends Employee{  
5.  int bonus=10000;  
6.  public static void main(String args[]){  
7.    Programmer p=new Programmer();  
8.    System.out.println("Programmer salary is:"+p.salary);  
9.    System.out.println("Bonus of Programmer is:"+p.bonus);  
10. }  
11. }  
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will
learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void bark(){System.out.println("barking...");}  
6. }  
7. class TestInheritance{  
8. public static void main(String args[]){  
9. Dog d=new Dog();  
10. d.bark();  
11. d.eat();  
12. }}  
Output:

barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal class,
so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void bark(){System.out.println("barking...");}  
6. }  
7. class BabyDog extends Dog{  
8. void weep(){System.out.println("weeping...");}  
9. }  
10. class TestInheritance2{  
11. public static void main(String args[]){  
12. BabyDog d=new BabyDog();  
13. d.weep();  
14. d.bark();  
15. d.eat();  
16. }}  

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

File: TestInheritance3.java

1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void bark(){System.out.println("barking...");}  
6. }  
7. class Cat extends Animal{  
8. void meow(){System.out.println("meowing...");}  
9. }  
10. class TestInheritance3{  
11. public static void main(String args[]){  
12. Cat c=new Cat();  
13. c.meow();  
14. c.eat();  
15. //c.bark();//C.T.Error  
16. }}  

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A
and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time error.
1. class A{  
2. void msg(){System.out.println("Hello");}  
3. }  
4. class B{  
5. void msg(){System.out.println("Welcome");}  
6. }  
7. class C extends A,B{//suppose if it were  
8.    
9.  public static void main(String args[]){  
10.    C obj=new C();  
11.    obj.msg();//Now which msg() method would be invoked?  
12. }  
13. }  
Test it Now
Compile Time Error

Abstract class
Abstract classes are the class which contains method without providing a complete
implementation (or without having background details). It is not possible create object of an
abstract class. Abstract classes can include methods having all details.

Program 3.7 Demonstration of abstract


class.
Solution:.abstra
ct class A
{
abstract void callme();

// concrete methods are still allowed in abstract


void callmetoo()
{
System.out.println("This is a concrete method.");
}
}
class B extends A
{
void callme();
{
System.out.println("This is a A’s method.");

}
// concrete methods are still allowed in abstract

}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}

Although abstract classes cannot be used to instantiate objects, they can be used to create object
references, because Java’s approach to run-time polymorphism is implemented through the use
of super class references. Thus, it must be possible to create a reference to an abstract class so
that it can be used to point to a subclass object.

Uses of final Keyword: To Prevent Inheritance

The keyword final has three uses:


1. First, it can be used to create constant variable whose value cannot be changed.
2. To Prevent method Overriding
• While method overriding is one of Java’s most powerful features, there will be times
when you will want to prevent it from occurring.
• To disallow a method from being overridden, specify final as a modifier at the start of
its declaration. Methods declared as final cannot be overridden.
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{
System.out.println("Illegal!");
}
}

Because meth ( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a


compile-time error will result.

3. To Prevent Inheritance
Sometimes we want to prevent a class from being inherited. To do this, precede the class
declaration with the keyword final. Declaring a class as final implicitly declares all of its methods
as final, too.

final class A
{
...
}
// The following class is illegal.
class B extends A
{
/ ERROR! Can't subclass A
/ ...
}

As the comments imply, it is illegal for B to inherit A since A is declared as final.

Package and Interface


Packages are containers for classes that are used to keep the class name space
compartmentalized.
For example, a package allows us to create a class named List, which you can store in your
own package without concern that it will collide with some other class named List stored
elsewhere.
Packages are stored in a hierarchical manner and are explicitly imported into new class
definitions.

Defining a Package

To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the
specified package.
The package statement defines a name space in which classes are stored. If you omit the
package statement, the class names are put into the default package, which has no name.
(Thisis why you haven’t had to worry about packages before now.)
While the default package is fine for short, sample programs, it is inadequate for real
applications. Most of the time, you will define a package for your code.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement
creates a package called MyPackage. package MyPackage;

package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{

public static void main(String args[])


{
Balance current[] = new Balance[3];

current[0] = new Balance("Sanjib",


123.23); current[1] = new
Balance("Chandan", 157.02); current[2] =
new Balance("Palak", -12.33);

for(int i=0; i<3; i+


+)
current[i].show()
;
}
}

Call this file AccountBalance.java, and put it in a directory called MyPack. Next, compile the
file. Make sure that the resulting .class file is also in the MyPack directory. Then try executing
the AccountBalanceclass, using the following command line:
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this
command, or to have your CLASSPATH environmental variable set appropriately. As
explained, AccountBalance is now part of the package MyPack. This means that it cannot be
executed by itself. That is, you cannot use this command line:
java AccountBalance
AccountBalancemust be qualified with its package name.

Access Protection

Private No Modifier Protected Public

Same class Yes Yes Yes Yes

Same package subclass No Yes Yes Yes

Same package non-subclass No Yes Yes Yes

Different package subclass


No No Yes Yes

Different package non-subclass No No No Yes

Importing Packages
Given that packages exist and are a good mechanism for compartmentalizing diverse
classes from each other, it is easy to see why all of the built-in Java classes are stored in
packages.
In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions. This is the general form of the
import statement: import pkg1 [.pkg2].(classname|*);
package MyPack;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
name = n;
bal = b;
}
public void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
As we can see, the Balance class is now public. Also, its constructor and its show( ) method are
public, too. This means that they can be accessed by any type of code outside the MyPack
package. For example, here TestBalance imports MyPack and is then able to make use of the
Balance class:

import MyPack.*;
class TestBalance
{
public static void main(String args[])
{
Balance test = new Balance("J. J. Jaspers",
99.88); test.show(); // you may also call show()
}
}

Interface
An interface is a collection of abstract methods (i.e. methods without having
definition). A class that implements an interface inherits abstract methods of the
interface.
An interface is not a class.
Writing an interface is similar to writing a class, but they differ in concepts.
A class describes both attributes (i.e. variables) and behaviors (i.e. methods) of an
object. An interface contains only behaviors (i.e. methods) that a class implements.
If a class (provided it is not abstract) implements an interface, then all the methods of
interface need to be defined in it.
Declaring Interfaces

The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:

public interface NameOfInterface


{
//Any number of final, static variables
//Any number of abstract method declarations (i.e. method without definitions)
}

Interfaces have the following properties:

An interface is implicitly (i.e. by default) abstract. We do not need to use the abstract
keyword when declaring an interface.
Each method in an interface is also implicitly (i.e. by default) abstract, so the abstract
keyword is not needed.
Methods in an interface are implicitly (i.e. by default) public.

Implementing Interfaces

A class can implement more than one interface at a time.


A class can extend only one class, but can implement many
interfaces. An interface itself can extend another interface.
The general form of a class that includes the implements clause looks like

this: class classname [extends superclass] [implements interface

[,interface...]]
{
// class-body
}
Example:
interface Message
{
void message1();
void message2();
}

class A implements Message


{
void message1()
{
System.out.println("Good Morning");
}

void message2()
{
System.out.println("Good Evening");
}

public static void main(String args[])


{
A a=new A();
a.message1();
a.message2();
}
}

Similarities between class and interface

Both class and interface can contain any number of methods.


Both class and interface are written in a file with a .java extension, with the name of the
interface matching the name of the file.
The bytecode of both class and interface appears in a .class file.

Dissimilarities between class and interface

We cannot instantiate (i.e. create object) an interface but we can instantiate a class.
An interface does not contain any constructors but a class may contain any constructors.
All the methods in an interface are abstract (i.e. without definitions) but in a class method
may or may not be abstract.
An interface cannot contain variables. The only variable that can appear in an interface
must be declared both static and final. But a class can contain any variable.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces (i.e. multiple inheritances can be achieved
through it).
Exception Handling
Error occurred in a program can be of two types: syntax error or logical error.
An exception is an abnormal condition that arises in a code sequence at run time. In
other words, an exception is a run-time error.
A Java exception is an object that describes an exceptional (that is, error) condition that
has occurred in a piece of code.
Exception Handling is a mechanism by which exception occurred in a program is handled.
Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.

Keyword/Block Meanings
The statements which are expected to throw exception are kept inside try
try block block.

If an exception occurs within the try block, it is throws an exception to the


catch block catch
block which handle it in some rational manner.

throw To manually throw an exception, use the keyword throw.

throws A throws clause lists the types of exceptions that a method might throw.

Any code that absolutely must be executed before a method returns is put in
finally a
finally block.

Execution Flow of the try, catch and finally block

Try block

finally Catch block

finally
The general form of an exception-handling
block is: try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
………..
………..
finally
{
// block of code to be executed before try block ends
}

Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is
at the top of the exception class hierarchy.
The Throwable class has two subclasses Error and
Exception. Error and Exception classes are used for
handling errors in java.

Object

Throwable

Error Exception

SQL Runtime
Exception Exception
AWT Error

Class not Found Arithmatic

Thread
……. Number Format
…… ……
Unchecked exceptions
Before we learn how to handle exceptions in your program, it is useful to see what happens
when we don’t handle them. This small program includes an expression that intentionally
causes a divide-by-zero error.
class E
{
public static void main(String args[])
{
int x = 0;
int y = 1 /
x;
}
}

Here is the output generated when this example is


executed. java.lang.ArithmeticException: / by zero
at E.main(E.java:4)

Using try and catch

The following program includes a try block and a catch clause which processes the
ArithmeticExceptiongenerated by the division-by-zero error.

Program 5.1 Demonstration of Division by zero


Exception.
Solution
: class
Ex
{
public static void main(String args[])
{
int x, y;
try
{
x = 0;
y= 1/
x;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}

This program generates the following output:


Division by zero.
After catch statement.

Notice that the call to println( ) inside the try block is never executed. Once an exception is
thrown, program control transfers out of the try block into the catch block. Put differently,
catch is not “called,” so execution never “returns” to the try block from a catch. Thus, the line
“This will not be printed.” is not displayed. Once the catch statement has executed, program
control continues with the next line in the program following the entire try/catch mechanism.
In some cases, more than one exception could be raised by a single piece of code. To
handlethis type of situation, you can specify two or more catch clauses, each catching a
different type of exception. When an exception is thrown, each catch statement is inspected in
order, and the first one whose type matches that of the exception is executed. After one catch
statement executes, the others are bypassed, and execution continues after the try/catch
block. The following example traps two different exception types:

Program 5.2 Demonstration of multiple catch


block.
Solution:
class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " +
a); int b = 1 / a;
int c[] =
{3,4} c[42]
= 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
This program will cause a division-by-zero exception if it is started with no commandline
parameters, since a will equal zero. It will survive the division if you provide a command-line
argument, setting a to something larger than zero. But it will cause an
ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the
program attempts to assign a value to c[42].
Here is the output generated by running it both ways:

C:\>java
MultiCatch a = 0
Divide by 0: java.lang.ArithmeticException: / by
zero After try/catch blocks.
C:\>java
MultiCatchTestArg a = 1
Array index oob:
java.lang.ArrayIndexOutOfBoundsException After
try/catch blocks.

throw

So far, you have only been catching exceptions that are thrown by the Java run-time system.
However, it is possible for our program to throw an exception explicitly, using the throw
statement. The general form of throw is shown here:

throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

Program 5.3 Demonstration of throw statement.

Solution:

class ThrowDemo
{
public static void main(String args[])
{
int x=2,
y=0; try
{
if(y==0)
throw newArithmeticException();
}
catch(ArithmeticException e)
{
System.out.println("Exception Occurred: Division by 0 " + e);
}
}
}

throws
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. We do this
by including throws clause in the method's declaration. A throws clause lists the types of
exceptions that a methodmight throw.

This is the general form of a method declaration that includes a throws clause:
Return_type method-name (parameter-list) throws exception-list
{
// body of method
}
Program 5.4 Demonstration of thows
statement.

Solution:

class ThrowsDemo
{
static void throwOne() throws IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new
IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}

Finally

finally creates a block of code that will be executed after a try/catch block has
completed andbefore the code following the try/catch block.
The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no catch statement
matches the exception.

Program 5.5 Demonstration of finally


block.
Solution
: class
Ex
{
public static void main(String args[])
{
int x, y;
try
{
x = 0;
y= 1/
x;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
finally
{
System.out.println("End of Try/Catch Block");
}
}
}

Output:
Division by zero.
End of Try/Catch Block
Java’s Built-in Exceptions

Inside the standard package java.lang, Java defines several exception classes.
The most general of these exceptions,are subclasses of the standard type
RuntimeException. Since java.lang is implicitly,imported into all Java programs, most
exceptions derived from
RuntimeExceptionare automatically available.

Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked
thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread
state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.

User Defined Exceptions

Although Java’s built-in exceptions handle most common errors, we will probably want to
create our own exception types to handle situations specific to your applications.
This is quite easy to do: just define a subclass of Exception (which is, of course, a subclass of
Throwable).

Program 5.6 Demonstration of User Defined


Exceptions.
Solution:
class MyException extends Exception
{
private int detail;
MyException(int
a)
{
detail = a;
}
public String toString()
{
return "MyException[" + detail + "]";
}
}
class ExceptionDemo
{
static void compute(int a) throws MyException
{
System.out.println("Called compute(" + a + ")"); if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[])
{
try
{
compute(1);
compute(20);
}
catch (MyException e)
{
System.out.println("Caught " + e);
}
}
}
Interface in Java
1. Interface
2. Example of Interface
3. Multiple inheritance by Interface
4. Why multiple inheritance is supported in Interface while it is not supported in case of
class.
5. Marker Interface
6. Nested Interface

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.

Syntax:
1. interface <interface_name>{  
2.       
3.     // declare constant fields  
4.     // declare methods that abstract   
5.     // by default.  
6. }  

Java 8 Interface Improvement

Since Java 8, interface can have default and static methods which is discussed later.

Internal addition by the compiler


The Java compiler adds public and abstract keywords before the interface method.
Moreover, it adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.

The relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

Java Interface Example

In this example, the Printable interface has only one method, and its implementation is
provided in the A6 class.

1. interface printable{  
2. void print();
3.   }  
4. class A6 implements printable{  
5. public void print(){System.out.println("Hello");}  
6.   
7. public static void main(String args[]){  
8. A6 obj = new A6();  
9. obj.print();  
10.  }  
11. }  
Test it Now

Output:

Hello

Java Interface Example: Drawable

In this example, the Drawable interface has only one method. Its implementation is provided
by Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but
its implementation is provided by different implementation providers. Moreover, it is used by
someone else. The implementation part is hidden by the user who uses the interface.

File: TestInterface1.java

1. //Interface declaration: by first user  
2. interface Drawable{  
3. void draw();  
4. }  
5. //Implementation: by second user  
6. class Rectangle implements Drawable{  
7. public void draw(){System.out.println("drawing rectangle");}  
8. }  
9. class Circle implements Drawable{  
10. public void draw(){System.out.println("drawing circle");}  
11. }  
12. //Using interface: by third user  
13. class TestInterface1{  
14. public static void main(String args[]){  
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDra
wable()  
16. d.draw();  
17. }}  
Test it Now

Output:

drawing circle

Java Interface Example: Bank

Let's see another example of java interface which provides the implementation of Bank
interface.

File: TestInterface2.java

1. interface Bank{  
2. float rateOfInterest();  
3. }  
4. class SBI implements Bank{  
5. public float rateOfInterest(){return 9.15;}  
6. }  
7. class PNB implements Bank{  
8. public float rateOfInterest(){return 9.7;}  
9. }  
10. class TestInterface2{  
11. public static void main(String[] args){  
12. Bank b=new SBI();  
13. System.out.println("ROI: "+b.rateOfInterest());  
14. }}  
Test it Now

Output:

ROI: 9.15
Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is


known as multiple inheritance.

1. interface Printable{  
2. void print();  
3. }  
4. interface Showable{  
5. void show();  
6. }  
7. class A7 implements Printable,Showable{  
8. public void print(){System.out.println("Hello");}  
9. public void show(){System.out.println("Welcome");}  
10.   
11. public static void main(String args[]){  
12. A7 obj = new A7();  
13. obj.print();  
14. obj.show();  
15.  }  
16. }  
Test it Now
Output:Hello
Welcome
Q) Multiple inheritance is not supported through class in java, but it is possible by an interface,
why?

As we have explained in the inheritance chapter, multiple inheritance is not supported in the
case of class because of ambiguity. However, it is supported in case of an interface because
there is no ambiguity. It is because its implementation is provided by the implementation class.
For example:

1. interface Printable{  
2. void print();  
3. }  
4. interface Showable{  
5. void print();  
6. }  
7.   
8. class TestInterface3 implements Printable, Showable{  
9. public void print(){System.out.println("Hello");}  
10. public static void main(String args[]){  
11. TestInterface3 obj = new TestInterface3();  
12. obj.print();  
13.  }  
14. }  
Test it Now

Output:

Hello

As you can see in the above example, Printable and Showable interface have same methods
but its implementation is provided by class TestTnterface1, so there is no ambiguity.

Interface inheritance

A class implements an interface, but one interface extends another interface.

1. interface Printable{  
2. void print();  
3. }  
4. interface Showable extends Printable{  
5. void show();  
6. }  
7. class TestInterface4 implements Showable{  
8. public void print(){System.out.println("Hello");}  
9. public void show(){System.out.println("Welcome");}  
10.   
11. public static void main(String args[]){  
12. TestInterface4 obj = new TestInterface4();  
13. obj.print();  
14. obj.show();  
15.  }  
16. }  
Test it Now

Output:

Hello
Welcome

Java 8 Default Method in Interface

Since Java 8, we can have method body in interface. But we need to make it default method.
Let's see an example:

File: TestInterfaceDefault.java

1. interface Drawable{  
2. void draw();  
3. default void msg(){System.out.println("default method");}  
4. }  
5. class Rectangle implements Drawable{  
6. public void draw(){System.out.println("drawing rectangle");}  
7. }  
8. class TestInterfaceDefault{  
9. public static void main(String args[]){  
10. Drawable d=new Rectangle();  
11. d.draw();  
12. d.msg();  
13. }}  
Test it Now

Output:

drawing rectangle
default method

Java 8 Static Method in Interface

Since Java 8, we can have static method in interface. Let's see an example:

File: TestInterfaceStatic.java

1. interface Drawable{  
2. void draw();  
3. static int cube(int x){return x*x*x;}  
4. }  
5. class Rectangle implements Drawable{  
6. public void draw(){System.out.println("drawing rectangle");}  
7. }  
8.   
9. class TestInterfaceStatic{  
10. public static void main(String args[]){  
11. Drawable d=new Rectangle();  
12. d.draw();  
13. System.out.println(Drawable.cube(3));  
14. }}  
Test it Now

Output:

drawing rectangle
27

Q) What is marker or tagged interface?


An interface which has no member is known as a marker or tagged interface, for
example, Serializable, Cloneable, Remote, etc. They are used to provide some essential
information to the JVM so that JVM may perform some useful operation.

1. //How Serializable interface is written?  
2. public interface Serializable{  
3. }  

Nested Interface in Java

Note: An interface can have another interface which is known as a nested interface. We will
learn it in detail in the nested classes chapter. For example:

1. interface printable{  
2.  void print();  
3.  interface MessagePrintable{  
4.    void msg();  
5.  }  
6. }  

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since
abstract methods. Java 8, it can have default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of


implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare interface.


abstract class.

6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multiple Java interfaces.

7) An abstract class can be extended using An interface can be implemented using keyword


keyword "extends". "implements".

8) A Java abstract class can have class members Members of a Java interface are public by default.
like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Example of abstract class and interface in Java

Let's see a simple example where we are using interface and abstract class both.

1. //Creating interface that has 4 methods  
2. interface A{  
3. void a();//bydefault, public and abstract  
4. void b();  
5. void c();  
6. void d();  
7. }  
8.   
9. //Creating abstract class that provides the implementation of one method of A interface 
 
10. abstract class B implements A{  
11. public void c(){System.out.println("I am C");}  
12. }  
13.   
14. //Creating subclass of abstract class, now we need to provide the implementation of res
t of the methods  
15. class M extends B{  
16. public void a(){System.out.println("I am a");}  
17. public void b(){System.out.println("I am b");}  
18. public void d(){System.out.println("I am d");}  
19. }  
20.   
21. //Creating a test class that calls the methods of A interface  
22. class Test5{  
23. public static void main(String args[]){  
24. A a=new M();  
25. a.a();  
26. a.b();  
27. a.c();  
28. a.d();  
29. }}  
Test it Now

Output:

I am a
I am b
I am c
I am d

Exception Handling in Java


class A
{
public static void main(String args[] )
{
int a=10; int b =0; int c; int X[]={1,2};
try { AE
c= a/args.length;
}
Catch(Exception e)
{ Sopln(“hello”) ;}
System.out.println( c); AIOOBE
}
}

1. Exception Handling
2. Advantage of Exception Handling
3. Hierarchy of Exception classes
4. Types of Exception
5. Exception Example
6. Scenarios where an exception may occur

The Exception Handling in Java is one of the powerful mechanism to handle the runtime


errors so that normal flow of the application can be maintained.

In this page, we will learn about Java exceptions, its type and the difference between checked
and unchecked exceptions.

What is Exception in Java

Dictionary Meaning: Exception is an abnormal condition.


In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

What is Exception Handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,


IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:

1. statement 1;  
2. statement 2;  
3. statement 3;  
4. statement 4;  
5. statement 5;//exception occurs  
6. statement 6;  
7. statement 7;  
8. statement 8;  
9. statement 9;  
10. statement 10;  

Suppose there are 10 statements in your program and there occurs an exception at statement
5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we
perform exception handling, the rest of the statement will be executed. That is why we use
exception handling in Java.

Do You Know?

o What is the difference between checked and unchecked exceptions?


o What happens behind the code int data=50/0;?
o Why use multiple catch block?
o Is there any possibility when finally block is not executed?
o What is exception propagation?
o What is the difference between throw and throws keyword?
o What are the 4 rules for using exception handling with method overriding?

Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by
two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:
Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered
as the unchecked exception. According to Oracle, there are three types of exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions


e.g.ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g.OutOfMemoryError, VirtualMachineError, AssertionError etc.

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should place exception code. The try bl
followed by either catch or finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try block which mea
catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the program. It is executed wheth
handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
occur an exception in the method. It is always used with method signature.

Java Exception Handling Example

Let's see an example of Java Exception Handling where we using a try-catch statement to
handle the exception.
1. public class JavaExceptionExample{  
2.   public static void main(String args[]){  
3.    try{  
4.       //code that may raise exception  
5.       int data=100/0;  
6.    }catch(ArithmeticException e){System.out.println(e);}  
7.    //rest code of the program   
8.    System.out.println("rest of the code...");  
9.   }  
10. }  
Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch


block.

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException  

2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

1. String s=null;  
2. System.out.println(s.length());//NullPointerException  
3) A scenario where NumberFormatException occurs

The wrong formatting of any value may occur NumberFormatException. Suppose I have
a string variable that has characters, converting this variable into digit will occur
NumberFormatException.

1. String s="abc";  
2. int i=Integer.parseInt(s);//NumberFormatException  

4) A scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

1. int a[]=new int[5];  
2. a[10]=50; //ArrayIndexOutOfBoundsException  

Java Exceptions Index

1. Java Try-Catch Block


2. Java Multiple Catch Block
3. Java Nested Try
4. Java Finally Block
5. Java Throw Keyword
6. Java Exception Propagation
7. Java Throws Keyword
8. Java Throw vs Throws
9. Java Final vs Finally vs Finalize
10. Java Exception Handling with Method Overriding
11. Java Custom Exceptions

class MultiCatch
{
public static void main(String args[])
{
try
{
int a = args.length;
System.out.println("a = " +
a); int b = 1 / a;
int c[] =
{3,4} c[42]
= 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");

1. public class TestThrow1{  
2.    static void validate(int age){  
3.      if(age<18)  
4.       throw new ArithmeticException("not valid");  
5.      else  
6.       System.out.println("welcome to vote");  
7.    }  
8.    public static void main(String args[]){  
9.       validate(13);  
10.       System.out.println("rest of the code...");  
11.   }  
12. }  
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}

// This is now correct.


class ThrowsDemo {
static void throwOne () throws Exception {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (Exception e) {
System.out.println("Caught " + e);
}
}
}

1. class TestCustomException1{  
2.   
3.    static void validate(int age)throws InvalidAgeException{  
4.      if(age<18)  
5.       throw new InvalidAgeException("not valid");  
6.      else  
7.       System.out.println("welcome to vote");  
8.    }  
9.      
10.    public static void main(String args[]){  
11.       try{  
12.       validate(13);  
13.       }catch(Exception m){System.out.println("Exception occured: "+m);}  
14.   
15.       System.out.println("rest of the code...");  
16.   }  
17. }  

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy