Unit - I
Unit - I
System)
Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by
providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Apart from these concepts, there are some other terms which are used in Object-
Oriented design:
Coupling
Cohesion
Association
Aggregation
Composition
OOPs (Object-Oriented Programming System)
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.
Class :- Collection of objects is called class. It is a logical entity. A class can
also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Inheritance :- When one object acquires all the properties and behaviors of a
parent object, it is known as inheritance. It provides code reusability. It is
used to achieve runtime polymorphism.
Polymorphism :- If one task is performed in different ways, it is known as
polymorphism. For example: to convince the customer differently, to draw
something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve
polymorphism.
Another example can be to speak something; for example, a cat speaks
meow, dog barks woof, etc.
Cont.…
Abstraction :- Hiding internal details and showing functionality is known as
abstraction. For example phone call, we don't know the internal
processing. In Java, we use abstract class and interface to achieve
abstraction.
Encapsulation :- Binding (or wrapping) code and data together into a single
unit are known as encapsulation. For example, a capsule, it is wrapped with
different medicines. A java class is the example of encapsulation. Java bean
is the fully encapsulated class because all the data members are private
here.
Coupling :- It refers to the knowledge or information or dependency of
another class. It arises when classes are aware of each other. If a class has
the details information of another class, there is strong coupling. In Java,
we use private, protected, and public modifiers to display the visibility level
of a class, method, and field. You can use interfaces for the weaker
coupling because there is no concrete implementation.
Cont.…
Cohesion :- It refers to the level of a component which performs a single well-defined task. A single
well-defined task is done by a highly cohesive method. The weakly cohesive method will split the task
into separate parts. The java.io package is a highly cohesive package because it has I/O related classes
and interface. However, the java.util package is a weakly cohesive package because it has unrelated
classes and interfaces.
Association :-It represents the relationship between the objects. Here, one object can be associated
with one object or many objects. There can be four types of association between the objects:
One to One
One to Many
Many to One, and
Many to Many
Let's understand the relationship with real-time examples. For example, One country can have one prime
minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can
have one prime minister (many to one), and many ministers can have many departments (many to many).
Association can be undirectional or bidirectional.
Aggregation :- It is a way to achieve Association. Aggregation represents the relationship where one
object contains other objects as a part of its state. It represents the weak relationship between objects.
It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is
another way to reuse objects.
Composition :- It is also a way to achieve Association. The composition represents the relationship
where one object contains other objects as a part of its state. There is a strong relationship between the
containing object and the dependent object. It is the state where containing objects do not have an
independent existence. If you delete the parent object, all the child objects will be deleted
automatically.
Brief Overview of
JAVA
What is java?
Java is a computer programming language that is concurrent,
class-based, object oriented.
It is intended to let application developers “write once run any
where" (WORA).
Java applications are typically compiled to bytecode (class file)
that can run on any Java virtual machine (JVM) regardless of
computer architecture.
Java is, as of 2014, one of the most popular programming
languages in use, particularly for client-server web
applications.
Java is the Internet programming language.
Java's History
• Java was originally developed by James Gosling at
Sun Microsystems (which has since merged into
Oracle Corporation).
• Originally named OAK in 1991 First non
commercial version in 1994
• Renamed and modified to Java in 1995 and released
as a core component of Sun Microsystems' Java
platform.
• First Commercial version in late 1995
• Hot Java
Portable: Java is portable because it facilitates you to carry the Java bytecode
to any platform. It doesn't require any implementation.
a=10; // valid
Multidimensional Array
Output
10
20
30
Operators
Operator is a special symbol that tells the compiler to perform specific
mathematical or logical Operation. Java supports following lists of operators.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Ternary or Conditional Operators
Classes in Java
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be
physical.
class Student{
int id;
String name; Output:
} 101 Sonoo
class TestStudent3{
public static void main(String args[]){ 102 Amit
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name=“ABC";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
Constructor in Java
In Java, a constructor is a block of codes similar to the method. It is called
when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one
constructor is called.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for
garbage collection
3) By anonymous object:
new Employee();
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:
protected void finalize(){}
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.
public static void gc(){}
Example of garbage collection
public class TestGarbage
{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage s1=new TestGarbage();
TestGarbage s2=new TestGarbage();
s1=null;
s2=null;
System.gc();
}
}
Output:
Important points
In the inheritance the class which is give data members and
methods is known as base or super or parent class.
The class which is taking the data members and methods is
known as sub or derived or child class.
The data members and methods of a class are known as features.
The concept of inheritance is also known as re-usability or
extendable classes or sub classing or derivation.
Terms used in Inheritance
Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields
and methods of the existing class when you create a new class. You can use the same fields and methods
already defined in the previous class.
The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
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.
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
Advantage of inheritance
If we develop any application using concept of Inheritance than that
application have following advantages,
Application development time is less.
Application take less memory.
Application execution time is less.
Application performance is enhance (improved).
Redundancy (repetition) of the code is reduced or minimized so that we
get consistence results and less storage cost.
Types of Inheritance
Based on number of ways inheriting the feature of base class into
derived class we have five types of inheritance; they are:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance
Single inheritance
In single inheritance there exists single base class and
single derived class.
class Faculty
{
float salary=30000;
}
class Science extends Faculty
{
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous
is:"+obj.bonous);
}
}
Output:
Salary is: 30000.0
Bonous is: 2000.0
Multilevel inheritances in Java
In Multilevel inheritances there exists single base class, single derived class and
multiple intermediate base classes.
Single base class + single derived class + multiple intermediate base classes.
class Animal{
void eat(){
System.out.println("eating...");} Output:
} weeping...
class Dog extends Animal{ barking...
void bark(){ eating...
System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){
System.out.println("weeping...");}
}
class TestInheritance{
public static void main(String args[])
{
BabyDog d = new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Hierarchical Inheritance
When more than one classes inherit a same class then this is called
hierarchical inheritance. For example class B, C and D extends a same
class A. when a class has more than one child classes (sub classes) or in
other words more than one child classes have the same parent class
then this type of inheritance is known as hierarchical inheritance.
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();
Dog d = new Dog();
d.bark();
d.eat();
}
}
Output:
meowing...
eating...
Hybrid Inheritance
interface Person
{
void run();
}
class Employee implements Person
{
public void run()
{
System.out.println("Run fast");
}
}
Output:
Hello
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
There properties can be reused commonly in a There properties commonly usable in any application of
2
specific application. java environment.
5 Which may contain either variable or constants. Which should contains only constants.
The default access specifier of abstract class methods There default access specifier of interface method are
6
are default. public.
These class properties can be reused in other class These properties can be reused in any other class using
7
using extend keyword. implements keyword.
8 Inside abstract class we can take constructor. Inside interface we can not take any constructor.
There are no any restriction for abstract class For the interface variable can not declare variable as
10
variable. private, protected, transient, volatile.
Exception handling
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
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of
the program. It is an object which is thrown at runtime.
What is Exception Handling
Exception Handling is a mechanism to handle runtime errors such
as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
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
1) Checked Exception
The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions e.g.
IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e){
System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
java.lang.ArithmeticException:/ by zero
rest of the code...
Finally block
Java finally block is a block that is used to execute
important code such as closing connection, stream etc.
Java finally block is always executed whether exception
is handled or not.
Java finally block follows try or catch block.
Why use java finally
Finally block in java can be used to put "cleanup" code
such as closing a file, closing connection etc.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
OUTPUT
5
finally block is always executed
Multithreading
Multithreading in Java is a process of executing multiple threads
simultaneously.
A thread is a lightweight sub-process, the smallest unit of
processing. Multiprocessing and multithreading, both are used to
achieve multitasking.
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.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.
Thread class
Threads allows a program to operate more efficiently by doing multiple
things at the same time.
Threads can be used to perform complicated tasks in the background
without interrupting the main program.
Creating a Thread
There are two ways to create a thread.
By extending Thread class
By implementing Runnable interface.
Extend Syntax
public class Main extends Thread
{
public void run() {
System.out.println("This code is running in a thread");
}
Constructors of Thread class:
1. Thread(): This allocates a new Thread object.
2. Thread(Runnable target): This allocates a new Thread object.
3. Thread(Runnable target, String name): This allocates a new Thread object.
4. Thread(String name): This constructs allocates a new Thread object.
5. Thread(ThreadGroup group, Runnable target): This allocates a new Thread
object.
6. Thread(ThreadGroup group, Runnable target, String name): This allocates
a new Thread object so that it has target as its run object, has the specified name
as its name, and belongs to the thread group referred to by group.
7. Thread(ThreadGroup group, Runnable target, String name, long
stackSize): This allocates a new Thread object so that it has target as its run
object, has the specified name as its name, belongs to the thread group referred
to by group, and has the specified stack size.
8. Thread(ThreadGroup group, String name): This allocates a new Thread
object.
Methods of Thread class
run()
Which contains the main business logic that can be executed by multiple threads
simultaneously in every user defined thread class run method should be
overridden.
public Class_Name extends Thread {
public void run() {
..... .....
}
}
start()
Used to convert ready state thread to running state.
Thread t=new Thread();
t.start();
stop()
This method is used to convert running state thread to dead state.
Thread t=new Thread();
t.stop();
class Demo extends Thread{
public void run(){
System.out.println("thread is running...");
-----
------
}
public static void main(String args[]){
Demo t1=new Demo();
t1.start();
t1.stop();
}
}
Output:
thread is running...
Runnable Interface
Runnable is one of the predefined interface in
java.lang package, which is containing only one
method and whose prototype is " Public abstract void
run "
The run() method of thread class defined with null
body and run() method of Runnable interface belongs
to abstract. Industry is highly recommended to
override abstract run() method of Runnable interface
but not recommended to override null body run()
method of thread class.
Class Demo implements Runnable{
public void run()
{
System.out.println("thread is running...");
}
thread is running...
User Define Exception
If any exception is design by the user known as user defined
or Custom Exception. Custom Exception is created by user.
Rules to design user defined Exception
Create a package with valid user defined name.
Create any user defined class.
Make that user defined class as derived class of Exception or
RuntimeException class.
Declare parametrized constructor with string variable.
call super class constructor by passing string variable within
the derived class constructor.
Save the program with public class name.java
class UserDefine extends Exception
{
UserDefine(String s)
{
super(s);
} OUTPUT:
} Entered input is incorrect
Class Input
{
void method() throws UserDefine
{
throw new UserDefine (“Entered input is incorrect”):
}
}
public class User
{
public static void main(String[] args)
{
try{
new Input().method();
}
catch(UserDefine w)
{
System.out.println(w.getMessage());
}
}
}
Inter-thread communication
Inter-thread communication or Co-operation is all
about allowing synchronized threads to communicate with
each other.
Cooperation (Inter-thread communication) is a
mechanism in which a thread is paused running in its
critical section and another thread is allowed to enter (or
lock) in the same critical section to be executed. It is
implemented by following methods of Object class:
wait()
Causes current thread to release the lock and wait until
either another thread invokes the notify() method or the
notifyAll() method for this object
notify()
Wakes up a single thread that is waiting on this object's
monitor. If any threads are waiting on this object, one of
them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation.
public final void notify()
notifyAll()
Wakes up all threads that are waiting on this object's
monitor.
public final void notifyAll()
class Pen{} Thread t2 = new Thread() {
class Paper{} public void run()
{
public class Write { synchronized(pr)
{
public static void main(String[] args) System.out.println("Thread2 is holding Paper");
{ try {
final Pen pn =new Pen(); Thread.sleep(1000);
final Paper pr =new Paper(); }
catch(InterruptedException e){
Thread t1 = new Thread() { // do something
public void run() }
{ synchronized(pn)
synchronized(pn) {
{
System.out.println("requesting for Pen");
System.out.println("Thread1 is holding Pen");
}
try{
}
Thread.sleep(1000);
}
}
};
catch(InterruptedException e){
// do something
t1.start();
}
t2.start();
synchronized(pr)
}
{
}
System.out.println("Requesting for Paper");
}
OUTPUT:
}
}
}; Thread1 is holding Pen
Thread2 is holding Paper
Thank You