Final Java Notes
Final Java Notes
Features Of Java
There is given many features of java. They are also known as java buzzwords.
1. Object Oriented :-
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies the software development and maintenance by providing some
concepts:-
i)Object
ii)Class
ii)Inheritance
iv)Polymorphism
v)Abstraction
vi)Encapsulation
[Link]-independent:-
Java runs on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX.
3. Simple:-
Java was designed to be easy for the professional programmer to learn and use
effectively. If you already understand the basic concepts of object-oriented
programming, learning Java will be even easier.
Best of all, if you are an experienced C++ programmer, moving to Java will
require very little effort. Because Java inherits the C/C++ syntax and many of the
object-oriented features of C++, most programmers have little trouble learning Java.
4. Secured:-
Java is secured because:
i) No explicit pointer
ii) Programs run inside virtual machine sandbox.
5. Robust:-
Robust simply means strong. Java uses strong memory management. There are
lack of pointers that avoids security problem. There is automatic garbage collection in
java. There is exception handling and type checking mechanism in java. All these
points make java robust.
6. Architectural-neutral:-
There is no implementation dependent features e.g. size of primitive types is
set.
7. Portable: -
We may carry the java bytecode to any platform.
8. 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 Java environment, in which small fragments of
bytecode may be dynamically updated on a running system.
9. Interpreted:-
As described earlier, Java enables the creation of cross-platform programs by
compiling into an intermediate representation called Java bytecode. This code can be
executed on any system that implements the Java Virtual Machine. Most previous
attempts at cross-platform solutions have done so at the expense of performance.
10. High-performance:-
Java is faster than traditional interpretation since byte code is "close" to native
code still somewhat slower than a compiled language (e.g., C++)
[Link]-threaded:-
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it shares the same memory. Threads are important
for multi-media, Web applications etc.
[Link]:-
We can create distributed applications in java. RMI and EJB are used for
creating distributed applications. We may access files by calling the methods from
any machine on the internet.
How Java Virtual Machine works?
By using Java Virtual Machine, this problem can be solved. But how it works on
different processors and O.S. Let's understand this process step by step.
Step 1:-
Step 2:-
Using the java compiler the code is converted into an intermediate code called
the bytecode. The output is a .class file.
Step 3:-
This code is not understood by any platform, but only a virtual platform called
the Java Virtual Machine.
Step 4:-
This Virtual Machine resides in the RAM of your operating system. When the Virtual
Machine is fed with this bytecode, it identifies the platform it is working on and converts
the bytecode into the native machine code.
Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of
memory location. It is a combination of "vary + able" that means its value can be changed.
Types of Variables
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared among
instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can
create a single copy of static variable and share among all the instances of the class. Memory
allocation for static variable happens only once when the class is loaded in the memory.
Example :
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Char 2 bytes
0 to 65535
boolean true or false
Arrays
Array is a collection of similar type of elements that have contagious memory location.
Array is an object the contains elements of similar data type. It is a data structure where we
store similar elements. We can store only fixed elements in an array.
Arrays are capable of storing primitive data types as well as objects. The elements of the
array can be accessed by its index value that starts from 0. Once array is declared, its size
cannot be altered dynamically.
Arrays can be :-
a) declared and later assigned or
b) initialized.
// declaration of an array
int subject[ ] = new int[ 10 ] ;
// if not assigned, default 0 is assigned for int element
[Link]( subject[ 1 ] ) ;
Advantages of Array
1. Code Optimization: It makes the code optimized, we can retrive or sort the data easily.
2. Random access: We can get any data located at any index position.
Disadvantage of Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in java.
Types of Array
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
Example:-Single Dimensional Array
//initialization
array[0]=100;
array[1]=200;
array[2]=300;
array[3]=400;
array[4]=500;
array[5]=600;
//printing array
[Link](array[i]);
Output:-
123
245
445
Java Constructors
A constructor is a special member method which will be called by the JVM
implicitly(automatically) for placing user/programmer defined values instead of placing
default values.
Constructors are meant for initializing the object. Constructor is a special type of method that
is used to initialize the state of an object.
Constructor is invoked at the time of object creation. It constructs the values i.e. data for the
object that is why it is known as constructor.
Constructor is just like the instance method but it does not have any explicit return type.
Advantages of Constructors:
1. A constructor eliminates placing the default values.
2. A constructor eliminates callling the normal method implicitly.
RULES/CHARACTERISTICS of a Constructor:
1. Constructor name must be same as its class name.
2. Constructor should not return any value even void also.
3. Costructors should not be static .
4. Constructors should not be private.
5. Constructors will not be inherited at all.
6. Constructors are called automatically whenever an object is cereating.
Types of Constructors:
There are two types of constructors:-
1. Default constructor (no-argument constructor)
2. Parameterized constructor
Syntax:-
class < class name >
{
classname() //default constructor
{
Block of statements;
...................;
...................;
}
..................;
..................;
};
Example:-
//Start Of TestConstructor
class TestConstrucutor
{
int a, b;
TestConstructor()
{
[Link](" Default Constructor !!!");
a = 10;
b = 20;
[Link]("Value of a = " +a);
[Link]("Value of b = " +b);
}
};
class MainConstructor
{
public static void main(String args[])
{
TestConstructor obj = new TestConstructor();
}
};
2. Parameterized Constructor:-
Syntax:-
Example:-
//Start Of TestConstructor
class TestConstrucutor
{
int a, b;
TestConstructor(int x, int y)
{
[Link](" Parameterized Constructor !!!");
a = x;
b = y;
[Link]("Value of a = " +a);
[Link]("Value of b = " +b);
}
};
class MainConstructor
{
public static void main(String args[])
{
TestConstructor obj = new TestConstructor(10,20);
}
};
[Link]
InputStreamReader
BufferedReader
The data is received in the form of bytes from the keyboard by [Link] which is an InputStream
object.
Then the InputStreamReader reads bytes and decodes them into characters.
Then finally BufferedReader object reads text from a character-input stream, buffering characters so
as to provide for the efficient reading of characters, arrays, and lines.
[Link]() reads a single character from the BufferedReader object ‘br’ but returns its ASCII value
which is an integer. so we use typecast to convert an integer to character by using (char) before
[Link]().
String s = [Link]()
[Link]() reads a line of text from the BufferedReader object ‘br’ and returns string. So no need of
casting here.
String no = [Link]()
To retrieve integer, we use
Since typecasting is done only between data types and String is a class. we cannot typecast
String to an integer so we use parseInt method of Integer Wrapper class. Similarly for other
data types, refer the below table
double value =
Double [Link]([Link]() );
boolean value =
Boolean [Link]([Link]() );
import [Link];
Sample output:
import [Link];
Sample output:
Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on
the data (methods) together as a single unit. In encapsulation, the variables of a class will be
hidden from other classes, and can be accessed only through the methods of their current
class. Therefore, it is also known as data hiding.
[Link](6);
[Link]("aarti");
[Link]([Link]());
[Link]([Link]());
}
class Emp
return empId;
[Link] = empId;
return empNm;
[Link](6);
[Link]("aarti");
[Link]([Link]());
[Link]([Link]());
class Emp
{ return empId; }
{ [Link] = empId; }
{ return empNm; }
{ [Link] = empNm; }
Inheritance.
The process by which one class acquires the properties(data members) and
functionalities(methods) of another class is called inheritance. The aim of inheritance is to
provide the reusability of code so that a class has to write only the unique features and rest of
the common properties and functionalities can be extended from the another class.
Child Class:
The class that extends the features of another class is known as child class, sub class or
derived class.
Parent Class:
The class whose properties and functionalities are used(inherited) by another class is known
as parent class, super class or Base class.
Syntax
To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is
parent class. The class XYZ is inheriting the properties and methods of ABC class.
Types of inheritance
1. Single Inheritance:
a1.num1=5;
a1.num2=50;
[Link]();
[Link]();
}
class Add
int num1,num2,result;
result=num1+num2;
[Link](result);
result=num1-num2;
[Link](result);
[Link] inheritance:
Multilevel inheritance: refers to a child and parent class relationship where a class extends the
child class. For example class C extends class B and class
extends class A.
public class Multilevelinheritance
[Link]();
class child1
child2()
{
child3()
void show()
[Link](str);
[Link]();
}
class child1
child2()
child3()
}
void show()
[Link](str);
Hierarchical inheritance:
refers to a child and parent class relationship where more than one classes extends the same
class. For example, classes B, C & D extends the same class A.
Multiple Inheritance:
refers to the concept of one class extending more than one classes, which means a child class
has two parent classes. For example class C extends both classes A and B. Java doesn’t
support multiple inheritance, read more about it here.
Keywords in java:
class Test
{
int a;
int b;
// Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
}
void display()
{
//Default constructor
Test()
{
this(10, 20);
[Link]("Inside default constructor \n");
}
//Parameterized constructor
Test(int a, int b)
{
this.a = a;
this.b = b;
[Link]("Inside parameterized constructor");
}
//Default constructor
Test()
{
a = 10;
b = 20;
}
// Default constructor
Test()
{
a = 10;
b = 20;
}
void display()
{
// calling fuction show()
[Link]();
void show() {
[Link]("Inside show funcion");
}
class B
{
int x = 5;
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
}
class Animal
{
String color="White";
}
class Dog extends Animal
{
String color="black";
void display()
{
[Link](color);//prints color of Dog class
[Link]([Link]);//prints color of Animal class
}
}
}
class CircleArea
{
float pi=3.14f;
int r=1;
float result;
void cal()
{
result=pi*r*r;
[Link]("area of circle"+result);
}
}
class CirclePeremeter extends CircleArea
{
void cal()
{
[Link]();
result=2*pi*r;
[Link]("Perimeter of circle :"+result);
}
}
}
class A
{
A()
{
[Link]("defalut constructor of class A");
}
A(int x)
{
[Link]("parameterise constructor of class A");
}
}
class B extends A
{
B()
{
super(2);
[Link]("default constructor of class B");
}
B(int x)
{
[Link]("parameterised constructor of class B");
}
}
Output:-
parameterise constructor of class A
Let's see the real use of super keyword. Here, Emp class inherits Person class so all the
properties of Person will be inherited to Emp by default. To initialize all the property, we are
using parent class constructor from child class. In such way, we are reusing the parent class
constructor
class Person
{
int id;
String name;
Person(int id,String name)
{
[Link]=id;
[Link]=name;
}
}
class Emp extends Person
{
float salary;
Emp(int id,String name,float salary)
{
super(id,name);//reusing parent constructor
[Link]=salary;
}
void display()
{
[Link](id+" "+name+" "+salary);}
}
class TestSuper5
{
public static void main(String[] args)
{
Emp e1=new Emp(1,"ankit",45000f);
[Link]();
}
}
Output:-
1 ankit 45000
The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students
etc.
The static variable gets memory only once in class area at the time of class loading.
class Student{
int rollno;
String name;
String college="ITS";
Suppose there are 500 students in my college, now all instance data members will get
memory each time when object is [Link] student have its unique rollno and name
so instance data member is [Link], college refers to the common property of all
[Link] we make it static,this field will get memory only once.
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.
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;
[Link](count);
}
public static void main(String args[]){
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Output:
1
2
3
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
Output:125
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method
directly.
class A{
int a=40;//non static
public static void main(String args[]){
[Link](a);
}
}
Test it Now
Output:Compile Time Error
Ans) because object is not required to call static method if it were non-static method,
jvm create object first then call main() method that will lead the problem of extra
memory allocation.
Ans) Yes, one of the way is static block but in previous version of JDK not in JDK
1.7.
class A3{
static{
[Link]("static block is invoked");
[Link](0);
}
}
Test it Now
Output:Error: Main method not found in class A3, please define the main method as:
[Link] Keyword
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
[Link]
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
class Bike{
final void run(){[Link]("running");}
}
class Honda extends Bike{
void run(){[Link]("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
[Link]();
}
}
Test it Now
Output:Compile Time Error
}
Output:Compile Time Error
Polymorphism:
Polymorphism is the capability of a method to do different things based on the object that it is
acting upon. In other words, polymorphism allows you define one interface and have multiple
implementations.
Types of polymorphism
[Link] time Polymorphism/method overloading:
public class Polycompiletime
{
public static void main(String[] args)
{
overload o=new overload();
[Link]();
[Link](5.6);
[Link](8);
[Link](4, 6);
}
}
class overload
{
void show()
{
[Link]("hi");
}
void show(int a)
{
[Link]("a :"+a);
}
void show(double b)
{
[Link]("b :"+b);
}
void show(int a,int b)
{
[Link]("Addotion of a and b : "+(a+b));
}
}
Output:-
}
class A
{
public void show()
{
[Link]("in show A");
}
}
class B extends A
{
public void show()
{
[Link]("in show B");
}
}
Note:if you have to pass obj1 to reference a then it will display show() of class A.
Output:-
in show B
Java Garbage Collection
In java, garbage means unreferenced objects.
To do so, we were using free() function in C language and delete() in C++. But, in java
it is performed automatically. So, java provides better memory management.
It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
1) By nulling a reference:
Employee e=new Employee();
e=null;
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object
class as:
Note: The Garbage collector of JVM collects only those objects that are created by new
keyword. So if you have created any object without new, you can use finalize method to
perform cleanup processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing.
The gc() is found in System and Runtime classes.
1) String Literal
String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the
string already exists in the pool, a reference to the pooled instance is returned. If string
doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any string
object with the value "Welcome" in string constant pool, so it will create a new object. After
that it will find the string with the value "Welcome" in the pool, it will not create new object
but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool.
To make Java more memory efficient (because no new objects are created if it exists already
in string constant pool).
2) By new keyword
The [Link] class provides many useful methods to perform operations on sequence
of char values.
No. Method
1 char charAt(int index) returns char value for the particular index
4 static String format(Locale l, String format, returns formatted string with given locale
Object... args)
5 String substring(int beginIndex)
6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index
7 boolean contains(CharSequence s) returns true or false after matching the sequence of char
value
8 static String join(CharSequence delimiter, returns a joined string
CharSequence... elements)
9 static String join(CharSequence delimiter, returns a joined string
Iterable<? extends CharSequence> elements)
10 boolean equals(Object another) checks the equality of string with object
11 boolean isEmpty() checks if string is empty
12 String concat(String str) concatinates specified string
13 String replace(char old, char new) replaces all occurrences of specified char value
14 String replace(CharSequence old, CharSequence replaces all occurrences of specified CharSequence
new)
15 static String equalsIgnoreCase(String another) compares another string. It doesn't check case.
16 String[] split(String regex) returns splitted string matching regex
17 String[] split(String regex, int limit) returns splitted string matching regex and limit
18 String intern() returns interned string
19 int indexOf(int ch) returns specified char value index
20 int indexOf(int ch, int fromIndex) returns specified char value index starting with given
index
21 int indexOf(String substring) returns specified substring index
22 int indexOf(String substring, int fromIndex) returns specified substring index starting with given
index
23 String toLowerCase() returns string in lowercase.
24 String toLowerCase(Locale l) returns string in lowercase using specified locale.
25 String toUpperCase() returns string in uppercase.
26 String toUpperCase(Locale l) returns string in uppercase using specified locale.
27 String trim() removes beginning and ending spaces of this string.
28 static String valueOf(int value) converts given type into string. It is overloaded.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}
The insert() method inserts the given string with this string at the given position.
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link](1,"Java");//now original string is changed
[Link](sb);//prints HJavaello
}
}
The replace() method replaces the given string from the specified beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3,"Java");
[Link](sb);//prints HJavalo
}
}
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link](1,3);
[Link](sb);//prints Hlo
}
}
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
[Link]();
[Link](sb);//prints olleH
}
}
The StringBuilder append() method concatenates the given argument with this string.
class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
}
}
toString() method
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object.
So overriding the toString() method, returns the desired output, it can be the state of an object
etc. depends on your implementation.
Advantage of Java toString() method
By overriding the toString() method of the Object class, we can return values of the object, so
we don't need to write much code.
class Student{
int rollno;
String name;
String city;
class Student{
int rollno;
String name;
String city;
StringTokenizer in Java
The [Link] class allows you to break a string into tokens. It is simple
way to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class.
example 1
Let's see the simple example of StringTokenizer class that tokenizes a string "my name is
khan" on the basis of whitespace.
import [Link];
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while ([Link]()) {
[Link]([Link]());
}
}
}
Output:my
name
is
khan
example 2
import [Link].*;
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.
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:
interface <interface_name>{
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.
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: [Link]
Output:
drawing circle
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}
Interface inheritance:-
A class implements an interface, but one interface extends another interface.
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
Example2:-
abstract class Bike{
Bike(){[Link]("bike is created");}
abstract void run();
void changeGear(){[Link]("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){[Link]("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
[Link]();
[Link]();
}
}
Output:-
bike is created
running safely..
gear changed
Rule: If you are extending an abstract class that has an abstract method, you must either
provide the implementation of the method or make this class abstract.
We use inner classes to logically group classes and interfaces in one place so that it can be
more readable and maintainable.
Additionally, it can access all the members of outer class including private data members and
methods.
Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner A class created for implementing interface or extending class.
Class
Its name is decided by the java compiler.
A non-static class that is created inside a class but outside a method is called member inner
class.
Syntax:
class Outer{
//code
class Inner{
//code
}
}
example
In this example, we are creating msg() method in member inner class that is accessing the
private data member of outer class.
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){[Link]("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
[Link] in=[Link] Inner();
[Link]();
}
}
Java Local inner class
A class i.e. created inside a method is called local inner class in java. If you want to invoke
the methods of local inner class, you must instantiate this class inside the method.
Example:-
Output:
30
A class that have no name is known as anonymous inner class in java. It should be used if
you have to override method of class or interface. Java Anonymous inner class can be created
by two ways:
example
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){[Link]("nice fruits");}
};
[Link]();
}
}
Output:
nice fruits
A static class i.e. created inside a class is called static nested class in java. It cannot access
non-static data members and methods. It can be accessed by outer class name.
Output:
data is 30
An interface i.e. declared within another interface or class is known as nested interface. The
nested interfaces are used to group related interfaces so that they can be easy to maintain. The
nested interface must be referred by the outer interface or class. It can't be accessed directly.
Syntax :-
interface interface_name{
...
interface nested_interface_name{
...
}
}
interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface1 implements [Link]{
public void msg(){[Link]("Hello nested interface");}
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.
What is Exception in Java
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
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.
The [Link] 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
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
Try The "try" keyword is used to specify a block where we should place exception code. The try
block must be 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
means we can't use 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
whether an exception is 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 that there may 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.
Output:
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
[Link]([Link]());//NullPointerException
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.
String s="abc";
int i=[Link](s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Example:
class Excep6{
public static void main(String args[]){
try{
try{
[Link]("going to divide");
int b =39/0;
}catch(ArithmeticException e){[Link](e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){[Link](e);}
[Link]("other statement);
}catch(Exception e){[Link]("handeled");}
[Link]("normal flow..");
}
}
Note: If you don't handle exception, before terminating the program, JVM executes finally
block(if any).
class TestFinallyBlock{
int data=25/5;
[Link](data);
catch(NullPointerException e){[Link](e);}
Test it Now
Output:5
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a message
welcome to vote.
Output:
Multithreading in java
is a process of executing multiple threads simultaneously.
However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.
Each process has an address in memory. In other words, each process allocates a
separate memory area.
A process is heavyweight.
Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.
A thread is lightweight.
Threads are independent. If there occurs exception in one thread, it doesn't affect other
threads. It uses a shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads.
ead Methods
thread object.
5) void join() It waits for a thread to die.
6) int getPriority() It returns the priority of the thread.
7) void setPriority() It changes the priority of the thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
10) long getId() It returns the id of the thread.
11) boolean isAlive() It tests if the thread is alive.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but before the invocation
of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
{
public void run()
{
for(int i=0;i<=4;i++)
{
[Link]("hi");
try{[Link](1000);}catch(Exception e){}
}
}
}
class hello implements Runnable
{
public void run()
{
for(int i=0;i<=4;i++)
{
[Link]("hello");
try{[Link](1000);}catch(Exception e){}
}
}
}
class threadedemo
{
public static void main(String ar[])
{
hi h=new hi();
hello ho=new hello();
Thread t=new Thread(h);
Thread t1=new Thread(ho);
[Link]();
try{[Link](500);}catch(Exception e){}
[Link]();
}
}
No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for second
time, it will throw exception.
Syntax:
public void join()throws InterruptedException
[Link]();
[Link]();
}
}
Output:
1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
getName(),setName(String) and getId() method:
public String getName()
[Link]();
[Link]();
[Link]("Sonoo Jaiswal");
[Link]("After changing name of t1:"+[Link]());
}
}
Output:
Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...
Syntax:
public static Thread currentThread()
[Link]();
[Link]();
}
}
Output:
Thread-0
Thread-1
Priority of a Thread (Thread Priority):
Each thread have a priority. Priorities are represented by a number between 1 and 10. In
most cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses.
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
}
}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
Secured
It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os
etc.
Drawback of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
}
Note: class must be public because its object is created by Java Plugin software that resides
on the browser.
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>
________________________________________
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer [Link]. Now Html file is not
required but it is for testing purpose only.
//[Link]
import [Link];
import [Link];
public class First extends Applet{
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:
import [Link];
import [Link];
[Link]
<html>
<body>
<applet code="[Link]" width="300" height="300">
<param name="msg" value="Welcome to applet">
</applet>
</body>
</html>
</applet>
*/
We can get any information from the HTML file as a parameter. For this purpose, Applet
class provides a method named getParameter(). Syntax:
public String getParameter(String parameterName)
import [Link];
import [Link];
String str=getParameter("msg");
[Link](str,50, 50);
[Link]
<html>
<body>
</applet>
</body>
c:\>javac [Link]
c:\>appletviewer [Link]
Java Package
Package are used in Java, in-order to avoid name conflicts and to control access of class,
interface and enumeration etc. A package can be defined as a group of similar types of
classes, interface, enumeration or sub-package. Using package it becomes easier to locate the
related classes and it also provides a good structure for projects with hundreds of classes and
other files.
Built-in Package: Existing Java package for example [Link], [Link] etc.
User-defined-package: Java package created by user to categorize their project's classes
and interface.
Creating a package
Creating a package in java is quite easy. Simply include a package command followed by
name of the package as the first statement in java source file.
package mypack;
statement;
The above statement will create a package woth name mypack in the project directory.
Java uses file system directories to store packages. For example the .java file for any class
you define to be part of mypack package must be stored in a directory called mypack.
Additional points about package:
A package is always defined as a separate folder having the same name as the package
name.
Store all the classes in that package folder.
All classes of the package which we wish to access outside the package must be declared
public.
All classes within the package must have the package statement as its first line.
All classes of the package must be compiled before use (So that they are error free)
package learnjava;
[Link]("Welcome to package");
Example:
javac -d . [Link]
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like d:/abc (in case of windows) etc. If you want to keep the package within
the same directory, you can use . (dot).
To Run:
java [Link]
import keyword
import keyword is used to import built-in and user-defined packages into your java source
file so that your class can refer to a class that is in another package by directly using its name.
There are 3 different ways to refer to any class that is present in a different package:
If you use fully qualified name to import any class into your program, then only that
particular class of the package will be accessible in your program, other classes in the
same package will not be accessible. For this approach, there is no need to use
the import statement. But you will have to use the fully qualified name every time you are
accessing the class or the interface, which can look a little untidy if the package name is
long.
This is generally used when two packages have classes with same names. For
example: [Link] and [Link] packages contain Date class.
Example :
//save by [Link]
package pack;
public class A {
[Link]("Hello");
//save by [Link]
package mypack;
class B {
[Link]();
Output:
Hello
If you import [Link] then only the class with name classname in the
package with name packagename will be available for use.
Example :
//save by [Link]
package pack;
public class A {
public void msg() {
[Link]("Hello");
}
}
//save by [Link]
package mypack;
import pack.A;
class B {
public static void main(String args[]) {
A obj = new A();
[Link]();
}
}
Output:
Hello
If you use packagename.*, then all the classes and interfaces of this package will be
accessible but the classes and interface inside the subpackages will not be available for
use.
The import keyword is used to make the classes and interface of another package
accessible to the current package.
Example :
//save by [Link]
package learnjava;
[Link]("Hello");
//save by [Link]
package Java;
import learnjava.*;
class Second {
public static void main(String args[]) {
First obj = new First();
[Link]();
}
}
Output:
Hello
Points to remember
When a package name is not specified, the classes are defined into the default package
(the current working directory) and the package itself is given no name. That is why, you
were able to execute assignments earlier.
While creating a package, care should be taken that the statement for creating package
must be written before any other import statements.
// not allowed
import package p1.*;
package p3;
Below code is correct, while the code mentioned above is incorrect.
//correct syntax
package p3;
import package p1.*;