Unit 1
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
recognized by JVM
Solaris
(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).
(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.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.
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);
It also converts the Bytes (from the input stream) into characters using the platform's default
charset.
Java Scanner class provides the following methods to read different primitives types:
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:
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);
// String input
// Numerical input
int age =myObj.nextInt();
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.
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
class Student{
int a;
int b;
a=c;
b=d;
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
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.
1) If you want to make your object eligible for Garbage Collection, assign its reference variable to
null.
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.
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.
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.
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.
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.
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
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
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.
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
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.
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.
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:
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
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
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.
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
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
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:
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to
the current object.
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.
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
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.
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
If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:
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:
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.
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
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.
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.
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.
When one class inherits multiple classes, it is known as multiple inheritance. For 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...
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...
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...
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.
}
// 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.
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
/ ...
}
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
{
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
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:
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
[,interface...]]
{
// class-body
}
Example:
interface Message
{
void message1();
void message2();
}
void message2()
{
System.out.println("Good Evening");
}
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.
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.
Try 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
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;
}
}
The following program includes a try block and a catch clause which processes the
ArithmeticExceptiongenerated by the division-by-zero error.
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:
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.
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.
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.
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).
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.
There are mainly three reasons to use interface. They are given below.
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. }
Since Java 8, interface can have default and static methods which is discussed later.
In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.
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
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
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
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
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
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
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
1. //How Serializable interface is written?
2. public interface Serializable{
3. }
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. }
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.
3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
6) An abstract class can extend another Java An interface can extend another Java interface only.
class and implement multiple Java interfaces.
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();
} }
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
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
In this page, we will learn about Java exceptions, its type and the difference between checked
and unchecked exceptions.
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?
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
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
3) Error
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.
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.
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:
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1. int a=50/0;//ArithmeticException
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
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
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();
}
}
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. }