Java Unit-I Notes
Java Unit-I Notes
Let ‘Hari’ be a florist, but florist more specific form of shot keeper. Additionally, a shop keeper is a
human and a human is definitely a mammal. But a mammal is an animal & animal is material object.
METHOD BINDING
When the method is super class have same name that of the method in sub class, then the subclass
method overridden the super-class method. The program will find out a class to which the reference is
actually pointing and that class method will be binded.
Example
class parent
{
void print()
{
System.out.println(“From Parent”);
}
}
class child extends parent
{
void print()
{
System.out.println(“From Child”);
}
}
class Bind
{
Public static void main(String arg[])
{
child ob=new child();
ob.print();
}
}
Output: From Child
The child’s object ‘ob’ will point to child class print() method thus that method will be binded.
OVERRIDING
When the name and type of the method in a subclass is same as that of a method in its super class.
Then it is said that the method present in subclass overrides the method present in super class. Calling
an overridden method from a subclass will always point to the type of that method as defined by the
subclass, where as the type of method defined by super class is hidden.
E.g. (above ’method binding’ example)
EXCEPTIONS
Exception is a error condition that occurs in the program execution. There is an object called
‘Exception’ object that holds error information. This information includes the type and state of the
program when the error occurred.
E.g. Stack overflow, Memory error etc
SUMMARY OF OOP CONCEPTS
Everything is an object.
Computation is performed by objects communicating with each other, requesting that other objects
perform actions. Objects communicate by sending & receiving messages. A message is a request for
an action bundled with whatever arguments may be necessary to complete the task.
Each object has its own memory, which consists of other objects.
Every Object is an instance of class. A class simply represents a grouping of similar objects, such as
integers or lists.
The class is the repository for behavior associated with an object. That is all objects that are
instances of same class can perform the same actions.
Classes are organized into a singly rooted tree structure, called inheritance hierarchy.
OOP CONCEPTS
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which every
program is follows the concept of object. In other words, OOP is a way of writing programs based on
the object concept.
The object-oriented programming paradigm has the following core concepts.
Class
Object
Encapsulation
Inheritance
Polymorphism
Abstraction
Class
Class is a blue print which is containing only list of variables and methods and no memory is allocated
for them. A class is a group of objects that has common properties.
Object
Any entity that has state and behavior is known as an object.
For example a chair, pen, table, keyboard, bike, etc. It can be physical or logical.An Object can be
defined as an instance of a class.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Encapsulation
Encapsulation is the process of combining data and code into a single unit.
In OOP, every object is associated with its data and code.
In programming, data is defined as variables and code is defined as methods.
The java programming language uses the class concept to implement encapsulation.
Inheritance
Inheritance is the process of acquiring properties and behaviors from one object to another
object or one class to another class.
In inheritance, we derive a new class from the existing class. Here, the new class acquires the
properties and behaviors from the existing class.
In the inheritance concept, the class which provides properties is called as parent class and the
class which recieves the properties is called as child class.
Person
name,
designation
learn(),
walk(),
eat()
Polymorphism
Polymorphism is the process of defining same method with different implementation. That
means creating multiple methods with different behaviors.
The java uses method overloading and method overriding to implement polymorphism.
Method overloading - multiple methods with same name but different parameters.
Method overriding - multiple methods with same name and same parameters.
Abstraction
Abstraction is hiding the internal details and showing only esential functionality.
In the abstraction concept, we do not show the actual implemention to the end user, instead we
provide only esential things.
For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music system
works? etc.
JAVA BUZZWORDS(JAVA FEATURES)
Java is the most popular object-oriented programming language.
Java has many advanced features, a list of key features is known as Java Buzz Words.
The Following list of Buzz Words
Simple
Secure
Portable
Object-oriented
Robust
Architecture-neutral (or) Platform Independent
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++.
In a java programming language, many complicated features like pointers, operator overloading,
structures, unions, etc. have been removed.
One of the most useful features is the garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have pointers concept.
java provides a feature "applet" which can be embedded into a web application.
The applet in java does not allow access to other parts of the computer, which keeps away from
harmful programs like viruses and unauthorized access.
Portable
Portability is one of the core features of java .
If a program yields the same result on every machine, then that program is called portable.
Java programs are portable
This is the result of java System independence nature.
Object-oriented
Java is an object oriented programming language.
This means java programs use objects and classes.
Robust
Robust means strong.
Java programs are strong and they don’t crash easily like a C or C++ programs
There are two reasons
Java has got excellent inbuilt exception handling features. An exception is an error that occurs at
runtime. If an exception occurs, the program terminates suddenly giving rise to problems like loss
of data. Overcoming such problem is called exception handling.
Most of the C and C++ programs crash in the middle because of not allocating sufficient memory or
forgetting the memory to be freed in a program. Such problems will not occur in java because the
user need not allocate or deallocate the memory in java. Everything will be taken care of by JVM
only.
Architecture-neutral (or) Platform Independent
Java has invented to archive "write once; run anywhere, anytime, forever".
The java provides JVM (Java Virtual Machine) to archive architectural-neutral or platform-
independent.
The JVM allows the java program created using one operating system can be executed on any other
operating system.
Multi-threaded
Java supports multi-threading programming.
Which allows us to write programs that do multiple operations simultaneously.
Interpreted
Java programs are compiled to generate byte code.
This byte code can be downloaded and interpreted by the interpreter in JVM.
If we take any other language, only an interpreter or a compiler is used to execute the program.
But in java, we use both compiler and interpreter for the execution.
High performance
The problem with interpreter inside the JVM is that it is slow.
Because of Java programs used to run slow.
To overcome this problem along with the interpreter.
Java soft people have introduced JIT (Just in Time ) compiler, to enhance the speed of execution.
So now in JVM, both interpreter and JIT compiler work together to run the program.
Distributed
Information is distributed on various computers on a network.
Using Java, we can write programs, which capture information and distribute it to the client.
This is possible because Java can handle the protocols like TCP/IP and UDP.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running system
and it has a dynamic memory allocation and deallocation (objects and garbage collector).
OVERVIEW OF JAVA
Java is a object oriented programming language.
Java was created based on C and C++.
Java uses C syntax and many of the object-oriented features are taken from C++.
Before Java was invented there were other languages like COBOL, FORTRAN, C, C++, Small Talk, etc.
These languages had few disadvantages which were corrected in Java.
Java also innovated many new features to solve the fundamental problems which the previous
languages could not solve.
Java was developed by James Gosling, Patrick Naughton, Chris warth, Ed Frank and Mike Sheridon
at Sun Microsystems in the year 1991.
This language was initially called as “OAK” but was renamed as “Java” in 1995.
The primary motivation behind developing java was the need for creating a platform independent
Language (Architecture Neutral), that can be used to create a software which can be embedded in
various electronic devices such as remote controls, micro ovens etc.
The problem with C, C++ and most other languages is that, they are designed to compile on specific
targeted CPU (i.e. they are platform dependent), but java is platform Independent which can run on
a variety of CPU’s under different environments.
The secondary factor that motivated the development of java is to develop the applications that can
run on Internet. Using java we can develop the applications which can run on internet i.e. Applet. So
java is a platform Independent Language used for developing programs which are platform
Independent and can run on internet.
STRUCTURE OF JAVA PROGRAM
Structure of a Java program contains the following elements:
Documentation Section
The documentation section is an important section but optional for a Java program.
It includes basic information about a Java program. The information includes the author's name,
date of creation, version, program name, company name, and description of the program. It
improves the readability of the program. Whatever we write in the documentation section, the Java
compiler ignores the statements during the execution of the program. To write the statements in the
documentation section, we use comments.
Comments there are three types
1. Single-line Comment: It starts with a pair of forwarding slash (//).
2. Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
Example : /* It is an example of
multiline comment */
3. Documentation Comment: It starts with the delimiter (/**) and ends with */.
SAMPLE JAVA PROGRAM
/* This is First Java Program */
Class sample
{
public static void main(String args[])
{
System.out.println(“Hello Java Programming”);
}
}
Parameters used in First Java Program
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
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 the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static method.
The main method is executed by the JVM, so it doesn't require to create an object to invoke the main
method. So it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program execution
String[] args is used for command line argument.
System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class.
How to Compile and Run the Java Program
To Compile : javac Sample.java [ program name]
To Run : java Sample
Output : Hello Java Programming
EXECUTION PROCESS OF JAVA PROGRAM
WHAT IS JVM
Java Virtual Machine is the heart of entire java program execution process. It is responsible for taking
the .class file and converting each byte code instruction into the machine language instruction that can
be executed by the microprocessor.
DATA TYPES IN JAVA
Java programming language has a rich set of data types. The data type is a category of data stored in
variables. In java, data types are classified into two types and they are as follows.
Primitive Data Types
Non-primitive Data Types
-9223372036854775808 to
long 8 bytes 0L
+9223372036854775807
Float Data Types
Float data types are represent numbers with decimal point.
Minimum and Maximum
Data Type Memory Size Default Value
values
-3.4e38 to -1.4e-45 and 1.4e-45
float 4 byte 0.0f
to 3.4e38
-1.8e308 to -4.9e-324 and 4.9e-
double 8 bytes 0.0d
324 to 1.8e308
Note: Float data type can represent up to 7 digits accurately after decimal point.
Double data type can represent up to 15 digits accurately after decimal point.
Character Data Type
Character data type are represents a single character like a, P, &, *,..etc.
Minimum and Maximum
Data Type Memory Size Default Value
values
class Employee
{
int empid=500;
void emp1()
{
empid++;
System.out.println("Employee id:"+empid);
}
}
class Sample
{
public static void main(String args[])
{
Employee e1=new Employee();
e1.emp1();
e1.emp1();
e1.emp1();
Employee e2=new Employee();
e2.emp1();
e2.emp1();
e2.emp1();
}
}
Output:
Employee id:501
Employee id:502
Employee id:503
Employee id:501
Employee id:502
Employee id:503
Example2 With Static variable
class Employee
{
static int empid=500;
static void emp1()
{
empid++;
System.out.println("Employee id:"+empid);
}
}
class Sample
{
public static void main(String args[])
{
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
Employee.emp1();
}
}
Output:
Employee id:501
Employee id:502
Employee id:503
Employee id:504
Employee id:505
Employee id:506
ARRAYS
An array is a collection of similar data values with a single name.
An array can also be defined as, a special type of variable that holds multiple values of the same
data type at a time.
In java, arrays are objects and they are created dynamically using new operator.
Every array in java is organized using index values.
The index value of an array starts with '0' and ends with 'zise-1'.
We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
One Dimensional Array
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
Operator Description
2. Logical OR ( || ) : Logical OR is denoted by double pipe characters (||). it is used to check the
combinations of more than one conditions. if any one condition true the complete condition becomes
true.
Truth table of Logical OR
Condition1 Condition2 Condition1 && Condition2
True True True
True False True
False True True
False False False
3. Logician NOT (!): Logical NOT is denoted by exclamatory characters (!), it is used to check the
opposite result of any given test condition. i.e, it makes a true condition false and false condition true.
Truth table of Logical NOT
Condition1 !Condition2
True False
False True
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
<< Left Shift
>> Right Shift
1. Bitwise AND (&):
Bitwise AND operator is represented by a single ampersand sign (&).
Two integer expressions are written on each side of the (&) operator.
if any one condition false ( 0 ) the complete condition becomes false ( 0 ).
0 0 0
0 1 0
1 0 0
1 1 1
0 0 0
0 1 1
1 0 1
1 1 1
Example : int x = 10;
int y = 20;
x|y=?
x = 0000 1010
y = 0000 1011
x | y = 0000 1011 = 11
3. Bitwise Exclusive OR :
The XOR operator is denoted by a carrot (^) symbol.
It takes two values and returns true if they are different; otherwise returns false.
In binary, the true is represented by 1 and false is represented by 0.
Truth table of Bitwise XOR
Condition1 Condition2 Condition1 ^ Condition2
0 0 0
0 1 1
1 0 1
1 1 0
Example
ab+
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
+ab
CONTROL STATEMENTS
In java, the default execution flow of a program is a sequential order.
But the sequential order of execution flow may not be suitable for all situations.
Sometimes, we may want to jump from line to another line, we may want to skip a part of the
program, or sometimes we may want to execute a part of the program again and again.
To solve this problem, java provides control statements.
Types of Control Statements
If only one statement is being repeated, there is no need for the curly braces.
In for-statement, the execution begins with the initialization statement. After the initialization
statement, it executes Condition. If the condition is evaluated to true, then the block of statements
executed otherwise it terminates the for-statement. After the block of statements execution,
the modification statement gets executed, followed by condition again.
Example
public class ForTest
{
public static void main(String[] args)
{
for(int i = 0; i < 10; i++)
{
System.out.println("i = " + i);
}
System.out.println("Statement after for!");
}
}
3. Jump Statements
The java programming language supports jump statements that used to transfer execution control
from one line to another line.
The java programming language provides the following jump statements.
1. break statement
2. continue statement
break
When a break statement is encountered inside a loop, the loop is terminated and program control
resumes at the next statement following the loop.
Example
class BreakStatement
{
public static void main(String args[] )
{
int i;
i=1;
while(true)
{
if(i >10)
break;
System.out.print(i+" ");
i++;
}
}
}
Continue
This command skips the whole body of the loop and executes the loop with the next iteration. On
finding continue command, control leaves the rest of the statements in the loop and goes back to the
top of the loop to execute it with the next iteration (value).
Example
/* Print Number from 1 to 10 Except 5 */
class NumberExcept
{
public static void main(String args[] )
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
continue;
System.out.print(i +" ");
}
}
}
INTRODUCING CLASSES AND METHODS
classes usually consist of two things: instance variables and methods.
All the objects of a class have the same properties and behaviors that were defined in the class.
Example
Here is a class called Box that defines three instance variables: width, height, and depth.
class Box
{
double width;
double height;
double depth;
void volume()
{
………………….
}
}
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the class is said to be
instantiated.
All the objects that are created using a single class have the same properties and methods.
Syntax
ClassName objectName = new ClassName( );
The objectName must begin with an alphabet, and a Lower-case letter is preferred.
Example
To actually create a Box object, you will use a statement like the following:
Box mybox = new Box();
The new operator dynamically allocates memory for an object.
Example
class Box
{
double width;
double height;
double depth;
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
METHODS
A method is a block of statements under a name that gets executes only when it is called.
Every method is used to perform a specific task. The major advantage of methods is code re-
Example
class Animal
{
String name;
void show()
{
System.out.println(“Animal name is:"+name);
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Barking");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.name="DOG";
d.show();
d.bark();
}
}
2. Multilevel inheritances in Java
When there is a chain of inheritance, it is known as multilevel inheritance.
In Multilevel inheritances there exists single base class, single derived class and multiple
intermediate base classes.
Example
In the example, BabyDog class inherits the Dog class which again inherits the Animal class, so there is
a multilevel inheritance.
class Animal
{
String name;
void show()
{
System.out.println("Animal Name is"+name);
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Mother Dog Barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("Baby Dog weeping");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.name="MotherDog";
d.show();
d.bark();
d.weep();
}
}
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass.
In the below image, class A serves as a base class for the derived class B, C and D.
Example
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class Cat extends Animal
{
void meow()
{
System.out.println("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
4. Multiple inheritance
In multiple inheritance there exist multiple classes and singel derived class.
The concept of multiple inheritance is not supported in java through concept of classes but it can be
supported through the concept of interface.
5. Hybrid inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple
inheritances with classes, hybrid inheritance is also not possible with classes. In Java, we can achieve
hybrid inheritance only through Interfaces.
ACCESS CONTROL(MEMBER ACCESS)
In Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modifier used
with the element.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
1. Default Access Modifier
When no access modifier is specified for a class, method, or data member – It is said to be having
the default access modifier by default.
The default modifier is accessible only within package.
It cannot be accessed from outside the package.
It provides more accessibility than private. But, it is more restrictive than protected, and public.
Example
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
2. private
The private access modifier is accessible only within the class.
The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the class in which
they are declared.
Any other class of the same package will not be able to access these members.
Top-level classes or interfaces can not be declared as private because private means “only visible
within the enclosing class”.
Example
In this example, we have created two classes A and Simple.
A class contains private data member and private method.
We are accessing these private members from outside the class, so there is a compile-time error.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
4. public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
The public access modifier is specified using the keyword public.
Example
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Table: class member access
Let's understand the access modifiers in Java by a simple table.
Private YES NO NO NO
class ThisDemo2
{
public static void main(String args[])
{
Employee e1 = new Employee(111,"Harry");
e1.show();
}
}
Example2
import java.util.*;
abstract class Shape
{
int length, breadth, radius;
Scanner input = new Scanner(System.in);
abstract void printArea();
}
class Rectangle extends Shape
{
void printArea()
{
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}
class Triangle extends Shape
{
void printArea()
{
System.out.println("\n*** Finding the Area of Triangle ***");
System.out.print("Enter Base And Height: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Triangle is: " + (length * breadth) / 2);
}
}
class Cricle extends Shape
{
void printArea()
{
System.out.println("\n*** Finding the Area of Cricle ***");
System.out.print("Enter Radius: ");
radius = input.nextInt();
System.out.println("The area of Cricle is: " + 3.14f * radius * radius);
}
}
public class AbstractClassExample
{
public static void main(String[] args)
{
Rectangle rec = new Rectangle();
rec.printArea();
Triangle tri = new Triangle();
tri.printArea();
Cricle cri = new Cricle();
cri.printArea();
}
}
OBJECT CLASS
In java, the Object class is the super most class of any class hierarchy. The Object class in the java
programming language is present inside the java.lang package.
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't know. Because
it is the superclass of all other classes in java, it can refer to any type of object.
Return
Method Description
Value
hashCode() returns the hashcode number for object being used. int
notifyAll() wakes up all the threads, waiting on invoking object's monitor. void
wait() causes the current thread to wait, until another thread notifies. void
wait(long,int) causes the current thread to wait for the specified milliseconds and void
nanoseconds, until another thread notifies.