Java Notes
Java Notes
Raj
History of JAVA
JAVA is a distributed technology developed by James Gosling, Patric Naugton, etc., at Sun Micro
System has released lot of rules for JAVA and those rules are implemented by JavaSoft Inc, USA (which is
the software division of Sun Micro System) in the year 1990. The original name of JAVA is OAK (which is
a tree name). In the year 1995, OAK was revised and developed software called JAVA (which is a coffee
seed name). JAVA released to the market in three categories J2SE (JAVA 2 Standard Edition), J2EE (JAVA
2 Enterprise Edition) and J2ME (JAVA 2 Micro/Mobile Edition). i. J2SE is basically used for developing
client side applications/programs. ii. J2EE is used for developing server side applications/programs. iii.
J2ME is used for developing server side applications/programs. If you exchange the data between client
and server programs (J2SE and J2EE), by default JAVA is having on internal support with a protocol called
http. J2ME is used for developing mobile applications and lower/system level applications. To develop
J2ME applications we must use a protocol called WAP (Wireless Applications Protocol).
What is Java?
Java is a programming language and platform. Platform any hardware or software environment in which
a program runs known as platform. Since java has its own Runtime Environment (JRE) and API, it is called
as platform.
Features of Java:
There is given many features of java. They are also known as java buzzwords. The Java Features given
below are simple and easy to understand.
Simple
Object-Oriented
Platform independent
Secured
Robust
Portable
Interpreted
High Performance
Multithreaded
Distributed
Sample Program:
public class SampleProgram {
2
Understanding first java program
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility, it means it is visible to all.
static is a keyword, if we declare any method as static, it is known as static method. The core
advantage of static method is that there is no need to create object to invoke the static method.
The main method is executed by the JVM, so it doesn't require creating object to invoke the
main method.
void is the return type of the method, it means it doesn't return any value.
main represents startup of the program.
String[] args is used for command line argument.
System.out.println() is used print statement.
Variable
Variable is a name of memory location. (OR) A variable is an identifier whose value will be changed
during execution of the program.
Types of Variable:
There are three types of variables in java
local variable
A variable that is declared inside the method is called local variable.
instance variable
A variable that is declared inside the class but outside the method is called instance variable . It
is not declared as static.
static variable
A variable that is declared as static is called static variable. It cannot be local.
class A {
int data = 50;// instance variable
static int m = 100;// static variable
void method() {
int n = 90;// local variable
}
}
Constant: Constant is an identifier whose value cannot be changed during execution of the program.
In JAVA to make the identifiers are as constants, we use a keyword called final.
Final is a keyword which is playing an important role in three levels. They are at variable level, at
method level and at class level.
3
When we don’t want to change the value of the variable, then that variable must be declared as
final.
When the final variable is initialized, no more modifications or assignments are possible
Example:
final int a =10; //valid
final int b;
b=20; //invalid
Datatypes
There are two types of datatypes in java, primitive and non-primitive.
4
Object based programming language:
Object based programming language follows all the features of OOPs except Inheritance. JavaScript and
VBScript are examples of object based programming languages.
class Room {
int l;// data member (also instance variable)
int w;// data member (also instance variable)
}
}
new: The new keyword is used to allocate memory at runtime. This new operator is known as dynamic
memory allocation operator.
Object gets the memory in Heap area and reference variable refers to the object allocated in the
Heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in
memory. Method gets the memory in Stack. All constants of JAVA program available in associative
memory.
Anonymous object
Anonymous simply means nameless. An object that has no reference is known as anonymous
object.
If you have to use an object only once, anonymous object is a good approach.
class Calculation {
void fact(int n) {
5
int fact = 1;
for (int i = 1; i <= n; i++) {
fact = fact * i;
}
System.out.println("factorial is " + fact);
}
Method overloading:
If a class has multiple methods by same name but different parameters, it is known as Method
Overloading. Method overloading increases the readability of the program.
There are two ways to overload the method in java
By changing number of arguments
By changing the data type
Example 1:
class Calc {
void sum(int a, int b) {
System.out.println(a + b);
}
Example2:
class Room {
void area(int l, int b) {
System.out.println(l * b);
}
6
Room rm = new Room();
rm.area(20, 20);
rm.area(10.5, 10.5);
}
}
Constructor
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.
Rules for creating constructor:
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
Constructors should not be static since constructors will be called each and every time
whenever an object is creating.
Constructor should not be private provided an object of one class is created in another class
(constructor can be private provided an object of one class created in the same class).
Constructors will not be inherited at all.
Constructors are called automatically whenever an object is creating.
Types of constructors:
There are two types of constructors:
default constructor is one which will not take any parameters (no-arg constructor)
parameterized constructor
Example1:
A constructor that has no parameter is known as default constructor.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
class Bike {
Bike() {
System.out.println("Bike is created");
}
7
Example 2:
class Bike {
Bike(String name) {
System.out.println("Bike is created name is :" + name);
}
Static block
The static keyword is used in java mainly for memory management. We may apply static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than
instance of the class.
The static can be:
variable (also known as class variable)
method (also known as class method)
block
nested class
Inheritance
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors
of parent object. 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
parent class, and you can add new methods and fields also. Inheritance represents the IS-A relationship,
also known as Parent-Child relationship.
class Superclass-name{
//methods and fields
}
class Subclass-name extends Superclass-name{
//methods and fields
}
The keyword extends indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a
subclass.
class Employee1 {
float salary = 40000;
}
8
public static void main(String args[]) {
Programmer p = new Programmer();
System.out.println("Programmer salary is:" + p.salary);
System.out.println("Bonus of Programmer is:" + p.bonus);
}
}
Method overriding
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding. In other words, If subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as Method Overriding.
Advantage of Java Method Overriding:
Method Overriding is used to provide specific implementation of a method that is already
provided by its super class.
Method Overriding is used for Runtime Polymorphism
Rules for Method Overriding:
method must have same name as in the parent class
method must have same parameter as in the parent class.
must be IS-A relationship (inheritance).
class Bank {
int getRateOfInterest() {
return 0;
}
}
class SBI extends Bank {
int getRateOfInterest() {
return 7;
}
}
class ICICI extends Bank {
int getRateOfInterest() {
return 8;
}
}
class Customer {
public static void main(String args[]) {
SBI s = new SBI();
ICICI i = new ICICI();
System.out.println("SBI Rate of Interest: " + s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: " + i.getRateOfInterest());
}
}
Static method cannot be overridden because static method is bound with class whereas instance method
is bound with object. Static belongs to class area and instance belongs to heap area.
9
Super
The super is a reference variable that is used to refer immediate parent class object. Whenever
you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by super
reference variable.
Usage of super Keyword:
super is used to refer immediate parent class instance variable.
super() is used to invoke immediate parent class constructor.
super is used to invoke immediate parent class method.
class Account {
public Account() {
System.out.println("opening an account");
}
}
class Customer {
public static void main(String args[]) {
Savings s = new Savings();
}
}
this
‘this’ is an internal or implicit object created by JAVA for two purposes. They are
‘this’ object is internally pointing to current class object.
Whenever the formal parameters and data members of the class are similar, to differentiate the
data members of the class from formal parameters, the data members of class must be
proceeded by ‘this’.
Final
The final keyword in java is used to restrict the user. The final keyword can be used in many
contexts. Final can be:
variable
If you make any variable as final, you cannot change the value of final variable (It will be
constant).
Method
If you make any method as final, you cannot override it.
10
Class
If you make any class as final, you cannot extend it.
Runtime polymorphism
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time. In this process, an overridden
method is called through the reference variable of a superclass. The determination of the method to be
called is based on the object being referred to by the reference variable.
In the below example, we are creating two classes Bike and Splender. Splender class extends
Bike class and overrides its run() method. We are calling the run method by the reference variable of
Parent class. Since it refers to the subclass object and subclass method overrides the Parent class
method, subclass method is invoked at runtime. Since method invocation is determined by the JVM not
compiler, it is known as runtime polymorphism.
Upcasting:
When reference variable of Parent class refers to the object of Child class, it is known as upcasting.
example:
class Bike {
void run() {
System.out.println("running");
}
}
11
Run time polymorphism can’t be achieved by data members.
Example:
class Bike {
int speedlimit = 90;
}
12
Animal a = new Dog();
a.eat();
}
}
//output: dog is eating…
In the above example object type cannot be determined by the compiler, because the instance of Dog is
also an instance of Animal. So compiler doesn't know its type, only its base type.
Interface
An interface in java is a blueprint of a class. It has static constants and abstract methods only. The
interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in the
java interface not method body. It is used to achieve fully abstraction and multiple inheritances in Java.
There are mainly three reasons to use interface.
1) It is used to achieve fully abstraction.
2) By interface, we can support the functionality of multiple inheritances.
3) It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method and public, static and
final keywords before data members. In other words, Interface fields are public, static and final by
default, and methods are public and abstract.
interface Bank {
int countryCode = 5; Demo.java
void savingsAc();
}
interface Bank {
After compiling public static final int countryCode = 5; Demo.class
public abstract void savingsAc();
}
13
Packages:
A java package is a group of similar types of classes, interfaces and sub-packages. Package in
java can be categorized in two form, built-in package and user-defined package. There are many built-in
packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Example:
A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello");
}
}
B.java
package mypack;
import pack.*;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
}
}
//output: Hello
Encapsulation
Encapsulation in java is a process of wrapping code and data together into a single unit, for example
capsule i.e. mixed of several medicines. We can create a fully encapsulated class in java by making all
the data members of the class private. Now we can use setter and getter methods to set and get the
data in it.
Advantage of Encapsulation in java:
By providing only setter or getter method, you can make the class read-only or write-only.
It provides you the control over the data. Suppose you want to set the value of id i.e. greater
than 100 only, you can write the logic inside the setter method.
Student.java
package com.school;
14
public String getName() {
return name;
}
Test.java
package com.school;
Access Modifiers
There are two types of modifiers in java: access modifiers and non-access modifiers. The access
modifiers in java specifies accessibility (scope) of a data member, method, constructor or class.
There are 4 types of java access modifiers:
1) private
2) default
3) protected
4) public
There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient
etc.
private access modifier
The private access modifier is accessible only within class. If we access these private members from
outside the class, so there is compile time error. If any class constructor is private, you cannot create the
instance of that class from outside the class.
class A {
private int data = 40;
private A() {
System.out.println("In construcotr...");
}
15
public class AccessMod {
public static void main(String args[]) {
A obj = new A(); //// Compile Time Error
System.out.println(obj.data);// Compile Time Error
obj.msg();// Compile Time Error
}
}
class A {
void msg() {
System.out.println("Hello java");
}
}
AccessMod.java
package com.college;
import com.school;
B.java
package com.college;
public class B {
protected void msg() {
System.out.println("Hello world");
}
16
}
AccessMod.java
package com.school;
import com.college.*;
AccessMod.java
package com.school;
import com.college.*;
class AccessMod {
public static void main(String args[]) {
B obj = new B();
obj.msg();
}
}
Access Modifier within class within package outside package by outside package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Exception Handling
The exception handling in java is one of the powerful mechanisms to handle the runtime errors so that
normal flow of the application can be maintained.
17
What is exception?
Def 1: Exception is an abnormal condition. In java, exception is an event that disrupts the normal flow of
the program. It is an object which is thrown at runtime.
Def 2: An exception is an event that occurs during the execution of a program and disrupts the normal
flow of the program’s instructions.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is considered as
unchecked exception. The sun Microsystems says there are three types of exceptions:
1) Checked Exception
The classes that extend 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 that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Try block
Enclose the code that might throw an exception in try block. It must be used within the method and
must be followed by either catch or finally block.
Syntax 1:
Catch block is used to handle the Exception. It must be used after the try block.
18
try{
........
........
}catch(exception_class_name reference){
........
........
}
Syntax 2:
The finally block is a block that is always executed. It is mainly used to perform some important tasks
such as closing connection, stream etc.
try{
........
........
}finally {
........
........
}
Note: finally must be followed by try or catch block.
throw
The throw keyword is used to explicitly throw an exception. We can throw either checked or unchecked
exception. The throw keyword is mainly used to throw custom exception
public class Testing {
throws
This is the keyword which gives an indication to the calling function to keep the called function under try
and catch blocks.
Example 1:
class Testing1 {
public void div(String s1, String s2) throws ArithmeticException,
NumberFormatException {
int n1 = Integer.parseInt(s1);
19
int n2 = Integer.parseInt(s2);
int n3 = n1 / n2;
System.out.println("DIVISOIN = " + n3);
}
}
class Testing {
public static void main(String[] args) {
try {
String s1 = args[0];
String s2 = args[1];
Testing1 eo = new Testing1();
eo.div(s1, s2);
} catch (ArithmeticException Ae) {
System.out.println("DONT ENTER ZERO FOR DENOMINATOR");
} catch (NumberFormatException Nfe) {
System.out.println("PASS INTEGER VALUES ONLY");
} catch (ArrayIndexOutOfBoundsException Aioobe) {
System.out.println("PASS VALUES FROM COMMAND PROMPT");
}
}
};
Example 2:
import java.io.IOException;
void p() {
try {
n();
} catch (Exception e) {
System.out.println("exception handled");
}
}
20