[go: up one dir, main page]

0% found this document useful (0 votes)
64 views167 pages

Sem 3 Java 1 To 5

The document outlines a syllabus for a course on Object-Oriented Programming (OOP) and Java, covering key concepts such as classes, inheritance, interfaces, packages, exception handling, threads, and networking. It details the differences between procedural and object-oriented programming paradigms, emphasizing the importance of data encapsulation, abstraction, and the use of classes and objects. Additionally, it provides examples of Java syntax and methods, illustrating the practical application of these concepts in programming.

Uploaded by

kanishqchezian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views167 pages

Sem 3 Java 1 To 5

The document outlines a syllabus for a course on Object-Oriented Programming (OOP) and Java, covering key concepts such as classes, inheritance, interfaces, packages, exception handling, threads, and networking. It details the differences between procedural and object-oriented programming paradigms, emphasizing the importance of data encapsulation, abstraction, and the use of classes and objects. Additionally, it provides examples of Java syntax and methods, illustrating the practical application of these concepts in programming.

Uploaded by

kanishqchezian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 167

Syllabus –Unit 1 Unit 2- CLASSES, INHERITANCE AND INTERFACES

⚫INTRODUCTION TO OOPS AND JAVA : ⚫Class and objects:

⚫ Object Oriented Paradigm ⚫Defining class , Creating objects


⚫ Differences between Procedure Oriented ⚫Accessing class members , Constructors
Programming and Object Oriented Programming
⚫Method overloading , Simple programs
⚫ Basic concepts of Object Oriented Programming
⚫ Benefits of OOP and Applications of OOP ⚫Inheritance:

⚫ Java: Features ⚫Single Inheritance , Multilevel Inheritance ,Hierarchical Inheritance

⚫ Java Development Environment ⚫Overriding methods ,Final variables and methods


⚫ Simple Java program ⚫Visibility Control-Simple programs.
⚫ Comments, Data types ⚫Interfaces:
⚫ Variables, Operators
⚫Defining interface – Extending interface
⚫ Decision making Branching and Looping
⚫Implementing Interface.
⚫ Arrays and Strings

Unit -3 PACKAGES AND MANAGING EXCEPTIONS Unit-4 THREADS AND SWINGS IN JAVA


Threads:
Packages: ⚫ Creating Threads
⚫ Java API Packages ⚫ Extending the Thread Class
⚫ System Packages ⚫ Stopping and Blocking Thread
⚫ Naming Conventions ⚫ Life Cycle of a Thread
⚫ Creating & Accessing a Package ⚫ Thread Exceptions


Thread Priority
Adding Class to a Package. ⚫ Synchronization
⚫ Managing Exceptions: ⚫ Basic swing components:
⚫ Types of errors ⚫ JLabel, JTextField, JTextArea, JPasswordField, JButton,
⚫ Handling Exception JCheckBox, JRadioButton, JList, JComboBox, JPanel,User
Interface Design
⚫ multiple catch , Finally Statement ⚫ Event Handling:
⚫ User defined exceptions. ⚫ Action events, Key events, Item events.
Unit -5 NETWORKING, DATABASE CONNECTIVITY
What is Java?
AND COLLECTIONS ⚫ Java:
⚫NETWORKING : ⚫ Java is a general-purpose, class-based, object-oriented
⚫Establishing a simple server programming language, which works on different
operating systems such as Windows, Mac, and Linux.
⚫Establishing a simple client/server interaction with stream
⚫ Can use Java to develop:
socket and datagram socket
• Desktop applications
⚫DATABASE CONNECTIVITY • Web applications
⚫JDBC: JDBC Drivers • Mobile applications (especially Android apps)
⚫Seven steps to connect JDBC • Web and application servers
• Big data processing
⚫COLLECTIONS
• Embedded systems
⚫Overview of Interfaces and classes. ⚫ And much more

Paradigm
•Paradigm can also be termed as method to solve some problem or
do some task.
•Programming paradigm is an approach to solve problem using
some programming language.

• A programming paradigm is a style, or “way,” of programming.


• The term Programming paradigm means the methodology for
writing program codes
• In general, two paradigms are used to construct a program.
• These two ways are: 7
1. a process-oriented model
2. an object-oriented model
Imperative programming Imperative programming
paradigm paradigm
⚫ It is one of the oldest programming paradigm. ⚫ Advantages
⚫ It features close relation to machine architecture. ⚫ Very simple to implement
⚫ It is based on Von Neumann architecture. ⚫ It contains loops, variables etc

⚫ It works by changing the program state through ⚫ Disadvantages


assignment statements. ⚫ Complex problem cannot be solved
⚫ It performs step by step task by changing state. ⚫ Less efficient and less productive

⚫ The main focus is on how to achieve the goal. ⚫ Parallel programming is not possible

⚫ The paradigm consist of several statements and after


execution of all the result is stored.

Declarative programming paradigm


⚫ It is divided as Logic, Functional, Database. Procedural programming paradigm
⚫ It just declares the result we want rather how it has be
⚫ This paradigm emphasizes on procedure in terms of
produced.
⚫ This is the only difference between imperative (how to under lying machine model.
⚫ It has the ability to reuse the code and it was boon at
do) and declarative (what to do) programming
paradigms.
that time when it was in use because of its reusability.
⚫ Getting into deeper It will focus logic, functional and
database.
Object oriented programming Object- Oriented Paradigm
• Object- Oriented Paradigm is a way to solving the problem by
⚫ The program is written as a collection of classes and
object which are meant for communication. creating objects.
⚫ The smallest and basic entity is object and all kind of
computation is performed on the objects only. • OOP allows decomposition of a problem into a number of
⚫ More emphasis is on data rather than procedure. entities called objects and then builds data and functions
around these objects.
⚫ Advantages:
⚫ Data security 14
⚫ Inheritance • The data of an object can be accessed only by the function
⚫ Code reusability associated with that object.
⚫ Flexible and abstraction is also present

• However, functions of one object can access the functions of


other objects

Object- Oriented Paradigm Procedural Oriented Programming Object Oriented Programming

•OOP treats data as a critical element in the program Program is divided into small parts called functions.
Follows top-down approach.
Program is divided into small parts called objects.

development and does not allow it to flow freely around the There is no access specifier in
Follows bottom-up approach.

systems.
OOP have access specifiers like private, public, protected etc.
POP.
Adding new data and function is easy. Easy to maintain and extend as
new objects can be easily added without modifying the other objects
Adding new data and function is not easy.
Large Programs developed using this approach are difficult to maintain,
•It ties data more closely to the functions that operate on it, debug and extend. OOP provides data hiding so it is more secure. The data of one object
can be accessed by the associated functions of that object only. Other
and protects it from accidental modification from outside POP does not have any proper way for hiding data so it is less secure. functions are not allowed to access that data. ie data is hidden from the
Allows data to move freely from one function to another without any outside world
functions. security. This makes to modify the value of global data by any function.
Overloading is not possible in POP. Overloading is possible in OOP

In POP, function is more important than data. Emphasis is on the In OOP, data is more important than function. Emphasis on data rather
functionality of the Software rather than the data used by the function than the functions or the procedures

POP is based on unreal world. Data and associated functions are loosely OOP is based on real world. Models the real world very well by binding
related. the data and associated functions together under a single unit 11
Object-Oriented Programming (OOP) is an approach that provides a way of
modularizing programs by creating partitioned memory area for both data and
functions that can be used as templates for creating copies of such modules on Features of object-oriented programming:
demand.
•Emphasis is on data rather than procedure.
•Programs are divided into what are known as objects.
•Data structures are designed such that they characterize the objects.
•Data is hidden and cannot be accessed by external functions.
•Objects may communicate with each other through functions.
•New data and functions can be easily added whenever necessary.
•Follows bottom-up approach in program design

Basic concepts of OOP-10 marks

Object
Class
Data Abstraction
Encapsulation
Inheritance
Polymorphism
Dynamic Binding
19
Message Passing
Object:
•Objects are basic run time entity.
Object
•Any entity that has state and behavior is known as an object. •Object is an real world entity that has state, behavior and
•They may represent a person, a place, a bank account, a table of data or any identity.
item that the program has to handle. •State :
•It is represented by attributes of an object.
•For example: •It also reflects the properties of an object.
•a chair, pen, table, keyboard, bike, etc. •Behavior :
•It can be physical or logical. •It is represented by methods of an object.
•It also reflects the response of an object with other objects.
•Identity :
• It gives a unique name to an object and enables one object to
interact with other objects.

Object
•An Object can be defined as an instance of a class.
•An object contains an address and takes up some space
in memory.
•Objects can communicate without knowing the details
of each other's data or code.
•The only necessary thing is the type of message
accepted and the type of response returned by the 2
4
objects.
Object concept in programming:

• Any programming problem is analyzed based on


objects and how they communicate amongst
themselves.
•The objects interact with each other by sending
messages to one another when a program is
executed.
For Example:
‘customer’ and ‘account’ are two objects that
may send a message to the account object
requesting for the balance.
•Each object contains code and data to
manipulate the data.
•Objects can even interact without knowing
the details of each other’s code or data.

Class Class- Example


⚫ Collection of objects is called class. ⚫ A class called “Expensive Cars”
⚫ It is a logical entity. ⚫ it could have objects like
⚫ A class can also be defined as a blueprint or ⚫ Mercedes,
prototype from which objects are created. ⚫ BMW,
⚫ Class doesn't consume any space. ⚫ Toyota, etc.
⚫ Classes being passive do not communicate with each
⚫ Data or Its properties can be price or speed of these cars.
other but are used to instantiate objects that interact
with each other. ⚫ Methods may be performed with these cars are driving,
⚫ It represents the set of properties or methods that are reverse, braking etc.
common to all objects of one type.
Class Object
•The collection of objects of similar types is termed as a class. ⚫ Object is a real world entity,
For Example, ⚫ For example:
apple, orange, and mango are the objects of the class Fruit. ⚫ chair, car, pen, mobile, laptop etc.
⚫ object is an entity that has state and behavior.
•The entire set of code and data of an object can be made user-defined data type using
the concept of the class.
• A class is a ‘data-type’ and an object as a ‘variable’ of that type. ⚫ Here, state means data and behavior means
• Any number of objects can be created after a class is created. functionality.
•Characteristics of an object are represented in a class as Properties.
⚫ Object is a runtime entity, it is created at runtime.
•The actions that can be performed by objects become functions of the class and is ⚫ Object is an instance of a class.
referred to as Methods. ⚫ All the members of the class can be accessed through
object.
18 ⚫ Student s1 = new Student()

Class Sample Program


⚫ In java , class is a group of similar objects.
⚫ It can have fields, methods, constructors etc.
⚫ Example Using class and objects
⚫ public class Student
⚫ {
⚫ int id; //field or data member
⚫ String name; //field or data member
⚫ }
Example

⚫ public class Student OUTPUT
⚫ {
⚫ int id; //data member (also instance variable)
⚫ String name; //data member(also instance variable)
⚫ public static void main(string[] args)
⚫ {
⚫ Student s1 = new Student();
//creating an object of Student
⚫ s1.id = 1;
⚫ s1.name =“Soniya”;
⚫ System.out.println(“Id=”+s1.id);
⚫ System.out.println(“Name=”+s1.name);
⚫ }
⚫ }

Example 2: Having Main() in another class




public class Student
{
Output
⚫ public int id;
⚫ public String name;
⚫ }
⚫ class TestStudent
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ Student s1 = new Student();
⚫ s1.id = 1;
⚫ s1.name = "Soniya ";
⚫ System.out.println(“ID=”+s1.id);
⚫ System.out.println(“Name=”+s1.name);
⚫ }
⚫ }
Create a Method
Methods
⚫ A method is a block of code which only runs when it ⚫ A method is defined with the name of the method,
is called. followed by parentheses ().
⚫ Java provides some pre-defined methods, which you
⚫ You can pass data, known as parameters, into a already are familiar with, such as main(), but you can
method. also create your own methods to perform certain
actions.
⚫ Methods are used to perform certain actions, and they
are also known as functions.

Call a Method
Method Syntax ⚫ To call (execute) a method, write the method's name
followed by two parentheses () and a semicolon;
Example
⚫ public class Student
⚫ { Data Abstraction
⚫ static void MyMethod() ⚫ Data abstraction is the process of hiding certain details and showing
{ only essential information to the user.
⚫ System.out.println("Actions speak louder than words");
⚫ Abstraction can be achieved with either abstract classes or interfaces
⚫ }
public static void main(string[] args) ⚫ The abstract keyword is a non-access modifier, used for classes and

methods:
{
⚫ MyMethod(); ⚫ Abstract class: is a restricted class that cannot be used to create objects
⚫ MyMethod(); (to access it, it must be inherited from another class).

⚫ MyMethod(); ⚫ Abstract method: can only be used in an abstract class, and it does not
⚫ } have a body. The body is provided by the subclass (inherited from).
⚫ } ⚫ An abstract class can have both abstract and regular methods:

Example
⚫ For Example:
⚫ while driving a car, you do not have to be concerned
with its internal working.(hiding)
⚫ Here you just need to concern about parts like steering
wheel, Gears, accelerator, etc.(essential features)
Example program
⚫ // Abstract class

Encapsulation
abstract class Animal
⚫ {
⚫ // Abstract method (does not have a body)
⚫ public abstract void animalSound();

⚫ The wrapping up of the data and methods into the


⚫ // Regular method
⚫ public void sleep() {
⚫ System.out.println("Zzz");

⚫ }
}
single unit is known as encapsulation.
⚫ // Subclass (inherit from Animal) ⚫ The data is accessible only to those methods, which
⚫ class Pig extends Animal


{ are wrapped in the class, and not to the outside world.
⚫ This insulation of data from the direct access of the
public void animalSound() {
⚫ // The body of animalSound() is provided here
⚫ System.out.println("The pig says: wee wee");

⚫ }
}
program is called data hiding.


class Main {
public static void main(String[] args)
⚫ Encapsulation of the object makes it possible for the


{
Pig myPig = new Pig(); // Create a Pig object objects to be treated like ‘black boxes’ that perform a


myPig.animalSound(); // calling the method using object
myPig.sleep(); // calling the method using object specific task without any concern for internal

implementation.
}
⚫ }

Encapsulation
⚫ The meaning of Encapsulation, is to make sure that
"sensitive" data is hidden from users.
Why Encapsulation?
Example
⚫ Better control of class attributes and methods ⚫ public class Person // class creation
⚫ {
⚫ Class attributes can be made read-only (if you only use the ⚫ private String name; // data member declaration-private = restricted access
⚫ // Getter (using get method)
get method), or write-only (if you only use the set method) ⚫ public String getName()
⚫ Flexible: the programmer can change one part of the code ⚫ {
⚫ return name;
without affecting other parts ⚫ }
⚫ Increased security of data.
⚫ // Setter (using set method)
⚫ Data Hiding: ⚫ public void setName(String newName)
⚫ The user will have no idea about the inner implementation of ⚫ {
⚫ this.name = newName;
the class. ⚫ }
⚫ It will not be visible to the user that how the class is stored ⚫ }
values in the variables. ⚫ Note: this keyword is a reference variable.

Sample Program
⚫ public class Main //main class declaration
⚫ {
⚫ public static void main(String[] args)
⚫ { Using class and objects
⚫ Person myObj = new Person(); //object creation
⚫ myObj.setName("John"); //set method
⚫ System.out.println(myObj.getName()); // get method
⚫ }
⚫ }
⚫ Output:
⚫ John
Example
⚫ public class Student
⚫ { OUTPUT
⚫ int id; //data member (also instance variable)
⚫ String name; //data member(also instance variable)
⚫ public static void main(string[] args)
⚫ {
⚫ Student s1 = new Student();
//creating an object of Student
⚫ s1.id = 1;
⚫ s1.name =“Soniya”;
⚫ System.out.println(“Id=”+s1.id);
⚫ System.out.println(“Name=”+s1.name);
⚫ }
⚫ }

Example 2: Having Main() in another class




public class Student
{
Output
⚫ public int id;
⚫ public String name;
⚫ }
⚫ class TestStudent
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ Student s1 = new Student();
⚫ s1.id = 1;
⚫ s1.name = "Soniya ";
⚫ System.out.println(“ID=”+s1.id);
⚫ System.out.println(“Name=”+s1.name);
⚫ }
⚫ }
Inheritance
⚫ Inheritance (Derived and Base Class)
Inheritance ⚫ It is possible to inherit attributes and methods from
one class to another. Or
⚫ It is a mechanism in which one object acquires all the
properties and behaviors of a parent object.
⚫ The "inheritance concept" into two categories:
⚫ superclass (parent) - the class being inherited from
⚫ subclass (child) - the class that inherits from another
class
⚫ Deriving the properties from super class to sub
class.
⚫ To inherit from a class, use the extends keyword.

Inheritance Cont..
⚫ For Example
⚫ The Car class (subclass) inherits the attributes and methods
from the Vehicle class (superclass)
⚫ Types
Class A
Father
⚫ Single Inheritance

⚫ Hierarchical Inheritance

⚫ Multiple Inheritance -Interface Class B extends A


Son/daugher
⚫ Multilevel Inheritance
Hierarchical Inheritance
FATHER

SON - 1 SON - 2 SON - 3

Terms used in Inheritance


Syntax
1. class Subclass-name extends Superclass-name • Class:
• A class is a group of objects which have common properties.
2. { • It is a template or blueprint from which objects are created.
• Sub Class/Child Class:
3. //methods and fields • Subclass is a class which inherits the other class.
• It is also called a derived class, extended class, or child class.
4. }
• 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
to reuse the fields and methods of the existing class when you
create a new class.
• can use the same fields and methods already defined in the
previous class.
Why use inheritance in java ? Polymorphism
⚫ can perform a single action in different ways.
⚫ Polymorphism is derived from 2 Greek words:
⚫ For Method Overriding ⚫ poly and morphs.
(so runtime polymorphism can be achieved). ⚫ The word "poly" means many and "morphs" means forms.
⚫ For Code Reusability. ⚫ So polymorphism means many forms.

⚫ There are two types of polymorphism in Java:


⚫ compile-time polymorphism (Method Overloading)
⚫ runtime polymorphism. (method Overriding)

⚫ can perform polymorphism in java by method overloading


and method overriding.

Method Overloading- Compile time Different ways to overload the


Polymorphism method
⚫ A class has multiple methods having same name but
different in parameters, it is known as Method ⚫ There are two ways to overload the method in java
Overloading.
⚫ Example:
⚫ By changing number of arguments
⚫ Suppose we want to perform addition with same ⚫ Add(int,int) , add(int,int,int)
method name add()
⚫ By changing the data type
⚫ Different arguments are possible for the method
⚫ Add(float,int) , add(int,float,double)
such as add(int,int) for two parameters, and
add(int,int,int) for three parameters
Method Overriding –Run time
polymorphism Rules for Java Method Overriding
⚫ subclass (child class) has the same method as declared in
the parent class, it is known as method overriding in Java. ⚫ The method must have the same name as in the
parent class
⚫ In other words, If a subclass provides the specific ⚫ The method must have the same parameter as in the
implementation of the method that has been declared by
one of its parent class, it is known as method overriding. parent class.
⚫ There must be an IS-A relationship (inheritance).
⚫ Usage of Java Method Overriding
⚫ Method overriding is used to provide the specific
implementation of a method which is already provided by
its superclass.
⚫ Method overriding is used for runtime polymorphism

Binding binding
⚫ Connecting a method call to the method body is
known as binding. or
⚫ Binding is the process of linking a procedure call to the
code to be executed in response to the call
⚫ It means that the code associated with the given
procedure call is not known until the time of the call at
runtime
⚫ Types:
⚫ Static Binding (also known as Early Binding).
⚫ Dynamic Binding (also known as Late Binding).
Static Binding vs Dynamic Binding

⚫ Static Binding: ⚫ Dynamic Binding :


⚫ Static Binding (also known as Early Binding). ⚫ Dynamic Binding that happens at runtime
⚫ Static Binding that happens at compile time. ⚫ Dynamic Binding (also known as Late Binding).

⚫ The binding which can be resolved at compile time by ⚫ When compiler is not able to resolve the call/binding
compiler is known as static or early binding. at compile time, such binding is known as Dynamic or
late Binding.
⚫ Binding of private, static and final methods always
happen at compile time since these methods cannot be ⚫ Example:
overridden. ⚫ Method Overriding

Message Passing Message Passing


⚫ Message Passing in terms of computers is ⚫ An object-oriented program consists of a set of objects
communication between processes. that communicate with each other.
⚫ It is a form of communication used in object-oriented ⚫
programming as well as parallel programming. •The process of programming in an oops , therefore
involves the following basic steps:
⚫ Message passing in Java is like sending an object 1.Creating classes that define objects and their
i.e. message from one thread to another thread. behavior,
2.Creating objects from class definitions
3.Establishing communication among objects.
⚫ The network of Objects Communicating with Each
Other.
⚫ Objects communicate with one another by sending ⚫ Specifying the object name, the method name, and
and receiving information much the same way as the information to be sent is involved
people pass messages to one another. in message passing

⚫ Message passing involves specifying the name of the


object, the name of the function (message) and the
information to be sent.
Benefits of OOPS-2/3 marks
Security: Easily upgraded:
⚫ In OOP, Data is encapsulated with methods in the class so that data is
protected and secured from accidental modification by other external ⚫ Object-oriented system can be easily upgraded from small to
non-member methods. large systems because OOP uses bottom-up approach.
Reusability: Easy partition of work:
⚫ Through inheritance, we can use the features of an existing class in a new
class without repeating existing code that saves a lot of time of developers and ⚫ It is easy to partition of complicated work in a project based on
also increases productivity. objects.
Effective communication:
⚫ In OOP, objects can communicate via message passing technique that makes
Maintenance:
interface descriptions with outside systems much simpler. ⚫ The maintenance of object-oriented code is easier.
Developing complex software: Troubleshooting is easy.
⚫ OOPs is the most suitable approach for developing complex software because
it minimizes the complexity through the feature of inheritance. Efficiency:
⚫ Ability to reflect the real world and Code Modularity. ⚫ The concepts of OOP provides better efficiency and easy
development process

Applications of Object Oriented


Programming-2marks FEATURES OF JAVA -2/3/10marks
⚫ Graphical user interface (GUI)design in the Windows ⚫ The features of Java are also known as java buzzwords.
⚫ Simple
operating system. ⚫ Object-Oriented
⚫ Real Time Systems ⚫ Portable


⚫ Platform independent
Simulation and Modeling ⚫ Secured

⚫ Object oriented databases ⚫ Robust


⚫ Architecture neutral
⚫ AI and Expert System ⚫ Interpreted

⚫ Neural Networks and parallel programming ⚫ High Performance


⚫ Multithread
⚫ Decision support and office automation systems ⚫ Distributed

⚫ CIM/CAD/CAM etc. ⚫ Dynamic


Simple
⚫ Java is very easy to learn, and its syntax is simple, clean and
easy to understand.
⚫ It is simple
because of the following factors:
1.It is free from pointer due to this execution time of
application is improved.
2.It has Rich set of API (application protocol interface).
3.It has Garbage Collector which is always used to collect
un-Referenced (unused) Memory location for improving
performance of a Java program.
4.It contains user friendly syntax for developing any
applications.

Object Oriented Programming Platform Independent


⚫ Java is an object-oriented programming language. ⚫ Java is platform independent because it is different from
⚫ Everything in Java is an object. other languages like C, C++, etc. which are compiled into
⚫ Object-oriented means the software as a combination of different platform specific machines while Java is a write once, run
types of objects that incorporates both data and behavior. anywhere language.
⚫ Object-oriented programming (OOPs) is a methodology that
simplifies software development and maintenance by providing some ⚫ A platform is the hardware or software environment in
rules. which a program runs.
⚫ Basic concepts of OOPs are: ⚫ There are two types of platforms
⚫ Object ⚫ software-based
⚫ Class ⚫ hardware-based.

⚫ Java provides a software-based platform.
Inheritance
⚫ Polymorphism
⚫ Abstraction ⚫ The Java platform differs from most other platforms in the
⚫ Encapsulation sense that it is a software-based platform that runs on the
top of other hardware-based platforms
Secured
Platform Independent cont..
⚫ It has two components: ⚫ Java is best known for its security, virus-free systems can be
⚫ Runtime Environment developed.
⚫ API(Application Programming Interface)
⚫ Java is secured because:
⚫ No explicit pointer
⚫ Java code can be run on multiple platforms,
⚫ Java Programs run inside a virtual machine sandbox
⚫ Class loader: Class loader in Java is a part of the Java Runtime
⚫ For example, Environment(JRE) which is used to load Java classes into the Java
⚫ Windows, Linux, Sun Solaris, Mac/OS, etc. Virtual Machine dynamically.
⚫ Byte code Verifier: It checks the code fragments for illegal code
that can violate access right to objects.
⚫ Java code is compiled by the compiler and converted into bytecode.
⚫ Security Manager: It determines what resources a class can access
This bytecode is a platform-independent code because it can such as reading and writing to the local disk.
be run on multiple platforms, i.e., Write Once and Run
⚫ Java language provides these securities by default. Some security
Anywhere(WORA) provided by SSL, JAAS, Cryptography, etc

Robust
⚫ Robust simply means strong.
⚫ Java is robust because:
⚫ It uses strong memory management.
⚫ There is a lack of pointers that avoids security problems.
⚫ There is automatic garbage collection in java which runs
on the Java Virtual Machine to get rid of objects which
are not being used by a Java application anymore.
⚫ There are exception handling and the type checking
mechanism in Java.
Architecture-neutral
⚫ Java is architecture neutral because there are no implementation
dependent features.

⚫ Architecture represents processor.


⚫ A Language or Technology is said to be Architectural neutral which
can run on any available processors in the real world without
considering their development and
compilation.

⚫ The languages like C, CPP are treated as architectural dependent.

⚫ In C programming, int data type occupies 2 bytes of memory for 32-bit


architecture and 4 bytes of memory for 64-bit architecture.

⚫ For example, the size of primitive types is fixed


⚫ However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java

Portable High-performance
⚫ Java is portable because it facilitates to carry the Java ⚫ Java is faster than other traditional interpreted
byte code to any platform. programming languages because Java
⚫ It doesn't require any implementation. bytecode is "close" to native code.
⚫ It is still a little bit slower than a compiled language
(e.g., C++).
⚫ Java is an interpreted language that is why it is slower
than compiled languages, e.g., C, C++, etc.
Distributed
⚫ Java is distributed because it facilitates users to create
distributed applications in Java.
⚫ RMI and EJB are used for creating distributed
applications.
⚫ This feature of Java makes us able to access files by
calling the methods from any machine on the internet.

⚫ Note:
⚫ Remote Method Invocation (RMI)
⚫ Enterprise Java Bean (EJB)

Multi-threaded Dynamic
⚫ A thread is like a separate program, executing ⚫ Java is a dynamic language.
concurrently. ⚫ It supports dynamic loading of classes.
⚫ A flow of control is known as a thread. ⚫ It means classes are loaded on demand.
⚫ Can write Java programs that deal with many tasks at ⚫ It also supports functions from its native languages,
once by defining multiple threads. i.e., C and C++.
⚫ The main advantage of multi-threading is that it ⚫ Java supports dynamic compilation and automatic
doesn't occupy memory for each thread. memory management (garbage collection).
⚫ It shares a common memory area.
⚫ Threads are important for multi-media, Web
applications, etc
Thank you
How is Java platform independent?
Java
⚫ Java applications are typically compiled to bytecode
that can run on any Java virtual machine (JVM)
⚫ The meaning of platform-independent is that the java
regardless of computer architecture.
compiled code(byte code) can run on all operating
⚫ The latest version is Java 19 released on Sep 20, 2022 systems.
⚫ JVM, JRE, and JDK are platform dependent because
the configuration of each OS is different from each
other.
⚫ However, Java is platform independent.

Reason for platform independent


⚫ A program is written in a language that is a human-readable language. ⚫ Java program or source code(English) - user written
⚫ It may contain words, phrases, etc which the machine does not
understand. ⚫ Java program -> machine code (by compiler)-javac
⚫ For the source code to be understood by the machine, it needs to be in
a language understood by machines, typically a machine-level ⚫ Source code(java code) -> Byte code –compiler work

language.
⚫ So, here comes the role of a compiler. Bytecode-> executable code – interpreter work(JVM)
⚫ The compiler converts the high-level language (human language) into
a format understood by the machines.
⚫ Therefore, a compiler is a program that translates the source code for
⚫ Note: machine code= byte code=intermediate code
another program from a programming language into executable code.
⚫ This executable code may be a sequence of machine instructions that
can be executed by the CPU directly, or it may be an intermediate
representation that is interpreted by a virtual machine.
⚫ This intermediate representation in Java is the Java Byte Code.
Step by step Execution of Java
Program: JDK,JRE,JVM
⚫ JDK is a software development kit
1. Whenever, a program is written in JAVA, the javac compiles ⚫ JRE is a software bundle that allows Java program to
it.
run,
2. The result of the JAVA compiler is the .class file or the
bytecode and not the machine native code (unlike C ⚫ JVM is an environment for executing bytecode.
compiler).
3. The bytecode generated is a non-executable code and
needs an interpreter to execute on a machine.
4. This interpreter is the JVM and thus the Bytecode is
executed by the JVM.
5. And finally program runs to give the desired output.

JVM
JDK,JRE,JVM ⚫ JVM (Java Virtual Machine) is an abstract machine.
⚫ It is called a virtual machine because it doesn't physically
exist.
⚫ It is a specification that provides a runtime environment in
which Java bytecode can be executed.
⚫ It can also run those programs which are written in other
languages and compiled to Java bytecode.
⚫ The JVM performs the following main tasks:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
JRE
JRE
⚫ JRE is an acronym for Java Runtime Environment.
⚫ It is also written as Java RTE.
⚫ The Java Runtime Environment is a set of software tools which
are used for developing Java applications.
⚫ It is used to provide the runtime environment.
⚫ It is the implementation of JVM.
⚫ It physically exists.
⚫ It contains a set of libraries + other files that JVM uses at
runtime.
⚫ The implementation of JVM is also actively released by other
companies besides Sun Micro Systems

JDK JDK
⚫ JDK is an acronym for Java Development Kit.
⚫ The Java Development Kit (JDK) is a software development environment
which is used to develop Java applications and applets.
⚫ It physically exists.
⚫ It contains JRE + development tools.

⚫ JDK is an implementation of any one of the below given Java Platforms


released by Oracle Corporation:

⚫ Standard Edition Java Platform


⚫ Enterprise Edition Java Platform
⚫ Micro Edition Java Platform

⚫ The JDK contains a private Java Virtual Machine (JVM) and a few other
resources such as an interpreter/loader (java), a compiler (javac), an archiver
(jar), a documentation generator (Javadoc), etc. to complete the development
of a Java Application.
JDK– JAVA DEVELOPMENT KIT

JDK is a software development environment used in
the development of Java applications and applets.


JDK is the core component of Java environment.

It contains JRE (Java Runtime Environment) along
with Java compiler, Java debugger, and other classes.

Simple Java program

⚫ 1. Class Loader: class sample //class Declaration


•The Class Loader loads all necessary classes needed {
for the execution of a program public static void Main(String args[] )
⚫ 2. Byte Code Verifier: {
•Byte Code Verifier that checks the format and checks
System.out.println(“Welcome to java”);
for an illegal code
}
⚫ 3. Interpreter:
}
Converts Byte code to executable code
}
Comments
Java program for Assignment-2
⚫ Write a java program for the following ⚫ The Java comments are the statements in a program that
are not executed by the compiler and interpreter.
⚫ Fibonacci series
⚫ Why do we use comments in a code?
⚫ Factorial number
⚫ Comments are used to make the program more readable by
⚫ Palindrome adding the details of the code.
⚫ Reverse of a digit ⚫ It makes easy to maintain the code and to find the errors
⚫ Sum of digits
easily.
⚫ The comments can be used to provide information or
explanation about the variable, method, class, or any
statement.
⚫ It can also be used to prevent the execution of program code
while testing the alternative code.

Types of Java Comments

⚫ There are three types of comments in Java.


⚫ Single Line Comment
⚫ Multi Line Comment
⚫ Documentation Comment
1) Java Single Line Comment

⚫ The single-line comment is used to comment only one ⚫ Syntax:


line of the code. ⚫ //This is single line comment
⚫ It is the widely used and easiest way of commenting ⚫ Example
the statements. ⚫ int i=50; // i is a variable with value 10
⚫ Single line comments starts with two forward ⚫ System.out.println(i); //printing the variable i
slashes (//).
⚫ Any text in front of // is not executed by Java.

2) Java Multi Line Comment

⚫ The multi-line comment is used to comment multiple ⚫ Syntax:


lines of code. ⚫ /*
⚫ It can be used to explain a complex code snippet or to ⚫ This
comment multiple lines of code at a time (as it will be ⚫ is
difficult to use single-line comments there).
⚫ multi line
⚫ Multi-line comments are placed between /* and */.
⚫ comment
Any text between /* and */ is not executed by Java.
⚫ */
3) Java Documentation Comment
Example
⚫ /* float i = 12.9; ⚫ Documentation comments are usually used to write
⚫ float j = 41.4; large programs for a project or software application as
⚫ System.out.println( j + k ); */ it helps to create documentation API.
⚫ These APIs are needed for reference, i.e., which
classes, methods, arguments, etc., are used in the
code.
⚫ To create documentation API, we need to use
the javadoc tool. The documentation comments are
placed between /** and */.

Data types
⚫ Data types specify the different sizes and values that can be
Example stored in the variable.
⚫ There are two types of data types in Java
⚫ /** ⚫ Primitive data types:
⚫ * ⚫ Boolean,


char,
*We can use various tags to depict the parameter ⚫ byte,
⚫ *or heading or author name ⚫

short,
int,
⚫ *We can also use HTML tags ⚫ long,

⚫ float
* ⚫ double.
⚫ */ ⚫ Non-primitive data types:


⚫ Classes
⚫ Interfaces
⚫ Arrays, ect..
Java Primitive Data Types

⚫ Primitive data types are the building blocks of data


manipulation.

⚫ Boolean data type


⚫ byte data type
⚫ char data type
⚫ short data type
⚫ int data type
⚫ long data type
⚫ float data type
⚫ double data type

Boolean Data Type

⚫ The Boolean data type is used to store only two


possible values:
⚫ true and false.
⚫ This data type is used for simple flags that track
true/false conditions.
⚫ Example
⚫ Boolean one = false
Byte Data Type
⚫ It is an 8-bit signed two's complement integer. 2’s compliment
⚫ Its value-range lies between -128 to 127 (inclusive).
⚫ Find 2’s compliment for the decimal number 5
⚫ Its minimum value is -128 and maximum value is 127.
⚫ 8 bit binary equivalent for 5 is 0000 0101
⚫ Its default value is 0.
⚫ 1’s Compliment
⚫ Example:
⚫ Convert zero(0) to 1(one), and one(1) to zero(0)
⚫ byte a = 5, byte b = 6
⚫ 1111 1010
⚫ Add 1 to the 1’s complimnet
⚫ 1111 1011

Short Data Type int Data Type


⚫ The int data type is a 32-bit signed two's complement
integer.
⚫ The short data type is a 16-bit signed two's ⚫ Its value-range lies between - 2,147,483,648 (-2^31) to
complement integer. 2,147,483,647 (2^31 -1)
⚫ Its value-range lies between -32,768 to 32,767 ⚫ Its minimum value is - 2,147,483,648and maximum
⚫ The minimum value is -32,768 and maximum value is value is 2,147,483,647.
32,767. Its default value is 0. ⚫ Its default value is 0.
⚫ The short data type can also be used to save memory ⚫ The int data type is generally used as a default data
just like byte data type. type for integral values unless if there is no problem
⚫ A short data type is 2 times smaller than an integer. about memory.
⚫ Example ⚫ Example
⚫ short s = 10000, short r = -5000 ⚫ int a = 100000, int b = -200000
Long Data Type Float Data Type
⚫ The long data type is a 64-bit two's complement
integer. ⚫ The float data type is a single-precision 32-bit IEEE 754
⚫ Its value-range lies between floating point.
-9,223,372,036,854,775,808(-2^63) to ⚫ Its value range is unlimited.
9,223,372,036,854,775,807(2^63 -1) ⚫ It is recommended to use a float (instead of double) if you
⚫ Its minimum value is - 9,223,372,036,854,775,808and need to save memory in large arrays of floating point
maximum value is 9,223,372,036,854,775,807. numbers.
⚫ Its default value is 0. ⚫ The float data type should never be used for precise values,

such as currency.
The long data type is used when you need a range of
values more than those provided by int. ⚫ Its default value is 0.0F.

⚫ Example: Example:


float f1 = 234.5f
long a = 100000L, long b = -200000L

Double Data Type

⚫ The double data type is a double-precision 64-bit IEEE


754 floating point.
⚫ Its value range is unlimited.
⚫ The double data type is generally used for decimal
values just like float.
⚫ The double data type also should never be used for
precise values, such as currency.
⚫ Its default value is 0.0d.
⚫ Example:
⚫ double d1 = 12.3
Char Data Type
⚫ The char data type is a single 16-bit Unicode character.
Its value-range lies between '\u0000' (or 0) to '\uffff'
(or 65,535 inclusive).
⚫ The char data type is used to store characters.
⚫ Example:
⚫ char letterA = 'A'
⚫ Why char uses 2 byte in java and what is \u0000 ?
⚫ It is because java uses Unicode system not ASCII code
system.
⚫ The \u0000 is the lowest range of Unicode system.

Variables
⚫ A variable is a container which holds the value while Example
the Java program is executed.
⚫ A variable is assigned with a data type. ⚫ It is a combination of "vary + able" which means its
value can be changed.
⚫ Variable is a name of memory location.
⚫ There are three types of variables in java:
⚫ local,
⚫ instance
⚫ static.
Variable Types
⚫ int data=50;

⚫ 1) Local Variable Example


⚫ A variable declared inside the body of the method is ⚫ public class A
called local variable. ⚫ {
⚫ variable is only within that method and the other ⚫ static int m=100; //static variable
methods in the class aren't even aware that the ⚫ void method()
⚫ {
variable exists. ⚫ int n=90; //local variable
⚫ A local variable cannot be defined with "static" ⚫ }
keyword. ⚫ public static void main(String args[])
⚫ {
⚫ int data=50; //instance variable
⚫ }
⚫ }//end of class
Example
⚫ 2) Instance Variable ⚫ public class A
⚫ {
⚫ A variable declared inside the class but outside the ⚫ static int m=100; //static variable
body of the method, is called an instance variable. It is ⚫ void method()
not declared as static. ⚫ {

⚫ It is called an instance variable because its value is
int n=90; //local variable
⚫ }
instance-specific and is not shared among instances. ⚫ public static void main(String args[])
⚫ {
⚫ int data=50; //instance variable
⚫ }
⚫ }//end of class

⚫ 3) Static variable ⚫ public class A


⚫ {
⚫ A variable that is declared as static is called a static ⚫ static int m=100; //static variable
variable. ⚫ void method()
⚫ It cannot be local. ⚫ {
⚫ int n=90;//local variable
⚫ Can create a single copy of the static variable and share ⚫ }
it among all the instances of the class. ⚫ public static void main(String args[])

⚫ Memory allocation for static variables happens only {
⚫ int data=50;//instance variable
once when the class is loaded in the memory. ⚫ }
⚫ }//end of class
Narrowing (Typecasting)
Overflow
⚫ Float is converted as int ⚫ Big data size is type casted to small data size= overflow
⚫ Int-4 bytes, byte -1 byte.
⚫ float f=10.5f; ⚫ //Overflow
⚫ // int a=f; //Compile time error ⚫ int a=130;
⚫ int a=(int)f; ⚫ byte b=(byte)a;
⚫ System.out.println(f); ⚫ System.out.println(a);
⚫ System.out.println(a); ⚫ System.out.println(b);

Operators 1. Arithmetic Operators


An operator is simply a symbol that is used to perform operations.(ex) a+b(+ is
operator) ⚫ 1. Arithmetic Operators: They are used to perform
simple arithmetic operations on primitive data types.
1. Arithmetic Operators
⚫ * : Multiplication

2. Relational Operators
3. Logical Operators
/ : Division
4. Assignment Operators ⚫ % : Modulo
5. Increment and Decrement Operators(Unary Operator)
⚫ + : Addition

6. Bitwise Operators
7. Shift Operators
– : Subtraction
8. Instance Operator
9. Ternary Operator
Operators

2.Unary Operators
⚫ 2. Unary Operators: ⚫ ++ : Increment operator, used for incrementing the value by 1.
There are two varieties of increment operators.
⚫ Unary operators need only one operand. ⚫ Post-Increment: Value is first used for computing the result and
⚫ They are used to increment, decrement or negate a then incremented.
⚫ Pre-Increment: Value is incremented first, and then the result is
value computed.
⚫ – : Unary minus, used for negating the values. ⚫ – – : Decrement operator, used for decrementing the value by
⚫ + : Unary plus indicates the positive value 1. There are two varieties of decrement operators.
⚫ Post-decrement: Value is first used for computing the result and
then decremented.
⚫ Pre-Decrement: Value is decremented first, and then the result is
computed
⚫ ! : Logical not operator, used for inverting a boolean value.
3.Assignment Operator
⚫ Assignment Operator: There are 2 categories of assignment operators .
⚫ ‘=’ Assignment operator is used to assigning a value to
They are,
any variable.
⚫ It has a right to left associativity, i.e. value given on the 1. Simple assignment operator
right-hand side of the operator is assigned to the
variable on the left, and therefore right-hand side
( Example: = )
value must be declared before using it or should be a 2. Compound assignment operators
constant.
⚫ The general format of the assignment operator is: ( Example: +=, -=, *=, /=, %=)
⚫ variable = value;
Operators Example/Description
4. Relational Operators
⚫ 4. Relational Operators:
= sum = 10;
10 is assigned to variable sum

+= sum += 10;
⚫ These operators are used to check for relations like
This is same as sum = sum + 10 equality, greater than, and less than.
-= sum -= 10;
⚫ They return boolean results after the comparison and
This is same as sum = sum – 10 are extensively used in looping statements as well as
conditional if-else statements.

*= sum *= 10;
This is same as sum = sum * 10 Syntax:
⚫ variable relation_operator value

/= sum /= 10;
This is same as sum = sum / 10 Example
%= sum %= 10;
⚫ X>5
This is same as sum = sum % 10

5.Ternary operator
⚫ ==, Equal to returns true if the left-hand side is equal to ⚫ Ternary operator:
the right-hand side.
⚫ !=, Not Equal to returns true if the left-hand side is not ⚫ Ternary operator is a shorthand version of the if-else
equal to the right-hand side. statement.
⚫ <, less than: returns true if the left-hand side is less than ⚫ It has three operands and hence the name ternary.
the right-hand side.
⚫ <=, less than or equal to returns true if the left-hand side ⚫ The general format is:
is less than or equal to the right-hand side. ⚫ condition ? if true : if false
⚫ >, Greater than: returns true if the left-hand side is
greater than the right-hand side.
⚫ >=, Greater than or equal to returns true if the left-hand
side is greater than or equal to the right-hand side.
Conditional Operator (Ternary Operator)
The conditional operator is also known as a ternary operator. The conditional statements are the decision-making
statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.

6.Logical Operators
As conditional operator works on three operands, so it is also known as the ternary operator.

Syntax of a conditional operator ⚫ Logical Operators:


⚫ These operators are used to perform “logical AND” and “logical
Expression1 ? expression2 : expression3;
OR” operations, i.e., a function similar to AND gate and OR gate
in digital electronics

⚫ Conditional operators are:


⚫ &&, Logical AND: returns true when both conditions are true.
⚫ ||, Logical OR: returns true if at least one condition is true.
⚫ !, Logical NOT: returns true when a condition is false and
vice-versa

Logical Operators

Operator Description Example


Operators Example/Description
&& Called Logical AND operator. (A && B) is false.
If both the operands are non-zero, && (logical (x>5)&&(y<5)
then the condition becomes true. AND) It returns true when both conditions are true

|| Called Logical OR Operator. + (A || B) is true.


If any of the two operands is non-zero, (x>=10)||(y>=10)
|| (logical OR)
then the condition becomes true. It returns true when at-least one of the condition is true

! Called Logical NOT Operator. !(A && B) is true.


!((x>5)&&(y<5))
It is used to reverse the logical state of its
! (logical It reverses the state of the operand “((x>5) && (y<5))”
operand.
If a condition is true, then Logical NOT NOT) If “((x>5) && (y<5))” is true, logical NOT operator makes it
operator will make it false. false
Operator Meaning of operator

7.Bitwise & Bitwise AND operator

⚫ Bitwise Operators:
⚫ These operators are used to perform the manipulation of
| Bitwise OR operator
individual bits of a number.
⚫ They can be used with any of the integer types. ^ Bitwise exclusive OR operator
⚫ They are used when performing update and query operations of
the Binary indexed trees.
⚫ &, Bitwise AND operator: returns bit by bit AND of input ~ One's complement operator (unary operator)
values.
⚫ |, Bitwise OR operator: returns bit by bit OR of input values.
⚫ ^, Bitwise XOR operator: returns bit-by-bit XOR of input << Left shift operator
values.
⚫ ~, Bitwise Complement Operator: This is a unary operator >> Right shift operator
which returns the one’s complement representation of the input
value, i.e., with all bits inverted.

Bitwise | (Bitwise OR)

We consider two variables,

a = 23;

We have two variables a and b. b = 10;

a =6; The binary representation of the above two variables would be:

b=4; a = 0001 0111

The binary representation of the above two variables are given b = 0000 1010
below: When we apply the bitwise OR operator in the above two variables, i.e., a|b ,
a = 0110 then the output would be:

b = 0100 Result = 0001 1111

When we apply the bitwise AND operation in the above two


variables, i.e., a&b, the output would be:

Result = 0100
Bitwise ^ (Bitwise XOR) Bitwise ^ (Bitwise XOR)
Let’s take two integers say A = 5 and B = 9. Let’s take two integers say A = 5 and B = 9.
Then what will be the result of A ^ B? Then what will be the result of A ^ B?
Let’s represent each number in binary format. Let’s represent each number in binary format.
A = (0101) A = (0101)
B= (1001) B= (1001)

3 Types
⚫ 8. Shift Operators: ⚫ <<, Left shift operator: shifts the bits of the number to
⚫ These operators are used to shift the bits of a number the left and fills zer0 on voids left as a result. Similar effect
left or right. as multiplying the number with some power of two.
⚫ >>, Signed Right shift operator: shifts the bits of the
⚫ Syntax:
number to the right and fills 0 on voids left as a result. The
⚫ number shift_op number_of_places_to_shift; leftmost bit depends on the sign of the initial number.
⚫ Example: Similar effect as dividing the number with some power of
⚫ 7<<2 two.
⚫ 4>>3 ⚫ >>>, Unsigned Right shift operator: shifts the bits of the
number to the right and fills zero on voids left as a result.
The leftmost bit is set to zer0.(MSB=zer0)
Bitwise shift operators
int a = 5;

Two types of bitwise shift operators. The binary representation of 'a' is given below:

The bitwise shift operators will shift the bits either on the left-side or right-side. a = 0101

Therefore, we can say that the bitwise shift operator is divided into two categories: If we want to left-shift the above representation by 2, then the statement would be:

a << 2;
● Left-shift operator
0101<<2 = 00010100
● Right-shift operator

Left-shift operator
Let's understand through a program.
0 0 0 0 0 1 0 1
#include <stdio.h>
It is an operator that shifts the number of bits to the left-side. int main() 0 0 0 0 0 1 0 1
{
0 0 0 1 0 1 0 0
int a=5; // variable initialization

printf("The value of a<<2 is : %d ", a<<2);

return 0;

Right-shift operator Suppose we have a statement,

int a = 7;
It is an operator that shifts the number of bits to the right side.
The binary representation of the above variable would be:
Syntax of the right-shift operator is given below:
a = 0111
Operand >> n;
If we want to right-shift the above representation by 2, then the statement would be:

Where, a>>2;

0000 0111 >> 2 = 0000 0001


0 0 0 0 0 1 1 1
Operand is an integer expression on which we apply the right-shift operation.
0 0 0 0 0 1 1 1
N is the number of bits to be shifted.

In the case of the right-shift operator, 'n' bits will be shifted on the right-side. The 'n' bits on the 0 0 0 0 0 0 0 1
right-side will be popped out, and 'n' bits on the left-side are filled with 0. #include <stdio.h>

int main()

int a=7; // variable initialization

printf("The value of a>>2 is : %d ", a>>2);

return 0; }
Operators Summary
⚫ 9. instanceof operator:
⚫ The instance of the operator is used for type checking.
⚫ It can be used to test if an object is an instance of a
class, a subclass, or an interface.
⚫ Syntax:
⚫ object instance of class/subclass/interface

Tutorial:
⚫ Write a java program to implements all the operators
concepts.
⚫ Refer example sample programs for your referece.
1.Example Programs-unary

2.Arithmetic Left shift


Right shift Unsigned right shift

Logical and bitwise and Logical and bitwise OR


Ternary Operator Assignment Operator

Instance operator Branching


⚫ Branching:
⚫ Sequence of code in a program which is
conditionally execute depending on whether the
flow of control is altered or not
⚫ Types:
⚫ Conditional branching
⚫ Based on particular condition (with decisions)

⚫ Unconditional branching
⚫ Based on particular condition (without any
decisions)
Types of conditional statements in C#
Conditional Statements
⚫ Conditionals ⚫ The if(condition) statement
⚫ Involve a program’s ability to deduce and do different ⚫ The else-if statement
things depending on the conditions of the codes ⚫ The else statement
written in that program.
⚫ Nested if Statements

⚫ The Short Hand If...Else (or)


⚫ Ternary Operator ?:

⚫ The switch statement

The if(condition) statement


Conditions
⚫ Less than: a < b. ⚫ java uses Boolean variables to evaluate conditions.
⚫ Less than or equal to: a <= b. ⚫ The if statement contains a Boolean condition
⚫ Greater than: a > b. followed by a single or multi-line code block to be
⚫ Greater than or equal to: a >= b. executed.
⚫ Equal to a == b. ⚫ At runtime, if a Boolean condition evaluates to true,
then the code block will be executed, otherwise not.
⚫ Not Equal to: a != b.

⚫ Note: True or false


Syntax Example
int i = 10, j = 20; //initialization
if (i < j) //it checks i value(10) less than j value(20)
if (condition) {
{ System.out.println ("i is less than j"); //true statement
}
// code block to be executed when if condition
evaluates to true if (20 > 18 ) //it checks 20 greater than 18
{
}
System.out.println (“20 is greater than 18"); //true
statement
}

Syntax
The else if Statement ⚫ if(condition 1)
⚫ {
// code block to be executed when if condition1 evaluates to true
⚫ }
⚫ Multiple else if statements can be used after ⚫ else if(condition 2)
⚫ {
an if statement.
// code block to be executed when
⚫ It will only be executed when the if condition // condition1 evaluates to false
evaluates to false. // condition2 evaluates to true
⚫ }
⚫ So, either if or one of the else if statements can be ⚫ else if(condition 3)
executed, but not both. ⚫ {
// code block to be executed when
// condition1 evaluates to false
// condition2 evaluates to false
// condition3 evaluates to true
⚫ }
Example The else Statement
⚫ int i = 10, j = 20;
⚫ Use the else statement to specify a block of code to be
⚫ if (i == j) executed if the condition is False. Or if-else condition is
⚫ { false.
Console.WriteLine("i is equal to j"); //10=20? False ⚫ Syntax
⚫ } ⚫ if (condition)
⚫ else if (i > j) ⚫ {
{ // block of code to be executed if the condition is True
Console.WriteLine("i is greater than j"); //10>20? False ⚫ }
⚫ } ⚫ else
⚫ else if (i < j) ⚫ {
⚫ { // block of code to be executed if the condition is False
Console.WriteLine("i is less than j"); //10<20? TRUE ⚫ }
⚫ }

Example-1 Example-2
⚫ int time = 9 ; ⚫ int time = 9 ;
⚫ if (time < 12) //9<12 ? TRUE ⚫ if (time < 12)
⚫ {
⚫ {
Console.WriteLine("Good Morning"); //9<12 True
Console.WriteLine("Good Morning"); ⚫ }
⚫} ⚫ else if (time < 16)
⚫ else ⚫ {
⚫{ Console.WriteLine("Good Afternoon."); //9<16 False
⚫ }
Console.WriteLine("Good Afternoon.");
⚫ else
⚫}
⚫ {
Console.WriteLine("GoodEvening”) //False
⚫ }
Syntax
if(condition 1)
Nested if -Statements {
if(condition 2)
{
// code block to be executed when condition 1 and condition 2 evaluates to true
}

⚫ Java supports if else statements inside another if


else if (condition 3)
{
if(condition 4)
else statements. {
⚫ This is called nested if else statements. // code block to be executed when only condition 1, condition 3, and condition4 evaluates
to true

⚫ The nested if statements make the code more readable


}
else if(condition 5)
{
// code block to be executed when only condition 1, condition 3, and condition 5 evaluates
to true
}
else
{
// code block to be executed when condition 1, and condition 3 evaluates to true
// condition4 and condition5 evaluates to false
}
}
}

Example
int i = 10, j = 20;
if (i != j)
{
if (i < j)
Ternary Operator ?:
{ ⚫ Java includes a decision-making operator ?:
System.out.println("i is less than j"); //10<20 True
} ⚫ which is called the conditional operator or ternary
else if (i > j) operator.
{
⚫ It is the short form of the if else conditions.
System.out.println ("i is greater than j"); //10>20 False
}
}
else
{
System.out.println ("i is equal to j"); //10=20 False
}
Nested Ternary Operator
Syntax ⚫ Nested ternary operators are possible by including a
conditional expression as a second statement.
⚫ Example:
condition ? statement 1 : statement 2 var x = 2, y = 10;
Example: var result = (x * 3 )> y ? x : y > z? y : z;
int x = 20, y = 10; System.out.println(result);
var result = x > y ? "x is greater than y" : "x is less than y"; Explanation:
System.out.println(result); x*3 ?y – Condition
x – True Statement
Output: y > z – Condition
x is greater than y y= true staement
z- False statement

Syntax:
switch statement switch(match expression/variable)
{
⚫ The switch statement can be used instead of if
case constant-value:
else statement when you want to test a variable against
statement(s) to be executed;
three or more conditions.
break;
case constant-value:
statement(s) to be executed;
break;
default: statement(s) to be executed;
break;
}
Example
int x = 10;
switch (x)
Loops
{
case 5:
System.out.println ("Value of x is 5"); ⚫ A loop statement allows us to execute a statement or a
break; group of statements multiple times.
⚫ It can be divides as
case 10:
System.out.println ("Value of x is 10");
break; ⚫ Loop Statements
case 15: ⚫ Loop Control Statements
System.out.println ("Value of x is 15");
break;
default:
System.out.println ("Unknown value");
break;
}

For Loop
⚫ It Uses the Keyword for
Loop Statements ⚫ The for loop executes a block of statements repeatedly
⚫ Loop Statements: until the specified condition returns false.
⚫ Looping statement are the statements execute one or ⚫ For Loops types
more statement repeatedly several number of times ⚫ For
⚫ Nested For
⚫ Infinite For
⚫ Types of Loop Statements ⚫ For each
⚫ For Loop ⚫ Syntax:
⚫ While Loop for(initialization; condition; incr/decr)
⚫ Do-While Loop {
//code to be executed
}
For Loop –Flow Diagram
For Loop Explanation
⚫ Initialization:
⚫ The initialization section is used to initialize a variable.
⚫ It will be local variable to a for loop and cannot be
accessed outside loop.
⚫ Condition:
⚫ The condition is a Boolean expression that will return
either true or false.
⚫ If an expression evaluates to true, then it will execute
the loop again; otherwise, the loop is exited.
⚫ Iteration:
⚫ The iteration defines the increment or decrement of the
loop variable.

Example OUTPUT

⚫ public class ForExample
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ for(int i=1;i<=10;i++)
⚫ {
⚫ System.out.println(i);
⚫ }
⚫ }
⚫ }
Nested For Loop Example

⚫ For loop is executed inside another For loop, it is ⚫ public class NestedForExample
known as nested for loop. ⚫ {
⚫ Syntax: ⚫ public static void main(string[] args)
⚫ for(initialization; condition; incr/decr) ⚫ {
⚫ for(int i=1;i<=3;i++)
⚫ { ⚫ {
⚫ for(initialization; condition; incr/decr) ⚫ for(int j=1;j<=3;j++)
⚫ { ⚫ {
⚫ System.out.println (i+" "+j);
⚫ System.out.println (---------); ⚫ }
⚫ } ⚫ }
⚫ } ⚫ }
⚫ }

OUTPUT Infinite For Loop


⚫ Double semicolon is used in infinite for loop.
⚫ it will be executed infinite times.
⚫ Syntax
⚫ for (; ;)
⚫ {
⚫ System.out.println( “-------------");
⚫ }
OUTPUT
Example
⚫ public class InfiniteForExample
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ for (; ;)
⚫ {
⚫ System.out.println ("Infinitive For Loop");
⚫ }
⚫ }
⚫ }

For each Syntax and example


⚫ Java provides an enhanced for loop ⚫ for (datatype variableName : arrayName)
⚫ To traverse the data structures like array or collection. ⚫ {
⚫ In the for-each loop, don't need to update the loop ⚫ // code block to be executed
variable.
⚫ }
⚫ Syntax:
⚫ String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
⚫ for(data_type var : array_name/collection_name) ⚫ for (String i : cars)
⚫ { ⚫ {

⚫ //statements ⚫ System.out.println(i);
⚫ }
⚫ }
While While Flow Diagram
⚫ A while loop statement in java repeatedly executes a
target statement as long as a given condition is true.
⚫ while loops, which test the loop condition at the start
of the loop
⚫ Syntax
⚫ while(condition)
⚫ {
⚫ statement(s);
⚫ }

Example OUTPUT
⚫ public class WhileExample
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ int i=1;
⚫ while(i<=10)
⚫ {
⚫ System.out.println (i);
⚫ i++;
⚫ }
⚫ }
⚫ }
Nested While Loop Example: Example
⚫ While loop is used inside another while loop, it is known as
nested while loop. ⚫ public static void main(string[] args)
⚫ The nested while loop is executed fully when outer loop is ⚫ {
executed once. ⚫ int i=1;
⚫ Syntax: ⚫ while(i<=3)
⚫ while(condition) ⚫ {
⚫ { ⚫ int j = 1;
⚫ // Statements ⚫ while (j <= 3)
⚫ // increment or Decrement ⚫ {
⚫ while (condition) ⚫ System.out.println(i+" "+j);
⚫ { ⚫ j++;
⚫ // Statements ⚫ }
⚫ // increment or Decrement ⚫ i++;
⚫ } ⚫ }
⚫ ⚫ }
⚫ }

Output Infinitive While Loop

⚫ infinite while loop is created by passing true as the test


condition.
⚫ Syntax:
⚫ while(true)
⚫ {
⚫ // Statements
⚫ }
Example OUTPUT
⚫ public class WhileExample
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ while(true)
⚫ {
⚫ System.out.println ("Infinitive While Loop");
⚫ }
⚫ }
⚫ }

DO WHILE Flow diagram


⚫ Do-While is used to test the loop condition at the end
of the loop.
⚫ A do...while loop is similar to a while loop, except that
a do...while loop is guaranteed to execute at least one
time.
⚫ Syntax
⚫ do
⚫ {
statement(s);
⚫ } while( condition );
Example
⚫ public class DoWhileExample
⚫ { OUTPUT
⚫ public static void main(string[] args)
⚫ {
⚫ int i = 1;
⚫ do
⚫ {
⚫ System.out.println (i);
⚫ i++;
⚫ } while (i <= 10) ;

⚫ }
⚫ }

⚫ Loop Control Statements


Break Statement
⚫ Loop has a control whether to execute a statements or ⚫ The break is used to break loop or switch statement.
not. ⚫ Terminates the loop or switch statement
⚫ It breaks the current flow of the program at the given
⚫ Types condition.
⚫ Break ⚫ In case of inner loop, it breaks only inner loop.
⚫ Continue ⚫ break statement is encountered inside a loop, the loop
⚫ Goto is immediately terminated and program control
resumes at the next statement following the loop.
⚫ It can be used to terminate a case in
the switch statement.
⚫ Syntax
⚫ break;
Flow Diagram
Example
⚫ public class BreakExample
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ for (int i = 1; i <= 10; i++)
⚫ {
⚫ if (i == 5)
⚫ {
⚫ break;
⚫ }
⚫ System.out.println (i);
⚫ }
⚫ }
⚫ }

Break

Statement with Inner Loop
public class BreakExample
OUTPUT ⚫

{
public static void main(string[] args)
⚫ {
⚫ for(int i=1;i<=3;i++) // Outer Loop
⚫ {
⚫ for(int j=1;j<=3;j++) // Inner Loop
⚫ {
⚫ if(i==2&&j==2)
⚫ {
⚫ break;
⚫ }

⚫ System.out.println+" "+j);
⚫ }
⚫ }
⚫ }
⚫ }
Continue Statement
output ⚫ The continue statement is used to continue loop.
⚫ It continues the current flow of the program and skips
the remaining code at specified condition.
⚫ In case of inner loop, it continues only inner loop.
⚫ Syntax:
continue;

Flow Diagram Example



⚫ public class ContinueExample
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ for(int i=1;i<=10;i++)
⚫ {
⚫ if(i==5)
⚫ {
⚫ continue;
⚫ }
⚫ System.out.println (i);
⚫ }
⚫ }
⚫ }
Goto Statement
Output ⚫ The goto statement is also known jump statement.
⚫ It is used to transfer control to the other part of the
program.
⚫ It unconditionally jumps to the specified label.
⚫ It can be used to transfer control from deeply nested
loop or switch case label.
⚫ Syntax
⚫ Lable:
Executable Statements
Goto Lable

Example
⚫class A
Output
⚫ {
⚫ public static void main(string[] args)
⚫ {
⚫ ineligible:
⚫ System.out.println ("You are not eligible to vote!");
⚫ System.out.println ("Enter your age:\n");
⚫ Scanner input = new Scanner (System.in);
⚫ int age = input.NextInt());
⚫ if (age < 18)
⚫ {
⚫ goto ineligible;
⚫ }
⚫ else
⚫ {
⚫ System.out.println("You are eligible to vote!");
⚫ }
⚫ }
⚫ }
Array
⚫ Normally ,An array is a collection of similar type of elements which has
Example:2 contiguous memory location.

⚫ Java array is an object which contains elements of a similar data type.
class A
⚫ {
⚫ public static void main(string[] args)

⚫ The elements of an array are stored in a contiguous memory location.
{
⚫ System.out.println ("Enter your age:\n");
⚫ Scanner input = new Scanner (System.in);


int age = input.NextInt());
if (age < 18)
⚫ It is a data structure where can store similar elements.
⚫ {
⚫ goto ineligible; ⚫ Can store only a fixed set of elements in a Java array.
⚫ }
⚫ else
⚫ { ⚫ Array in Java is index-based, the first element of the array is stored at
⚫ System.out.println("You are eligible to vote!"); the zer0th index, 2nd element is stored on 1st index and so on.
⚫ }
⚫ ineligible:
⚫ System.out.println ("You are not eligible to vote!"); ⚫ In Java, array is an object of a dynamically generated class.

⚫ }
⚫ }

Advantages and Disadvantages


⚫ Advantages
⚫ Code Optimization: It makes the code optimized, we can
retrieve or sort the data efficiently.(less code)
⚫ Random access: can get any data located at an index
position.
⚫ Disadvantages
⚫ Size Limit: can store only the 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
which grows automatically.
Types of Array in java
1D array
⚫ There are two types of array.
⚫ Single Dimensional Array
⚫ Multidimensional Array

Single Dimensional Array in Java


Example
⚫ Syntax to Declare an Array in Java ⚫ int iArray[]; //declaring array
⚫ dataType[] arr; (or) ⚫ iArray = new int[20]; // allocating memory to array
⚫ dataType []arr; (or)
⚫ dataType arr[]; ⚫ OR
⚫ Instantiation of an Array in Java ⚫ int[] iArray = new int[20]; // combining both statements in
⚫ Instantiating an Array in Java(allocating size) one
⚫ When an array is declared, only a reference of an array ⚫ OR
is created. ⚫ int a[]={33,3,4,5};
⚫ var-name = new datatype [size]; ⚫ //declaration, instantiation and initialization
⚫ arr=new datatype[size];
example Multi dimensional array
⚫ class iarray ⚫ Data is stored in row and column based index
⚫ { ⚫ Syntax:
⚫ public static void main (String[] args) { ⚫ dataType[][] arrayname; (or)
⚫ // Syntax ⚫ dataType [][]arrayname; (or)
⚫ int [] arr= new int[3]; ⚫ dataType arrayname[][]; (or)
⚫ // 3 elements ⚫ dataType []arrayname[];
⚫ }
⚫}

Jagged array: Multidimensional


Arrays:
Jagged array
⚫ Multidimensional arrays are arrays of arrays with
each element of the array holding the reference of
other arrays.
⚫ These are also known as Jagged Arrays.
⚫ A multidimensional array is created by appending one
set of square brackets ([][]) per dimension.
⚫ Syntax :
⚫ data type [][] arrayname;
⚫ or
⚫ datatype arrayname[][];
Example
⚫ Example to instantiate Multidimensional Array in Java ⚫
⚫ int[][] arr=new int[3][3]; //3 row and 3 column
⚫ Example to initialize Multidimensional Array in Java ⚫ class jaggedarray
⚫ arr[0][0]=1; ⚫ {

⚫ public static void main (String[] args) {
arr[0][1]=2;
⚫ arr[0][2]=3;
⚫ arr[1][0]=4; ⚫ // Syntax
⚫ arr[1][1]=5; ⚫ int [][] arr= new int[3][3];
⚫ arr[1][2]=6;
⚫ arr[2][0]=7; ⚫ // 3 row and 3 column
⚫ arr[2][1]=8; ⚫ }

⚫}
arr[2][2]=9;

Accessing Java Array Elements


using for Loop
Array
⚫ Each element in the array is accessed via its index.
⚫ The index begins with zer0(0) and ends at (total array
size)-1.
⚫ All the elements of array can be accessed using Java for
Loop.
⚫ // accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
⚫ {
⚫ System.out.println("Element at index " + i + " : "+ arr[i]);
⚫ }
Program Jagged array
⚫ class Testmarray{ ⚫ public class multiDimensional


{
public static void main(String args[]) ⚫ public static void main(String args[])
⚫ { ⚫ {
⚫ //declaring and initializing 2D array ⚫

// declaring and initializing 2D array


int arr[][] = { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; ⚫
⚫ //printing 2D array ⚫ // printing 2D array


for (int i = 0; i < 3; i++)
for(int i=0;i<3;i++){ ⚫ {
⚫ for(int j=0;j<3;j++){ ⚫ for (int j = 0; j < 3; j++)
⚫ System.out.print(arr[i][j]+" "); ⚫

{


System.out.print(arr[i][j] + " ");
} ⚫ }
⚫ System.out.println(); ⚫


}
} ⚫ }
⚫ } ⚫ }
}

For-each Loop for Java Array


For each- array traversal
⚫ can also print the Java array using for-each loop.
⚫ The Java for-each loop prints the array elements one by
one.
⚫ It holds an array element in a variable, then executes
the body of the loop.
⚫ Syntax
⚫ for(data_type variable:array)
⚫ {
⚫ //body of the loop
⚫ }
Passing Arrays to Methods Returning Arrays from Methods
⚫ Like variables, we can also pass arrays to methods.


For example, ⚫ As usual, a method can also return an array.

public class Test
⚫ { For example,
⚫ ⚫ class Test


public static void main(String args[])
⚫ { {
⚫ int arr[] = { 3, 1, 2, 5, 4 }; ⚫ public static void main(String args[])

⚫ // passing array to method m1 ⚫ {
⚫ sum(arr); ⚫ int arr[] = m1();


}
⚫ for (int i = 0; i < arr.length; i++)
⚫ public static void sum(int[] arr) ⚫ System.out.print(arr[i] + " ");


{
⚫ // getting sum of array values }
⚫ int sum = 0; ⚫


⚫ public static int[] m1()

for (int i = 0; i < arr.length; i++)
⚫ sum += arr[i]; {


⚫ // returning array

System.out.println("sum of array values : " + sum);
⚫ } return new int[] { 1, 2, 3 };
⚫ }
⚫ }
⚫ }

Class Objects for Arrays Copying a Java Array


⚫ Every array has an associated Class object, shared with all other arrays with the same
component type.

⚫ class Test ⚫ We can copy an array to another by the arraycopy()


⚫ {
⚫ public static void main(String args[])
method of System class.
⚫ { ⚫ Syntax of arraycopy method


int intArray[] = new int[3];
⚫ byte byteArray[] = new byte[3]; public static void arraycopy
⚫ short shortsArray[] = new short[3]; ⚫ (


String[] strArray = new String[3];
⚫ System.out.println(intArray.getClass()); Object src, int srcPos,Object dest, int destPos, int len
⚫ System.out.println( intArray.getClass().getSuperclass());
gth


System.out.println(byteArray.getClass());
⚫ System.out.println(shortsArray.getClass()); )
⚫ System.out.println(strArray.getClass());
⚫ }
⚫ }
Cloning an Array in Java
example
⚫ Java create the clone of the Java array.
⚫ The clone of a single-dimensional array, it creates the
deep copy of the Java array.
⚫ It means, it will copy the actual value.
⚫ The clone of a multidimensional array, it creates the
shallow copy of the Java array.
⚫ which means it copies the references.

Example Matrix addition


Matrix multiplication Tutorial
⚫ 1. Java Program to print the elements of an array in
reverse order
⚫ 2.Java Program to print the duplicate elements of an
array
⚫ 3.Java Program to sort the elements of an array in
ascending order
⚫ 4. Java Program to sort the elements of an array in
descending order
⚫ 5. Java Program to print the sum of all the items of the
array

String How to create a string object?


⚫ String is a set character or group of character enclosed with
double quotes.
⚫ In Java, string is basically an object that represents ⚫ There are two ways to create String object:
sequence of char values.
⚫ By string literal
⚫ String is a sequence of characters.
⚫ By new keyword
⚫ But in Java, string is an object that represents a sequence of
characters. ⚫ 1) String Literal (memory efficient=memory allocated
⚫ The java.lang.String class is used to create a string object. once)
⚫ Syntax ⚫ Java String literal is created by using double quotes. For
1. char[] ch={‘v’,’I’,’b’,’g’,’y’,’o’,’r’}; Example:
2. String s=new String(ch); ⚫ String s=“color"; 4
3. String s=“color"; ⚫ 2) By new keyword
1. String s=new String(“color");
2. //creates two objects and one reference variable
example
⚫ Java String class provides a lot of methods to
perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.

Java String class methods


⚫ The java.lang.String class provides many useful
methods to perform operations on sequence of char
values.
Java program for Assignment-2
⚫ Write a java program for the following
⚫ Fibonacci series
⚫ Factorial number
⚫ Palindrome
⚫ Reverse of a digit and check the digits is palindrome
⚫ Reverse of a string and check the string is palindrome
⚫ Sum of digits
Object:
•Objects are basic run time entity.
Object
•Any entity that has state and behavior is known as an object. •Object is an real world entity that has state, behavior and
•They may represent a person, a place, a bank account, a table of data or any identity.
item that the program has to handle. •State :
•It is represented by attributes of an object.
•For example: •It also reflects the properties of an object.
•a chair, pen, table, keyboard, bike, etc. •Behavior :
•It can be physical or logical. •It is represented by methods of an object.
•It also reflects the response of an object with other objects.
•Identity :
• It gives a unique name to an object and enables one object to
interact with other objects.

Object
•An Object can be defined as an instance of a class.
•An object contains an address and takes up some space
in memory.
•Objects can communicate without knowing the details
of each other's data or code.
•The only necessary thing is the type of message
accepted and the type of response returned by the 4

objects.
Object concept in programming:

• Any programming problem is analyzed based on


objects and how they communicate amongst
themselves.
•The objects interact with each other by sending
messages to one another when a program is
executed.
For Example:
‘customer’ and ‘account’ are two objects that
may send a message to the account object
requesting for the balance.
•Each object contains code and data to
manipulate the data.
•Objects can even interact without knowing
the details of each other’s code or data.

Class Class- Example


⚫ Collection of objects is called class. ⚫ A class called “Expensive Cars”
⚫ It is a logical entity. ⚫ it could have objects like
⚫ A class can also be defined as a blueprint or ⚫ Mercedes,
prototype from which objects are created. ⚫ BMW,
⚫ Class doesn't consume any space. ⚫ Toyota, etc.
⚫ Classes being passive do not communicate with each
⚫ Data or Its properties can be price or speed of these cars.
other but are used to instantiate objects that interact
with each other. ⚫ Methods may be performed with these cars are driving,
⚫ It represents the set of properties or methods that are reverse, braking etc.
common to all objects of one type.
Class Object
•The collection of objects of similar types is termed as a class. ⚫ Object is a real world entity,
For Example, ⚫ For example:
apple, orange, and mango are the objects of the class Fruit. ⚫ chair, car, pen, mobile, laptop etc.
⚫ object is an entity that has state and behavior.
•The entire set of code and data of an object can be made user-defined data type using
the concept of the class.
• A class is a ‘data-type’ and an object as a ‘variable’ of that type. ⚫ Here, state means data and behavior means
• Any number of objects can be created after a class is created. functionality.
•Characteristics of an object are represented in a class as Properties.
⚫ Object is a runtime entity, it is created at runtime.
•The actions that can be performed by objects become functions of the class and is ⚫ Object is an instance of a class.
referred to as Methods. ⚫ All the members of the class can be accessed through
object.
18 ⚫ Student s1 = new Student()

Class Sample Program


⚫ In java , class is a group of similar objects.
⚫ It can have fields, methods, constructors etc.
⚫ Example Using class and objects
⚫ public class Student
⚫ {
⚫ int id; //field or data member
⚫ String name; //field or data member
⚫ }
Example Example 2: Having Main() in another class

⚫ public class Student ⚫ public class Student
⚫ { ⚫ {


public int id;
int id; //data member (also instance variable) ⚫ public String name;
⚫ String name; //data member(also instance variable) ⚫ }
⚫ public static void main(string[] args) ⚫ class TestStudent


{
{ ⚫ public static void main(string[] args)
⚫ Student s1 = new Student(); ⚫ {
//creating an object of Student ⚫ Student s1 = new Student();
⚫ s1.id = 1; ⚫ s1.id = 1;


s1.name = "Soniya ";
s1.name =“Soniya”; ⚫ System.out.println(“ID=”+s1.id);
⚫ System.out.println(“Id=”+s1.id); ⚫ System.out.println(“Name=”+s1.name);
⚫ System.out.println(“Name=”+s1.name); ⚫ }


}
}
⚫ }

Class Declaration A simple java program


class sample //class Declaration
{
Class sample public static void Main(String args[] )
฀ Class is a collection of an objects which defines the
{
data and functionality .
System.out.println(“Welcome to java”);
฀ Classes generally contain multiple methods.
}
฀ Methods define the behaviour of the class.
}
}
Class is a keyword and declare a new class definition.
Sample is a class name
access modifiers-2m/3m Accessing a class members
⚫ They are access modifiers and help us ⚫ Accessing a class members by objects.
implement Encapsulation (or information hiding). ⚫ Syntax:
They tell the compiler which other classes should have
access to the field or method being defined. ⚫ Classname objectname=new classname();
⚫ private - Only the current class will have access to the ⚫ Object.classmember;
field or method. ⚫ Example:
⚫ protected - Only the current class and subclasses ⚫ Student s1 = new Student();

(and sometimes also same-package classes) of this
s1.id = 1;
class will have access to the field or method.
⚫ public - Any class can refer to the field or call the ⚫ s1.name = "Soniya ";
method

Constructor Types
⚫ In Java, a constructor is a block of codes similar to the ⚫ There are two types of constructors in Java:
method.
⚫ no-arg constructor(default)
⚫ It is called when an instance of the class is created.
⚫ parameterized constructor.
⚫ 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.
Rules for creating Java constructor Java Default Constructor

⚫ There are two rules defined for the constructor. ⚫ A constructor is called "Default Constructor" when it
doesn't have any parameter.
⚫ Constructor name must be the same as its class name ⚫ Syntax of default constructor:
⚫ A Constructor must have no explicit return type 1. <class_name>()
⚫ A Java constructor cannot be abstract, static, final, and 2. {
synchronized 3. --------
4. }

Defining a Constructor
Constructor class Car
⚫ A constructor is a special method which has same {
name as class name. public string model;
⚫ It will invoke when object is created. public string color;
public Car() //Constructor
⚫ Syntax {
⚫ Constructor name() //same as class name model=“volkswagan polo”;
⚫ { color=“red”;
⚫ } }
}
Type of constructors
⚫ Default Constructor Parameterized Constructor:
⚫ Parameterized Constructor ⚫ When any constructor has at least one parameter, it is
Default Constructor: called the parameterized constructor.
⚫ When constructors do not have parameters, then it is called the default ⚫ Example
constructor. class Car
⚫ These types of constructors have all its objects initialized with the same {
value. public string green;
⚫ Example
public Car(string color) //parameter is used
class Car
{
{
green= color;
public Car()
}
{
……..
}
}
}

Method Overloading- Compile time Different ways to overload the


Polymorphism method
⚫ A class has multiple methods having same name but
different in parameters, it is known as Method ⚫ There are two ways to overload the method in java
Overloading.
⚫ Example:
⚫ By changing number of arguments
⚫ Suppose we want to perform addition with same ⚫ Add(int,int) , add(int,int,int)
method name add()
⚫ By changing the data type
⚫ Different arguments are possible for the method
⚫ Add(float,int) , add(int,float,double)
such as add(int,int) for two parameters, and
add(int,int,int) for three parameters
Example program1- use objects Example program-2 use class name
⚫ class Addition ⚫ class Addition
⚫ { ⚫ {
⚫ static int add(int a,int b) ⚫ static int add(int a,int b)
⚫ { ⚫ {
⚫ return a+b; ⚫ return a+b;
⚫ } ⚫ }
⚫ static int add(int a,int b,int c) ⚫ static int add(int a,int b,int c)
⚫ { ⚫ {
⚫ return a+b+c; ⚫ return a+b+c;
⚫ } ⚫ }
⚫ } ⚫ }
⚫ Class Over ⚫ Class Over
⚫ { ⚫ {
⚫ public static void main(String[] args) ⚫ public static void main(String[] args)
⚫ { ⚫ {
⚫ Addition a=new Addition(); ⚫ System.out.println(addition.add(5,5);
⚫ System.out.println(a.add(5,5); ⚫ System.out.println(addition.add(100,100,100);
⚫ System.out.println(a.add(100,100,100); ⚫ }
⚫ } ⚫ }
⚫ } ⚫ O/p
⚫ O/p ⚫ 10
⚫ 10 ⚫ 300
⚫ 300

2m/3m-important example
⚫ Can we overload java main() method?
⚫ class mover
⚫ {
⚫ Yes, by method overloading. ⚫

public static void main(String[] args)
{
⚫ We can have any number of main methods in a class ⚫

System.out.println("main with String[]");
}
by method overloading. ⚫ public static void main(String args)

⚫ But JVM calls main() method which receives string
{
⚫ System.out.println("main with String");
⚫ }
array as arguments only. ⚫ public static void main()
⚫ {
⚫ System.out.println("main without args");
⚫ }
⚫ }
⚫ O/p
⚫ main with String[]
this keyword in Java Usage of Java this keyword

⚫ There can be a lot of usage of Java this keyword. ⚫ The 6 usage of java this keyword.
⚫ In Java, this is a reference variable that refers to the ⚫ this can be used to refer current class instance
current object. variable.
⚫ this can be used to invoke current class method
(implicitly)
⚫ this() can be used to invoke current class constructor.
⚫ this can be passed as an argument in the method call.
⚫ this can be passed as argument in the constructor call.
⚫ this can be used to return the current class instance
from the method.

Inheritance
⚫ Inheritance (Derived and Base Class)
⚫ It is possible to inherit attributes and methods from
Inheritance Cont..
one class to another. Or ⚫ For Example
⚫ The Car class (subclass) inherits the attributes and methods
⚫ It is a mechanism in which one object acquires all the from the Vehicle class (superclass)
properties and behaviors of a parent object. ⚫ Types
⚫ The "inheritance concept" into two categories: Class A
Father
⚫ superclass (parent) - the class being inherited from ⚫ Single Inheritance
⚫ subclass (child) - the class that inherits from another
class ⚫ Hierarchical Inheritance
⚫ Deriving the properties from super class to sub
⚫ Multiple Inheritance -Interface
class. Class B extends A

⚫ To inherit from a class, use the extends keyword.


Son/daugher
⚫ Multilevel Inheritance
Hierarchical Inheritance Syntax
1. class Subclass-name extends Superclass-name
FATHER 2. {
3. //methods and fields
4. }

SON - 1 SON - 2 SON - 3


Terms used in Inheritance Why use inheritance in java ?

• Class: ⚫ For Method Overriding


• A class is a group of objects which have common properties.
• It is a template or blueprint from which objects are created. (so runtime polymorphism can be achieved).
⚫ For Code Reusability.
• 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
to reuse the fields and methods of the existing class when you
create a new class.
• can use the same fields and methods already defined in the
previous class.

⚫ class Main
Example: Programs-single ⚫ {
inheritance ⚫ public static void main(String[] args)
⚫ class Animal
⚫ {
⚫ { ⚫ // create an object of the subclass


// field and method of the parent class
⚫ String name; Dog la= new Dog();


public void eat()
⚫ { // access field of superclass


System.out.println("I can eat");
⚫ } la.name = "Rownu";


}
⚫ // inherit from Animal la.display();

⚫ class Dog extends Animal
⚫ { // call method of superclass


// new method in subclass
public void display() ⚫ // using object of subclass


{
System.out.println("My name is " + name);
⚫ la.eat();
⚫ } ⚫ }
⚫ }
⚫ }
Hierarchical Inheritance Hierarchical Inheritance
⚫ When two or more classes inherits a single class, it is
known as hierarchical inheritance. FATHER

SON - 1 SON - 2 SON - 3

Example:Hierarchical Program-2
⚫ class parent
⚫ class Animal
⚫ {


⚫ void eat()
⚫ { {

⚫ protected static int num1= 15;
System.out.println("eating...");
⚫ }


}


class Dog extends Animal{
void bark(){System.out.println("barking...");}
protected static void methodA () //method


}
class Cat extends Animal{ ⚫ {

⚫ void meow(){System.out.println("meowing...");}
⚫ } System.out.println ("Value of protected


class TestInheritance3{
public static void main(String args[]){ variable num1 in Superclass = " + num1);
⚫ }
⚫ Cat c=new Cat();
⚫ c.meow();


⚫ c.eat();
⚫ //c.bark();//C.T.Error }
⚫ }}
⚫ class child1 extends parent
⚫ {

⚫ private static int num2 = 25;
class child2 extends parent
⚫ {
⚫ protected static void methodB () //Method ⚫

private static int num3 = 45;
public static void methodC () //method
⚫ { ⚫ {


System.out.println("Value of private variable num3 in Subclass2 is
System.out.println ("Value of private variable = " + num3);
⚫ }
num2 in Subclass1 is = " + num2); ⚫ public static void main(String args[])
⚫ System.out.println ("Value of protected ⚫ { child2 c2 = new child2 ();
⚫ c2.methodA(); //calling super class method
variable num1 in Superclass = " + num1); ⚫ c2.methodC(); //calling own method
⚫ } ⚫

child1 c1 = new child1 ();
c1.methodB();
⚫ } ⚫ }
⚫ }

Polymorphism Method Overloading- Compile time


⚫ can perform a single action in different ways.
⚫ Polymorphism is derived from 2 Greek words:
Polymorphism
⚫ poly and morphs. ⚫ A class has multiple methods having same name but
⚫ The word "poly" means many and "morphs" means forms. different in parameters, it is known as Method
⚫ So polymorphism means many forms. Overloading.
⚫ Example:
⚫ There are two types of polymorphism in Java: ⚫ Suppose we want to perform addition with same
⚫ compile-time polymorphism (Method Overloading) method name add()
⚫ runtime polymorphism. (method Overriding) ⚫ Different arguments are possible for the method
such as add(int,int) for two parameters, and
⚫ can perform polymorphism in java by method overloading add(int,int,int) for three parameters
and method overriding.
Method Overriding –Run time
Different ways to overload the polymorphism
method ⚫ subclass (child class) has the same method as declared in
the parent class, it is known as method overriding in Java.
⚫ There are two ways to overload the method in java
⚫ In other words, If a subclass provides the specific
implementation of the method that has been declared by
⚫ By changing number of arguments one of its parent class, it is known as method overriding.
⚫ Add(int,int) , add(int,int,int)
⚫ Usage of Java Method Overriding
⚫ By changing the data type
⚫ Method overriding is used to provide the specific
⚫ Add(float,int) , add(int,float,double)
implementation of a method which is already provided by
its superclass.
⚫ Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


Final keyword
⚫ The method must have the same name as in the ⚫ The final keyword in java is used to restrict the user.
parent class ⚫ The java final keyword can be used in many context.
⚫ The method must have the same parameter as in the ⚫ variable
parent class. ⚫ method
⚫ There must be an IS-A relationship (inheritance). ⚫ Class
Final keywrd Example-final keyword for variable
⚫ Can use final keyword with variables, methods, and ⚫ class G1{

classes. ⚫ // Main driver method
⚫ When the final keyword is used with a variable of ⚫ public static void main(String args[])
primitive data types such as int, float, etc). ⚫ {

⚫ The value of the variable cannot be changed. ⚫ // Final primitive variable
⚫ It will be a constant ⚫ final int i = 10;
⚫ i = 30; //i value is trying to be changed so
⚫ // Error will be generated above
⚫ }
⚫ }

2) Java final method

⚫ class Bike ⚫ If a any method is said to be final, that method cannot


⚫ {
⚫ final int speedlimit=90; //final variable
override it.
⚫ void run()
⚫ {
⚫ speedlimit=400;
⚫ }
⚫ public static void main(String args[])
⚫ {
⚫ Bike obj=new Bike9();
⚫ obj.run();
⚫ }
⚫ }
3) Java final class
Example- final keyword for method
⚫ If any class is said to be final, then that class cannot
⚫ class Bike{
⚫ final void run()
⚫ {


System.out.println("running");
}
use for inheritance. That means cannot extend it.
⚫ }

⚫ class Honda extends Bike
⚫ {
⚫ void run()
⚫ {
⚫ System.out.println("running safely with 100kmph");
⚫ }

⚫ public static void main(String args[]){
⚫ Honda honda= new Honda();
⚫ honda.run();
⚫ }
⚫ }

⚫ o/p
⚫ Compile time error– because final method

Is final method inherited? 2m/3m


⚫ final class Bike ⚫
⚫ { ⚫ Yes,
⚫ System.out.println(“Welcome to bike showroom”); ⚫ final method is inherited but that method cannot override it. For Example:


}
Example

⚫ class Honda1 extends Bike ⚫ class Bike
⚫ { ⚫ {
⚫ void run() ⚫ final void run()
⚫ { ⚫ {
⚫ System.out.println("running safely with 100kmph"); ⚫ System.out.println("running...");}
⚫ } ⚫ }

⚫ class Honda2 extends Bike


public static void main(String args[]){
⚫ Honda1 honda= new Honda1(); {
⚫ honda.run(); ⚫ public static void main(String args[])
⚫ } ⚫ {
⚫ } ⚫ new Honda2().run();
⚫ O/p ⚫ }
⚫ Compile time error because final keyword in class ⚫ }
Visibility Control-(controlling
access modifiers-2m/3m access to members of a class)
⚫ They are access modifiers and help us
implement Encapsulation (or information hiding).
⚫ They tell the compiler which other classes should have
access to the field or method being defined.
⚫ private - Only the current class will have access to the
field or method.
⚫ protected - Only the current class and subclasses
(and sometimes also same-package classes) of this
class will have access to the field or method.
⚫ public - Any class can refer to the field or call the
method

Visibility Control
⚫ Visibility
⚫ (controlling access to members of a class)
⚫ private visibility allows a variable to only be accessed by its class.

⚫ public class SomeOtherClass
They are often used in conjunction with public getters and setters

⚫ Example ⚫ {
⚫ class SomeClass ⚫ public static void main(String[] args)
⚫ { ⚫ {
⚫ private int variable; ⚫ SomeClass sc = new SomeClass();
⚫ public int getVariable() ⚫ // These statement won't compile because in SomeClass variable is
⚫ { private:
⚫ return variable; ⚫ sc.variable = 7;
⚫ } ⚫ System.out.println(sc.variable);
⚫ public void setVariable(int variable) ⚫ // Instead, you should use the public getter and setter:
⚫ { sc.setVariable(7);
⚫ this.variable = variable; ⚫ System.out.println(sc.getVariable());

⚫ }
}

⚫ }
}
Public Visibility
⚫ Visible to the class, package, and subclass
⚫ Example
⚫ public class Test
⚫ {
⚫ public int number = 2;
⚫ public Test()
⚫ {
⚫ }
⚫ }
⚫ public class Other
⚫ {
⚫ public static void main(String[] args)
⚫ {
⚫ Test t = new Test();
⚫ System.out.println(t.number);
⚫ }
⚫ }

Protected Visibility
⚫ Protected visibility causes means that this member is visible to its package, along with


any of its subclasses.
Example:
Simple programs-tutorial week 6
⚫ class Animal ⚫ 1.Create a class named 'Person' with the following
⚫ {
⚫ Data members:
⚫ // protected method
⚫ Name
⚫ protected void display()
⚫ Age
⚫ {
⚫ Phone number
⚫ System.out.println("I am an animal");
⚫ } ⚫ Location
⚫ } ⚫ Method:
⚫ class Dog extends Animal ⚫ Person_information
⚫ { ⚫ Note:
⚫ public static void main(String[] args) ⚫ Create a class ‘employee’ which is inherits from ‘person’ class which will hold the
⚫ { method as ‘display details’ and data members as ‘department and designation.
⚫ // create an object of Dog class ⚫ Create a class ‘salary’ which inherits from employee class and hold the method
⚫ Dog dog = new Dog(); ‘net_pay’ and data member salary.
⚫ ⚫ Create an object for ‘salary’ class and invoke all the method associated to classes.
⚫ // access protected method
⚫ dog.display();
⚫ }
⚫ }
⚫ 2. Create a class called hostelwith the following. ⚫ 3. Create a class called Rectangle with the following

⚫ Data Members:
Data Members:
⚫ Hostel Rent
⚫ Mess bill ⚫ Length
⚫ Wi-Fi charges ⚫ Breadth
⚫ Warden fine ⚫ Area
⚫ Methods ⚫ Perimeter
⚫ To calculate the total monthly expense for an hostel
⚫ To display all the values. ⚫ Methods
⚫ Note: ⚫ To calculate the area of a rectangle
⚫ Use instance methods for setting and retrieving values. ⚫ To Calculate the perimeter of a rectangle
⚫ Instantiate an object to activate the class and their members and ⚫ To display the values
method.

Why multiple inheritance is not


Multiple inheritance
supported in Java?2m/3m
⚫ In Java, a class cannot extend more than one class.
⚫ Therefore following is illegal
⚫ Example
⚫ public class extends Animal, Mammal
⚫ {
⚫ }
Interface
Cont.. ⚫ An interface is an abstract type used to specify the behavior of a
⚫ A class can implement one or more interfaces, which has
class
helped Java get rid of the impossibility of multiple ⚫ An interface in Java is a blueprint of a class.
inheritances. ⚫ It has static constants and abstract methods.
⚫ The reason behind this is to prevent ambiguity.
⚫ Example: ⚫ It is used to achieve abstraction and multiple inheritances in
⚫ Consider a case where class B extends class A and Class C Java.
and both class A and C have the same method display().
⚫ The interface in Java is a mechanism to achieve abstraction.
⚫ Now java compiler cannot decide, which display method it
should inherit. ⚫ There can be only abstract methods in the Java interface, not
⚫ To prevent such situation, multiple inheritances is not method body.
allowed in java. ⚫ Java Interface also represents the IS-A relationship.

Why use Java interface? How to declare an interface?


⚫ There are mainly three reasons to use interface.
⚫ It is used to achieve abstraction.
⚫ By interface, we can support the functionality of ⚫ An interface is declared by using the interface
multiple inheritance. keyword.
⚫ It can be used to achieve loose coupling.(independent) ⚫ It provides total abstraction;
⚫ Which 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> ⚫ Interface fields are public, static and final by default,
⚫{ and the methods are public and abstract

⚫ // declare constant fields
⚫ // declare methods that abstract
⚫ // by default.
⚫}

The relationship between classes


and interfaces
Example
⚫ a class extends another class,
⚫ interface printable
⚫ {
⚫ an interface extends another interface, ⚫

void print();
}
⚫ but a class implements an interface. ⚫

class A implements printable //implements keyword
{
⚫ public void print()
⚫ {
⚫ System.out.println(“Welcome");
⚫ }
⚫ public static void main(String args[])
⚫ {
⚫ A obj = new A();
⚫ obj.print();
⚫ }
⚫ }
Multiple inheritance in Java by What is marker or tagged
interface interface? 2m/3m
⚫ If a class implements multiple interfaces, or an ⚫ An interface which has no member is known as a
interface extends multiple interfaces. marker or tagged interface,
⚫ It is known as multiple inheritance. ⚫ for example, Serializable, Cloneable, Remote, etc.
⚫ They are used to provide some essential information to
the JVM so that JVM may perform some useful
operation.
⚫ //How Serializable interface is written?
⚫ public interface Serializable
⚫ {
⚫ }

Nested Interface in Java

⚫ Note: An interface can have another interface which is


known as a nested interface.
⚫ For example:
⚫ interface printable
⚫ {
⚫ void print();
⚫ interface MessagePrintable{
⚫ void msg();
⚫ }
⚫ }
Built-in package vs user-defined package
Packages ⚫ Built-in package: (System Packages)
⚫ A package in Java is used to group related classes. ⚫ packages from the Java API
⚫ Example: ⚫ java, lang, awt, javax, swing, net, io, util, sql etc.
⚫ A folder with related files ⚫ Import keyword
⚫ Definition: ⚫ Syntax
⚫ A java package is a group of similar types of classes, ⚫ import package name. Class; // Import a single class
⚫ import package name.*; // Import the whole package
interfaces and sub-packages
⚫ Scanner keyword
⚫ Types:
⚫ Scanner is used to get user input.
⚫ Package is categorized in two forms
⚫ Syntax
⚫ Built-in package (System packages)
⚫ import java.util.Scanner;
⚫ user-defined package.
⚫ java.util is a package, while Scanner is a class of
the java.util package.

Built-in Packages
⚫ These packages consist of a large number of classes which are a part of
Java API.
⚫ Some of the commonly used built-in packages are:
⚫ 1) java.lang:
Packages-
⚫ Contains language support classes(e.g classed which defines primitive data types,
math operations). ⚫ java.lang − bundles the fundamental classes
⚫ This package is automatically imported.
⚫ 2) java.io:
⚫ Contains classed for supporting input / output operations.
⚫ 3) java.util:
⚫ java.io − classes for input , output functions are
⚫ Contains utility classes which implement data structures like Linked List, bundled in this package
Dictionary and support ; for Date / Time operations.
⚫ 4) java.applet:
⚫ Contains classes for creating Applets.
⚫ 5) java.awt:
⚫ Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
⚫ 6) java.net:
⚫ Contain classes for supporting networking operations.
user-defined package
Syntax
⚫ user-defined package ⚫ package package_name;
⚫ create your own packages.
⚫ Java uses a file system directory to store them. Just like ⚫ Example
⚫ package mypack;
folders on your computer:
⚫ Example
⚫ └── root
⚫ └── mypack
⚫ └── MyPackageClass.java
⚫ To create a package, use the package keyword

Usage of Packages
⚫ To avoid name conflicts
Example ⚫ Example
⚫ Two classes with name Employee in two packages,
⚫ package mypack; college.staff.cse.Employee
⚫ class MyPackageClass college.staff.ece.Employee
⚫ To write a better maintainable code.
⚫ {
⚫ To Make easier to searching/locating and usage of classes,
⚫ public static void main(String[] args) interfaces and enumerations easier
⚫ { ⚫ To Provide controlled access
⚫ Example:
⚫ System.out.println("This is my package!");
⚫ Protected and default have package level access control.
⚫ } ⚫ A protected member is accessible by classes in the same package

⚫ } and its subclasses


⚫ A default member (without any access specifier) is accessible by
classes in the same package only.
Advantage of Java Package
System packages(built-in) example
⚫ 1) Java package is used to categorize the classes and
interfaces so that they can be easily maintained.

⚫ 2) Java package provides access protection.

⚫ 3) Java package removes naming collision.

Package : Naming Conversions Naming Conventions cont..


⚫ It should be a lowercase letter such as java.lang.
⚫ Package names are written in all lower case to avoid
⚫ If the name contains multiple words, it should be
conflict with the names of classes or interfaces.
separated by dots (.) such as
⚫ Companies use their reversed Internet domain
⚫ java.util.Date
name to begin their package names.
⚫ java.lang
⚫ For example
⚫ Example ⚫ com.example.mypackage
package maths.test; ⚫ For a package named mypackage created by a
class marks programmer at example.com.
{
//code
}
Naming Conventions cont.. Package creation
⚫ To create a package use keyword package.
⚫ Use package name after package keyword.
⚫ Syntax:
⚫ package pack1;

⚫ package -> package keyword to create a package


⚫ pack1 –> package name

Package creation Program


Sample.java Test.java
⚫ package pack1; // package declaration ⚫ import pack1.Sample; // use package by import keyword
⚫ public class Sample //class declaration ⚫ public class Test // class declaration
⚫ { ⚫ {
⚫ public void print() //method declaration ⚫ public static void main(String args[])
⚫ { ⚫ {
⚫ System.out.println("class imported from package 1"); ⚫ Sample obj = new Sample(); //object creation
⚫ } ⚫ obj.print(); // calling method by an object
⚫ } ⚫ }
⚫ }
To Compile Output
⚫ javac –d . Sample.java //package class compilation
⚫ javac –d . Test.java // main class compilation
⚫ Package creation

⚫ To run
⚫ java Test // run main class

Program-MathOperations.Java
⚫ package arithmetic; // package creation
⚫ public class MathOperations // class creation and definition
⚫ {

Packages ⚫

public int addition (int a, int b) // method definition
{

⚫ 6. B)
return a + b;
PROGRAM TO PERFORM ARITHMETIC ⚫ }

OPERATION USING PACKAGES ⚫
public int subtraction (int a, int b)
{
⚫ return a - b;
⚫ }
⚫ public int multiplication (int a, int b)
⚫ {
⚫ return a * b;
⚫ }
⚫ public int division (int a, int b)
⚫ {
⚫ return a / b;
⚫ }
⚫ public int mod (int a, int b)
⚫ {
⚫ return a % b;
⚫ }
⚫ }
MathTest.java
⚫ import arithmetic.MathOperations; // Package import (use pakage) ⚫ int sum=obj.addition(n1,n2);
⚫ import java.util.*; // util package ⚫ int diff=obj.subtraction(n1,n2);
⚫ class MathTest ⚫ int prod=obj.multiplication(n1,n2);
⚫ { ⚫ int quot=obj.division(n1,n2);
⚫ public static void main(String args[]) ⚫ int rem=obj.mod(n1,n2);
⚫ { ⚫ System.out.println("Sum= " + sum);
⚫ Scanner input=new Scanner(System.in);
⚫ System.out.println("Difference= " + diff);
⚫ System.out.println("Enter the first number:");
⚫ int n1=input.nextInt(); //read values from user ⚫ System.out.println("Product= " + prod);
⚫ System.out.println("Enter the second number:"); ⚫ System.out.println("Quotient= " + quot);
⚫ int n2=input.nextInt(); //read values from user ⚫ System.out.println("Remainder= " + rem);
⚫ MathOperations obj=new MathOperations(); ⚫ }
⚫ ⚫ }

Output System Packages


⚫ Built in packages are called system packages.
⚫ packages from the Java API
⚫ java, lang, awt, javax, swing, net, io, util, sql etc.
Adding class to a packages
⚫ Adding Classes to Packages
⚫ In order to add Java classes to packages, do two things:
⚫ Put the Java source file inside a directory matching the
Java package.
⚫ Declare that class as part of the package.

⚫ Package program to display the students results


Example
⚫ //Student.java ⚫ public void show() //method definition
⚫ package student; //package creation ⚫ {
⚫ class Student
⚫ { ⚫ System.out.println(“Roll No :: ” + rollno);
⚫ private int rollno; ⚫ System.out.println(“Name :: ” + name);
⚫ private String name; ⚫ System.out.println(“Address :: ” + address);

⚫ }
private String address;
⚫ public Student(int rno, String sname, String sadd)
⚫ { //Parameterized construuctor Student ⚫}
⚫ rollno = rno;
⚫ name = sname;
⚫ address = sadd;
⚫ }
⚫ // Test.java
⚫ package student; //using student package
⚫ class Test extends Student // single inheritance concept used
⚫ {
⚫ protected int marksSubject1; ⚫ public void show()


protected int marksSubject2;
⚫ protected int marksSubject3; {
⚫ protected int marksSubject4; ⚫ super.show(); //shows rollno,name and address of student
⚫ public Test(int rno, String sname, String sadd,int mi, int m2, int m3, int ⚫ System.out.println(“Marks of Subject1 :: ” + marksSubject1);
m4) // Parameterized constructor -Test
⚫ { ⚫ System.out.println(“Marks of Subject2 :: ” + marksSubject2);
⚫ super(rno,sname,sadd); //super keyword ⚫ System.out.println(“Marks of Subject3 :: ” + marksSubject3);


/*The super keyword in Java is a reference variable which is used to refer
immediate parent class object. */ System.out.println(“Marks of Subject4 :: ” + marksSubject4);
⚫ //It will call super class constructor and method ⚫ }
⚫ marksSubject1 = mi; ⚫ }
⚫ marksSubject2 = m2;
⚫ marksSubject3 = m3;
⚫ marksSubject4 = m4;
⚫ }

//Result.java
⚫ totalMarks = marksSubject1 + marksSubject2 +
⚫ package student; // use package marksSubject3 + marksSubject4;
⚫ public class Result extends Test // multilevel inheritance ⚫ percentage = (totalMarks*100.00F/600.00F);
⚫ { ⚫ if (percentage >=50.00F)
⚫ private int totalMarks; ⚫ grade=’D’;
⚫ else
⚫ private float percentage;
⚫ if(percentage >=55.00F && percentage<=60.00F)
⚫ private char grade; ⚫ grade = ‘C’;
⚫ public Result(int rno, String sname, String sadd,int mi, int ⚫ else
m2, int m3, int m4) //parameterized constructor Result ⚫ if (percentage >=6l.00F && percentage<=70.00F)
⚫ { ⚫ grade = ‘B’;
⚫ super(rno,sname,sadd,ml,m2,m3,m4); //super method ⚫ else
⚫ if(percentage >=7l.00F && percentage<=75.00F)
⚫ grade = ‘A’;
⚫ else //Demo.java
⚫ if (percentage >=76.00F && percentage<=85.00F)
⚫ grade = ‘H’;
⚫ else ⚫ import student.Result; //import student package
⚫ grade = ‘S’; ⚫ public class Demo
⚫ } ⚫ {
⚫ public void show()
⚫ { ⚫ public static void main(String ar[])
⚫ super.show(); // It will show Test class show method ⚫ {
⚫ System.out.println(“Total Marks :: ” + totalMarks); ⚫ Result ob = new Result (1001, “Alice”, “New
⚫ System.out.println(“Percentage :: ” + percentage); York”,135,130,132,138);
⚫ System.out.println(“Grade :: ” + grade); ⚫ ob.show (); // display result show method
⚫ } ⚫}

⚫}
}

How to access package from


1) Using packagename.*
another package? ⚫ package.*
⚫ It will include all the classes and interfaces of this package will
⚫ There are three ways to access the package from
be accessible but not sub packages.
⚫ The import keyword is used
outside the package. ⚫ Example
⚫ import package.*; ⚫ import pack1.*; // use package
⚫ public class Test // class declaration
⚫ import package.classname; ⚫ {
⚫ Fully qualified name. ⚫ public static void main(String args[])
⚫ {
⚫ Sample obj = new Sample(); //object creation
⚫ obj.print(); // calling method by an object
⚫ }
⚫ }

2.Using packagename.classname 3. Fully qualified name.

⚫ import pack1.Sample; // use package ⚫ package pack1; // package declaration


⚫ public class Test // class declaration ⚫ public class Sample //class declaration
⚫ { ⚫ {
⚫ public static void main(String args[]) ⚫ public void print() //method declaration
⚫ {
⚫ {
⚫ Sample obj = new Sample(); //object creation
⚫ System.out.println("class imported from package 1");
⚫ obj.print(); // calling method by an object
⚫ } ⚫ }
⚫ } ⚫ }

Errors Compile time errors
⚫ Errors are mistakes that can make a program go wrong ⚫ All syntax errors will be detected and displayed by the
⚫ An Error may produce an incorrect output or java compiler.


Example
It may terminate the execution.
⚫ class Error
⚫ It is important to detect and correct errors.
⚫ {


Types of errors:
public static void main(String args[])
⚫ Compile time errors (Syntax Errors)
⚫ {
⚫ Run time errors (Wrong logic, stack overflow) ⚫ System.out.println(“Hello”) // ; missing
⚫ }
⚫ }

Compile time errors Run time errors


⚫ Missing semicolon ⚫ A program may compile successfully creating .class file
⚫ Missing brackets but may not run properly .
⚫ misspelling of keywords ⚫ Such programs produce wrong result is called as run
⚫ Missing double quotes time errors.
⚫ Use of undeclared variables
⚫ Incompatible types of augments
⚫ Bad reference to object
⚫ Operator mismatch
Run time errors ⚫ class error
⚫{
⚫ Dividing an integer by zero ⚫ public static void main(string args[])
⚫ Array index out of bound ⚫ {
⚫ Store an array in incompatible class or type ⚫ int a=10;


int b=5;
Passing parameter that is not in a valid range ⚫ int c=5;
⚫ Attempting to use a negative size of an array ⚫ int x=a/(b-c); //(10/(5-5) -> 10/0 [Error]
⚫ Converting invalid string to a number and vice versa ⚫ System.out.println(“x=” +x);


}
Accessing a character that is out of bounds of a string. ⚫ }
⚫ And so on.

Exception
⚫ Exception is an abnormal condition.
⚫ An exception is a condition that causes Run time errors in
the program.
⚫ coding errors made by the programmer.
⚫ Java interpreter encounters an error ,it create an exception
object and throws it(inform us that an error has occurred)
⚫ Exception Handling
Advantage of Exception Handling ⚫ It is a mechanism to handle runtime errors such as
⚫ ClassNotFoundException,
⚫ IOException,

⚫ To maintain the normal flow of the application ⚫ SQLException,


⚫ RemoteException, etc.
Types of Java Exceptions

⚫ Checked Exception ⚫ Checked Exception


⚫ Unchecked Exception ⚫ The classes that directly inherit the Throwable class
except RuntimeException.
⚫ For example:
⚫ IOException,
⚫ SQLException, etc.
⚫ Checked exceptions are checked at compile-time.

Unchecked Exception
⚫ The classes that inherit the RuntimeException are
known as unchecked exceptions.
⚫ For example,
⚫ ArithmeticException,
⚫ NullPointerException,
⚫ ArrayIndexOutOfBoundsException, etc.
⚫ Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
Java Exception Keywords Throws vs throw 2m/3m
⚫ try
⚫ specify a block of code where should place an exception code
⚫ catch
⚫ The "catch" block is used to handle the exception
⚫ Finally
⚫ The "finally" block is used to execute the necessary code of the
program
⚫ Throw
⚫ The "throw" keyword is used to throw an exception.
⚫ Throws-
⚫ The "throws" keyword is used to declare exceptions.
⚫ It specifies that there may occur an exception in the method.
⚫ It doesn't throw an exception.
⚫ It is always used with method signature.
Throws vs throw syntax
⚫ try
⚫ {
⚫ // Block of code to try
⚫ }
⚫ catch (Exception e)
⚫ {
⚫ // Block of code to handle errors
⚫ }

Try catch
⚫ Try ⚫ Catch
⚫ The try statement allows you to define a block of code ⚫ The catch statement allows you to define a block of
to be tested for errors while it is being executed. code to be executed, if an error occurs in the try block.
⚫ try //try block operation ⚫ catch (ArithmeticException e)
⚫ { ⚫ {
⚫ result = num1 / num2; ⚫ System.out.println(e);
⚫ } ⚫ }
Finally throw
⚫ Finally ⚫ Used to throw own exceptions.
⚫ Used to handle the exception ⚫ Using throw keyword.
⚫ The finally statement lets you execute code, ⚫ Syntax:
after try...catch, regardless of the result: ⚫ throw new throwable_subcclass
⚫ finally //final statement to print result ⚫ Example:
⚫ { ⚫ throw new AgeInvalidException(-----)
⚫ int result=a[1]/a[0];
⚫ system.out.println ("Result: ", result);
⚫ }

Multiple catch-syntax
⚫ try

Multiple catch statements-3m ⚫

{
---------
}
//generate exception

⚫ Possible to have one or more catch statements in the ⚫ catch (Exception type-1 e)
⚫ {
catch block ⚫ ------- // process exception type 1
⚫ }
⚫ catch(Exception type-2 e)
⚫ {
⚫ --------- // process exception type 2
⚫ }
⚫ .
⚫ .
⚫ catch(Exception type-N e)
⚫ {
⚫ --------- // process exception type N
⚫ }
Multiple catch statements-3m ⚫ catch(ArithmeticException e)
⚫ {
Example program ⚫ System.out.println(“Divided by zero”);

⚫ class error
}
⚫ catch(ArrayIndexOutOfBoundException e)
⚫{ ⚫ {
⚫ public static void main(String args[]) ⚫ System.out.println(“Array index error”);

⚫ { }
⚫ catch(ArrayStoreException e)
⚫ int a[ ]={5,10}; ⚫ {
⚫ int b=5; ⚫ System.out.println(“Wrong Data type”);
⚫ try ⚫ }


int y=a[1]/a[0];
{ ⚫ System.ot.println(“y=“ +y);
⚫ int x= a[2]/5-a[1]; ⚫ }
⚫ } ⚫ }

Using Finally statement-Program


Output ⚫ class error
⚫{
⚫ public static void main(String args[])
⚫ {
⚫ int a[ ]={30,10};
⚫ int b=5;
⚫ try
⚫ {
⚫ int x= a[2]/5-a[1];
⚫ }
⚫ catch(ArithmeticException e)



{

}
System.out.println(“Divided by zero”); Output
⚫ catch(ArrayIndexOutOfBoundException e)
⚫ {
⚫ System.out.println(“Array index error”);
⚫ }
⚫ catch(ArrayStoreException e)
⚫ {
⚫ System.out.println(“Wrong Data type”);
⚫ }
⚫ finally
⚫ {
⚫ int y=a[0]/a[1];
⚫ System.ot.println(“y=“ +y);
⚫ }
⚫ }
⚫ }

User defined Exception Tutorial week 7


⚫ User Defined Exception or custom exception ⚫ 1. Write a java program to find the cube, square,cube
⚫ It is used to create your own exception class and root and square root of a number
throws that exception using ‘throw’ keyword.
⚫ This can be done by extending the class Exception. ⚫ 2. Write a java program for user defined exception to a
license for 2 wheeler and 4 wheeler.
Example programs for user defined
exception
Creating Threads
Thread
⚫ A thread in Java is the direction or the path followed ⚫ Two ways to Create a thread
when executing a program. ⚫ By implementing Runnable interface and
⚫ By extending thread a class.
⚫ All the programs have at least one thread, known as ⚫ Every Java thread is created and controlled by
the main thread. the java.lang.Thread class.
⚫ Types
⚫ That is provided by the JVM or Java Virtual Machine at ⚫ Single thread
the starting of the program’s execution. ⚫ Multi thread

Multi thread usage Multi thread


⚫ For faster processing of background/batch tasks
⚫ To take advantage of modern processors
⚫ For reducing response times
⚫ To serve multiple users at the same time
Single vs multi thread Life cycle of a thread
⚫ single-thread: ⚫ A thread goes through various stages in its life cycle.
⚫ A single-threaded application has only one thread and For example,
can handle only one task at a time. ⚫ A thread is born,
⚫ Multi thread: ⚫ started,
⚫ To handle multiple tasks in parallel, multi-threading is ⚫ runs, and

used.
then dies.
⚫ multiple threads are created, each performing a different
task.

Life cycle of a Thread (Thread


Life cycle of a thread-simple
States)
explanation ⚫ A thread can have five different states, during its life time a
thread is always in any one of these states and can move from
one state to another.
⚫ In Java, a thread always exists in any one of the following
states.
⚫ These states are:
⚫ 1. Newborn state
⚫ 2. Runnable state
⚫ 3. Running state
⚫ 4. Blocked state
⚫ 5. Dead state
Life cycle of a thread cont..
Life cycle of a thread cont.. 10m ⚫ Newbornstate:
⚫ A newborn state is a state when a thread object is
created, and is not yet scheduled for running.
⚫ It can move to runnable state using start() method or
move to dead state using stop() method.
⚫ 2. Runnable state:
⚫ The runnable state means the thread is ready for the
execution and waiting for processor.
⚫ 3. Running state:
⚫ In this state the processor has given the time to the
thread for execution.
⚫ From this state, thread enters into blocked (when
suspend(),sleep(), or wait() is called ) or dead state
(when stop() is called).

Defining & Running Threads in 4 steps



Life cycle of a thread cont.. ⚫
The thread can be defined by extending the Thread class.
1. Define subclasses by extending the Thread class

⚫ 4. Blocked state: ⚫ class classname extends Thread


⚫ {
⚫ If we preventing the thread from entering into ⚫ }
runnable/running state then this state called as blocked
state. ⚫ 2. Override the run() method in all subclasses.
⚫ It goes to Runnable state when resume(),notify() is ⚫ public void run ( )
called or specified time expires. ⚫ {
⚫ 5. Dead state: ⚫ }

⚫ When a thread has completed its execution using run()


⚫ 3. Create thread object in the main() method
method it is called the natural death. ⚫ classname object = new classname();
⚫ And when we stopped or moved a thread to dead state
by calling stop() method it causes a premature death. ⚫ 4. Call the start method using the thread object.
⚫ Object.start();
Example- odd and even numbers printing
Java Thread Example by
⚫ class Even extends Thread //step 1
⚫ {
⚫ public void run() //step 2

extending Thread class


⚫ {
⚫ for(int i=0; i<=10; i=i+2)
⚫ System.out.println("Even number: "+i);
⚫ }
class Single extends Thread // Step 1 ⚫ }
⚫ class Odd extends Thread //step 1
{ ⚫ {
public void run() // Step 2 ⚫ public void run() //step 2
{ ⚫ {
System.out.println("thread is running..."); ⚫ for(int j=1; j<=10; j=j+2)
⚫ System.out.println("Odd number: "+j);
} ⚫ }
public static void main(String args[]) ⚫ }
{

Single s1=new Single(); // Step 3 public class Example
⚫ {
s1.start(); // Step 4 ⚫ public static void main(String args[ ])
} ⚫ {
} ⚫ Even e1 = new Even(); //step 3
⚫ Odd o1 = new Odd(); //Step 3

⚫ o/p
e1.start(); // Step 4

⚫ thread is running…
o1.start(); //Step 4
⚫ }
⚫ }

Commonly used methods of


Thread class:
⚫ public void setName(String name): changes the name of
the thread.
⚫ public void run(): is used to perform action for a
thread. ⚫ public Thread currentThread(): returns the reference of
⚫ public void start(): starts the execution of the thread. currently executing thread.
⚫ JVM calls the run() method on the thread.
⚫ public void sleep(long milliseconds): Causes the ⚫ public int getId(): returns the id of the thread.
currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds. ⚫ public Thread.State getState(): returns the state of the

thread.
public void join(): waits for a thread to die.
⚫ public void join(long milliseconds): waits for a ⚫ public boolean isAlive(): tests if the thread is alive.
thread to die for the specified milliseconds.
⚫ public int getPriority(): returns the priority of the
⚫ public void yield(): causes the currently executing thread
thread. object to temporarily pause and allow other threads to
⚫ public int setPriority(int priority): changes the execute.
priority of the thread.
⚫ public void suspend(): is used to suspend the thread.
⚫ public void resume(): is used to resume the suspended Common Thread methods
thread.
⚫ public void stop(): is used to stop the thread.
⚫ public boolean isDaemon(): tests if the thread is a
daemon thread.(less priority thread)
⚫ public void setDaemon(boolean b): marks the thread
as daemon or user thread.
⚫ public void interrupt(): interrupts the thread.
⚫ public boolean isInterrupted(): tests if the thread has
been interrupted.
⚫ public static boolean interrupted(): tests if the
current thread has been interrupted.

Runnable interface:
Thread class ⚫ The Runnable interface should be implemented by any
class whose instances(objects) are intended to be
⚫ Thread class provide constructors and methods to executed by a thread.
create and perform operations on a thread. ⚫ Runnable interface have only one method named run().
⚫ Thread class extends Object class and implements public void run(): is used to perform action for a
Runnable interface. thread.
⚫ Commonly used constructors of thread class ⚫ Starting a thread:
• Thread() ⚫ The start() method of Thread class is used to start a
newly created thread. It performs the following tasks:
• Thread(String name)
• A new thread starts(with new call stack).
• Thread(Runnable r)
• The thread moves from New state to the Runnable state.
• Thread(Runnable r,String name) • When the thread gets a chance to execute, its target run()
method will run.
java Thread Example by
Steps for implementing Runnable implementing Runnable
Interface interface
⚫ The thread can be defined by implementing Runnable interface class Single2 implements Runnable //Step 1
⚫ 1. Define classes by implementing Runnable interface
⚫ class classname implements Runnable
{
⚫ { public void run() // Step 2
⚫ } {
⚫ 2. Override the run() method in all subclasses.
System.out.println("thread is running...");
⚫ public void run ( ) }
⚫ { public static void main(String args[])
⚫ }
{
⚫ 3. Create thread object in the main() method Single2 m1=new Single2(); // class object creation , Step 3
⚫ classname object = new classname();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
⚫ 4. Use Thread Constructor(use any one) and create an thread class object and
⚫ pass the object to thread class //Step 4
⚫ Thread obj1= new Thread("My first thread"); or t1.start(); // Step 5
Thread obj1 = new Thread(object);
}
⚫ 5. Call the start method using the Runnable constructor Thread object. }
⚫ obj1.start(); ⚫ o/p
⚫ thread is running…

Using the Thread Class:


Thread(String Name)
Thread constructors example pgms public class MyThread1
{
• Thread() // Main method
public static void main(String args[])
• Thread(String name) {
// creating an object of the Thread class using the
• Thread(Runnable r) //constructor Thread(String name)
Thread t= new Thread("My first thread");
• Thread(Runnable r,String name) // the start() method moves the thread to the active state
t.start();
// getting the thread name by invoking the getName() method
String str = t.getName(); // str will store String name in constructor
System.out.println(str);
}
}
⚫ o/p
⚫ My first thread
Using the Thread Class:
Thread(Runnable r, String
name)
public class Thread2 implements Runnable
{
public void run()
{
System.out.println("Now the thread is running ...");
}
// main method
public static void main(String argvs[])
{
// creating an object of the class Thread2
Thread2 r1 = new Thread2();

// creating an object of the class Thread using


//Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");
// getting the thread name by invoking the getName()
String str = th1.getName();
System.out.println(str);
// the start() method moves the thread to the active state
th1.start();
}
}
O/p
My new thread
Now thread is running…
Stopping and blocking thread Blocking a thread
Stopping a thread ⚫ A thread can be temporarily suspended or blocked
from entering into the runnable and subsequently
⚫ stop()- method is used to stop the thread . running state by using either of the following 3
methods.
⚫ aThread.stop()
⚫ sleep()
⚫ This cause the thread move to the dead state,
⚫ suspend()
⚫ wait()

Thread Exception Thread Exceptions


⚫ Exceptions are the events that occur due to the ⚫ sleep() method is enclosed in try block and followed
programmer error or machine error which causes a by catch block.
disturbance in the normal flow of execution of the ⚫ sleep() method throws an exception
program. ⚫ It will throw IllegalThreadException.
⚫ When a method encounters an abnormal condition ⚫ Sleeping thread can not deal with the resume()
that it can not handle, an exception is thrown as an method because sleeping thread can not receive any
exception statement. instruction.
⚫ Same for Suspend() method.
⚫ Catch (ThreadDeath e) ⚫ Catch (IllegalArgumentException e)
⚫ { ⚫ {
⚫ ------- //Killed thread ⚫ -------
⚫ ------- ⚫ ------- //cannot handle it in the current state

⚫ } }


Catch (Exception e)
Catch (InterruptException e)
⚫ {
⚫ {
⚫ ------ // Illegal method argument
⚫ ------ ⚫ ------
⚫ ------ ⚫ }
⚫ }

Exception handling program without giving start method


⚫ Two types of exception may happen. They are ⚫ In main program start() method is not given to run the
thread. So that thread exception occur.
⚫ 1. without giving start() method
⚫ 2. using sleep() in try block
Exception with sleep ()
⚫ sleep() method of thread class is used where there is a ⚫ Exception: It does often throws out exceptions as java
demand to sleep the thread for a particular period of language being involving the concept of
time for the proper workflow of the code. multithreading
⚫ Syntax: ⚫ IllegalArgumentException is thrown when the
⚫ public static void sleep(long milliseconds) ; parametric value is negative as it is bounded as
⚫ public static void sleep(long milliseconds, int discussed between [0 — +999999]
nanoseconds) ;
⚫ InterrupteException is thrown when a thread is
interrupted with an ongoing thread.

Thread Priority Synchronization


⚫ Each thread is assigned a priority. ⚫ capability to control the access of multiple threads
⚫ Using setPriority() method. those are sharing resource.
⚫ ThreadName.setPriority(int number); ⚫ It allow only one thread to access the shared resource.
⚫ number – we can assign numbers 1 to 10. ⚫ The synchronization is mainly used to
⚫ MINIMUM PRIORITY= 1 ⚫ To prevent thread interference.
⚫ To prevent consistency problem.
⚫ NORM_PRIORITY =5 (default)
⚫ MAX_PRIORITY=10 ⚫ Types of Synchronization
⚫ Process Synchronization- OS
⚫ Thread Synchronization -Java
Thread Synchronization Java Synchronized Method
⚫ There are two types of thread synchronization ⚫ Method declared as synchronized, it is known as
⚫ mutual exclusive synchronized method.
⚫ inter-thread communication. ⚫ Synchronized method is used to lock an object for any
shared resource.
Mutual Exclusive ⚫ When a thread invokes a synchronized method, it
⚫ Only one thread can perform or run at a time automatically acquires the lock for that object and
⚫ It can be achieved by using the following three ways: releases it when the thread completes its task.
⚫ Synchronized Method ⚫ Synchronized keyword is used.
⚫ Synchronized Block
⚫ Static Synchronization

Syntax Thread A
synchronized void update() Synchronized method1()
{
{ Synchronized method2()
--------- {
---------
} }
}

Thread B
synchronized (lock object) Synchronized method1()
{
{ Synchronized method2()
--------- ---------
} }
}
Example class MyThread1 extends Thread
class Table {
{
synchronized void printTable(int n) //synchronized method (Step-6) Table t; //object creation for table class
{ MyThread1(Table t) //parameterized constructor
for(int i=1;i<=5;i++) (-step 2)
{
System.out.println(n*i); // print table values (step-7)
{
try this.t=t; //reference variable that refers to the current
{ object of a method or a constructor.
Thread.sleep(400); //thread is in sleep mode for 400 milliseconds }
}
catch(Exception e)
public void run() (Step-4)
{ {
System.out.println(e); t.printTable(5); //invoke printable method
}
}
}
}
} }

public class TestSynchronization


class MyThread2 extends Thread {
{
Table t; //object creation for table class public static void main(String args[])
MyThread2(Table t) //parameterized constructor 2nd thread step 2 {
{ Table obj = new Table();
this.t=t; //reference variable that refers to the current object of a MyThread1 t1=new MyThread1(obj);
method or a constructor.
} //invoke MyThread1 constructor (Step-1)
public void run() 2nd thread step 4 t1.start(); // Create thread and invoke run() in MyThread 1 (
{ Step-3)
t.printTable(10); //invoke printable method
MyThread2 t2=new MyThread2(obj);
}
} //invoke MyThread1 constructor
t2.start(); // Create thread and invoke run() in MyThread 2
}
}
⚫ Cooperation (Inter-thread communication in java)
Output ⚫ Exchange of message between two or more threads.
⚫ It used 3 methods
⚫ 5 ⚫ notify()
⚫ 10 ⚫ Resume the first thread that went into sleep mode.
⚫ 15 ⚫ final void notify();
⚫ 20 ⚫ notifyall()
⚫ Resume all the thread that went into sleep mode.
⚫ 25
⚫ final void notifyall();
⚫ 10
⚫ wait()
⚫ 20 ⚫ Sends the calling thread into the sleep mode.
⚫ 30 ⚫ This thread can be active by only notify () and notifyall()
⚫ 40 methods.
⚫ 50 ⚫ final void wait()

Swings
⚫ Basic swing components:
Unit-4 -THREADS AND SWINGS ⚫ JLabel,
⚫ JTextField,
⚫ Creating Threads ⚫ JTextArea,
⚫ Extending the Thread Class ⚫ JPasswordField,
⚫ JButton,
⚫ Stopping and Blocking Thread
⚫ JCheckBox,
⚫ Life Cycle of a Thread ⚫ JRadioButton,
⚫ Thread Exceptions ⚫ JPanel,
⚫ JList,
⚫ Thread Priority-Synchronization. ⚫ JComboBox,
⚫ Swings ⚫ User Interface Design - Event Handling :
⚫ Action events,
⚫ Basic swing components:
⚫ Key events,
⚫ User Interface Design - Event Handling ⚫ Item events.
Swings Java Swing
⚫ Used to create window-based applications. ⚫ Java Swing is a part of Java Foundation Classes (JFC)
⚫ It is built on the top of AWT (Abstract Windowing Toolkit) that is used to create window-based applications.
API and entirely written in java.
⚫ The javax.swing package provides classes for java swing API
such as ⚫ What is JFC?
⚫ JButton,
⚫ JTextField, ⚫ The Java Foundation Classes (JFC) are a set of GUI
⚫ JTextArea, components which simplify the development of
⚫ JRadioButton, desktop applications.
⚫ JCheckbox,
⚫ JMenu,
⚫ JColorChooser etc.

AWT Vs Swings
Features of Swing
⚫ 1.Platform Independent
⚫ 2.Lightweight:
⚫ 3.Pluggable Look and Feel
⚫ 4.Extensible and Configurable
⚫ 5.MVC
⚫ 6.Customizable
⚫ 7.Rich Controls
⚫ Every user interface considers the following three main
aspects .
⚫ UI Elements
⚫ Layouts
⚫ Behavior
Container Class Swing Components in java
⚫ Container classes are classes that can have other
components on it.
⚫ So for creating a GUI, need at least one container object.
⚫ There are 3 types of containers.
⚫ Panel: It is a pure container and is not a window in itself.
The sole purpose of a Panel is to organize the components
on to a window.
⚫ Frame: It is a fully functioning window with its title and
icons.
⚫ Dialog: It can be thought of like a pop-up window that
pops out when a message has to be displayed. It is not a
fully functioning window like the Frame

Methods used in swings 4 important methods


⚫ Add
⚫ Setsize
⚫ Setlayout
⚫ setVisible

⚫ Note:
⚫ Add frame to add all the swing components
Java Swing Examples Example- method 1(Association)
import javax.swing.*;
public class MySwingExample
{

⚫ There are two ways to create a frame:


public static void main(String[] args)
{
⚫ By creating the object of Frame class (association) JFrame f=new JFrame(); //creating instance of JFrame
JButton b=new JButton(“save"); //creating instance of JButton
⚫ By extending Frame class (inheritance) b.setBounds(120,100,100, 50); //x axis, y axis, width, height

f.add(b); //adding button in JFrame


⚫ We can write the code of swing inside the main(),
f.setSize(500,600); //500 width and 600 height
constructor or any other method.
f.setLayout(null); //using no layout managers

f.setVisible(true); //making the frame visible


}
}

Example – Method 2 (inheritance)




import javax.swing.*;
public class Simple2 extends JFrame { //inheriting JFrame
Components of Swing
⚫ JFrame f;
⚫ Simple2()
⚫ { ImageIcon

⚫ Used to set an image
JButton b=new JButton("click"); //create button
⚫ b.setBounds(130,100,100, 40);
⚫ ⚫ ImageIcon homeIcon = new
⚫ add(b); //adding button on frame
⚫ setSize(400,500); ImageIcon(“src/images/home.jpg”);
⚫ setLayout(null);
⚫ setVisible(true);
⚫ }
⚫ public static void main(String[] args)
⚫ {
⚫ new Simple2();
⚫ }
⚫ }
JButton
JLabel
⚫ Button class is used to create a push-button on the UI.
⚫ The button can contain some display text or image. ⚫ JLabel class is used to provide a read-only text label
⚫ It generates an event when clicked and double-clicked or images on the UI.
⚫ A JButton can be implemented in the application by ⚫ It does not generate any event.
calling one of its constructors. ⚫ JLabel textLbl = new JLabel(“Welcome you all ”);
⚫ JButton okBtn = new JButton(“Ok”); ⚫ This constructor returns a label with text.
⚫ This constructor returns a button with text Ok on it ⚫ JLabel imgLabel = new JLabel(homeIcon);


JButton homeBtn = new JButton(homeIcon);
It returns a label with a home icon.
⚫ It returns a button with a homeIcon on it.
⚫ JButton btn2 = new JButton(homeIcon, “Home”);
⚫ It returns a button with the home icon and text Home.

JTextField JTextArea
⚫ JTextArea class provides a multi-line text box.
⚫ JTextField provides an editable single-line text box. ⚫ Similar to the JTextField, a user can input
⚫ A user can input non-formatted text in the box. non-formatted text in the field.
⚫ To initialize the text field, call its constructor and ⚫ The constructor for JTextArea also expects two
pass an optional integer parameter to it. integer parameters which define the height and
width of the text-area in columns.


This parameter sets the width of the box measured
It does not restrict the number of characters that the
by the number of columns. user can input in the text-area.
⚫ It does not limit the number of characters that can ⚫ JTextArea txtArea = new JTextArea(“Welcome you
be input in the box. all for the Event”, 5, 20);
⚫ JTextField txtBox = new JTextField(20); ⚫ The above code provides a multi-line text-area of
⚫ It renders a text box of 20 column width. height 5 rows and width 20 columns, with default
text initialized in the text-area.
JPasswordField JCheckBox
⚫ JPasswordField is a subclass of JTextField class.
⚫ It provides a text-box that masks the user input text ⚫ JCheckBox provides a check-box with a label.
with bullet points. ⚫ The check-box has two states – on/off.
⚫ This is used for inserting passwords into the ⚫ When selected, the state is on and a small tick is
application. displayed in the box.
⚫ Example: ⚫ CheckBox chkBox = new JCheckBox(“Show Help”,
⚫ JPasswordField pwdField = new JPasswordField(15); true);
var pwdValue = pwdField.getPassword(); ⚫ It is a boolean value that indicates the default state
⚫ it returns a password field of 15 column width. of the check-box.
⚫ The getPassword method gets the value entered by ⚫ True means the check-box is defaulted to on state.
the user.

JRadioButton JList
⚫ JRadioButton is used to provide a group of radio buttons ⚫ JList component provides a scrollable list of elements.
in the UI. ⚫ A user can select a value or multiple values from the list.
⚫ A user can select one choice from the group. ⚫ DefaultListItem cityList = new DefaultListItem();
⚫ ButtonGroup radioGroup = new ButtonGroup(); fruitList.addElement(“Mango”):
JRadioButton rb1 = new JRadioButton(“Red”, true); fruitList.addElement(“Apple”):
JRadioButton rb2 = new JRadioButton(“Green”); fruitList.addElement(“Orange”):
JRadioButton rb3 = new JRadioButton(“Blue”); fruitList.addElement(“Lichi”):
radioGroup.add(rb1); fruitList.addElement(“Jackfruit”):
radioGroup.add(rb2); JList fruits = new JList(fruitList);
radioGroup.add(rb3); fruits.setSelectionModel(ListSelectionModel.SINGLE_S
⚫ The above code creates a button group and three radio ELECTION);
button elements. ⚫ The above code renders a list of fruits with 5 items in the
⚫ All three elements are then added to the group list.
⚫ This ensures that only one option out of the available ⚫ The selection restriction is set to SINGLE_SELECTION.
options in the group can be selected at a time. ⚫ If multiple selections is to be allowed, set the behavior
⚫ The default selected option is set to Easy. to MULTIPLE_INTERVAL_SELECTION.
JComboBox
⚫ JComboBox class is used to provide a dropdown of
the list of options. JPanel
String[] cityStrings = { "Mumbai", "London", "New
⚫ It provides space in which an application can
York", "Sydney", "Tokyo" };
attach any other component.
JComboBox cities = new JComboBox(cityList);
⚫ It inherits the JComponents class.
cities.setSelectedIndex(3);
⚫ The default selected option can be specified through
the setSelectedIndex method. JPanel panel=new JPanel();
⚫ The above code sets Sydney as the default selected panel.setBounds(40,80,200,200);
option. panel.setBackground(Color.gray);

Some constructors for your


references.
Event handling in java
⚫ Event:
⚫ Changing the state of an object is known as an
Events
event. ⚫ Change in the state of an object is known as Event,
⚫ For example, ⚫ i.e., event describes the change in the state of the source.
⚫ click on button, ⚫ Events are generated as a result of user interaction with
⚫ dragging mouse etc. the graphical user interface components.
⚫ For example,
⚫ The java.awt.event package provides many
⚫ clicking on a button,
event classes and Listener interfaces for event
⚫ moving the mouse,
handling.
⚫ entering a character through keyboard,
⚫ Java Event classes and Listener interfaces
⚫ selecting an item from the list,
⚫ scrolling the page

Types of Event
⚫ The events can be broadly classified into two categories −
⚫ Foreground Events
Event Handling
⚫ These events require direct interaction of the user.
⚫ They are generated as consequences of a person interacting with the graphical
⚫ ❖ Event Handling is the mechanism that controls the
components in the Graphical User Interface. event and decides what should happen if an event
⚫ For example,
⚫ clicking on a button, occurs.
⚫ moving the mouse,
⚫ entering a character through keyboard
⚫ ❖ This mechanism has a code which is known as an
⚫ selecting an item from list event handler, that is executed when an event occurs.
⚫ scrolling the page, etc.
⚫ Background Events ⚫ ❖ Java uses the Delegation Event Model to handle the
⚫ These events require the interaction of the end user.
⚫ For Example,
events.
⚫ Operating system interrupts
⚫ hardware or software failure
⚫ ❖ This model defines the standard mechanism to
⚫ timer expiration, generate and handle the events.

⚫ operation completion

⚫ The Delegation Event Model has the following key participants. ⚫ In the event model, there are three participants:
⚫ ❖ Source ⚫ event source
⚫ The source is an object on which the event occurs. ⚫ event object
⚫ Source is responsible for providing information of the occurred ⚫ event listener
⚫ Event source is the object whose state changes. It generates
event to it's handler.
⚫ Java provide us with classes for the source object.
Events.
⚫ ❖ Listener
⚫ It is also known as event handler.
⚫ Event object (Event) encapsulates the state changes in the
⚫ The listener is responsible for generating a response to an event.
event source.
⚫ ❖ The listener waits till it receives an event. ⚫ Event listener is the object that wants to be notified.
⚫ Once the event is received, the listener processes the event and ⚫ Event source object delegates the task of handling an event
then returns. to the event listener

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and


MouseMotionListener
MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener
Steps to perform Event
Handling • TextField
• public void addActionListener(ActionListener a){}
⚫ Following steps are required to perform event • public void addTextListener(TextListener a){}
handling: • TextArea
Register the component with the Listener • public void addTextListener(TextListener a){}
⚫ Registration Methods • Checkbox
⚫ For registering the component with the • public void addItemListener(ItemListener a){}
Listener, many classes provide the registration Choice
methods. • public void addItemListener(ItemListener a){}
⚫ For example:
• List
• Button • public void addActionListener(ActionListener a){}
• public void addActionListener(ActionListener • public void addItemListener(ItemListener a){}
a){}
• MenuItem
• public void addActionListener(ActionListener
a){}

import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener
Action Listner {
TextField tf;
⚫ ActionListener is notified whenever you click on AEvent()
{
the button or menu item.
⚫ It is notified against ActionEvent. //create components

tf=new TextField();
The ActionListener interface is found in tf.setBounds(60,50,170,20);
java.awt.event package. Button b=new Button("click me");

b.setBounds(100,120,80,30);
It has only one method:
⚫ actionPerformed(). //register listener
b.addActionListener(this);//passing current instance
//add components and set size, layout and visibility
add(b);
add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
Establishing a simple server-
Networking Client vs server General meaning
⚫ Connecting two or more computing devices together ⚫ Client
to share resources. ⚫ It is a computer or computer program that is make a
⚫ Advantage of Java Networking
request for any services and capable of obtaining
services.
⚫ Sharing resources ⚫ Clients are the ones who request services.
⚫ Centralize software management

⚫ Server
⚫ It is also a computer or computer program which
manages access to a centralized resource .
⚫ That provides the services based on the client request.
⚫ A server is the one who provides requested services.

Example
Example

⚫ Many corporate networks comprise a client


computer for each employee, each of which
connects to the corporate server.
⚫ The server provides resources like files,
information, Internet and intranet access, and
external processing power.
⚫ In the case of processing, any work done on the
server is referred to as "server-side" work.
⚫ Any work done on the local client is similarly
called "client-side“.
Types of clients
Server side vs. Client side
⚫ Based on the operating system (used by
users)the type of clients are classified as:
⚫ Apple client - Computer using macOS.
• IoT - Internet of Things device.
• Linux client - Computer running Linux.
• Smartphone or mobile - Mobile device like
a smartphone uses android
• Windows client - Computer
running Windows.

Server –Networking definition Server-image


⚫ A server is a software or hardware device
that accepts and responds to requests made
over a network.
⚫ Example
⚫ On the Internet, the term "server" commonly
refers to the computer system that receives
requests for a web files and sends those files
to the client.
• Domain name service-
• Domain Name System, a DNS is a service that receives a request

Types of server •
containing a domain name hostname and responds with the
corresponding IP address.
File server
• Application server • A file server is a computer on a network that is used to provide users on a
• Application oriented request processing(Java ,Php,.NET Framework network with access to files.
application) • Mail server
• Blade server • A remote or central computer that holds electronic mail (e-mail) messages
• one rack mount unit that is capable of holding many different for clients on a network is called a mail server.
servers. • Print server
• Cloud server • Computer or standalone device responsible for managing one or more
printers on a network.
• services provided over a network by a collection of remote servers.
• Proxy server
• Database server • A proxy is a server or program that's part of the gateway or another
• A database server is a computer system that provides other computer that separates a local network from outside networks.
computers with services related to accessing and retrieving data • Standalone server
from a database. • SAS is a server that does not rely on any other servers or services.
• Dedicated server • Web server
• A server that is hosted by a company and only allows one company • Computer or collection of computers used to deliver web pages and other
to lease and access it is called a dedicated server. content to multiple users.

Networking terminologies mostly IP Address


used in java
⚫ IP Address ⚫ IP address is a unique number assigned to a node of a
⚫ Protocol network.
⚫ Connection-oriented and connection-less protocol ⚫ Example
⚫ Port Number ⚫ 192.168.0.1 .
⚫ Socket ⚫ It is composed of octets that range from 0 to 255.
⚫ It is a logical address that can be changed.
MAC Address- Media Access Protocol
Control
⚫ MAC address is the physical address, ⚫ A protocol is a set of rules basically that is followed for
⚫ which uniquely identifies each device on a given network.
communication.
⚫ To make communication between two networked devices use ⚫ For example:
two addresses:
⚫ TCP
⚫ IP address and
⚫ MAC address. ⚫ UDP
⚫ FTP
⚫ It is assigned to the NIC (Network Interface card) of each device
that can be connected to the internet. ⚫ Telnet
⚫ SMTP
⚫ It stands for Media Access Control, and also known ⚫ POP etc.
as Physical address, hardware address, or BIA (Burned In
Address).

Connection-oriented and
Protocols connection-less protocol
⚫ TCP: Transmission Control Protocol ⚫ In connection-oriented protocol,
⚫ provides reliable communication between the sender ⚫ acknowledgement is sent by the receiver.
and receiver. ⚫ So it is reliable but slow.
⚫ TCP is used along with the Internet Protocol referred as ⚫ The example of connection-oriented protocol is TCP.
TCP/IP. ⚫ connection-less protocol,
⚫ UDP: User Datagram Protocol ⚫ acknowledgement is not sent by the receiver.
⚫ provides a connection-less protocol service by allowing ⚫ So it is not reliable but fast.
packet of data to be transferred along two or more nodes
⚫ The example of connection-less protocol is UDP.
Port Number

⚫ port number is a number


⚫ Number assigned to uniquely identify a connection
endpoint and to direct data to a specific service.
⚫ It acts as a communication endpoint between
applications.
⚫ The port number is associated with the IP address for
communication between two applications.

java.net package Socket


⚫ For networking concepts java.net package is used. Socket: A socket is an endpoint between two way
⚫ It can be divided into two parts. communication.
⚫ A Low-Level API ⚫ Make use of sockets to establish connection between
⚫ A High Level API client and server and then for exchanging data
⚫ A Low-Level API: ⚫ Sockets allow communication between two different
⚫ It deals with the abstractions of addresses processes on the same or different machines.
⚫ Socket is used in a client-server application
framework.
⚫ A High-Level API: ⚫ Most of the application-level protocols like FTP, SMTP,
⚫ It deals with the abstractions of URLs and POP3 make use of sockets to establish connection
between client and server and then for exchanging
data.
Java Socket Programming
Example
⚫ Java Socket programming is used for communication between ⚫ one-way client and server communication.
the applications running on different JRE. ⚫ In this application, client sends a message to the server,
⚫ Java Socket programming can be connection-oriented or server reads the message and prints it.
⚫ Here, two classes are being used:
connection-less.
⚫ connection-oriented socket programming.
⚫ Socket and ServerSocket.
⚫ Socket and
⚫ ServerSocket classes are used. ⚫ The Socket class is used to communicate client and server.
⚫ connection-less socket programming Through this class, we can read and write message.
⚫ DatagramSocket and ⚫ The ServerSocket class is used at server-side.
⚫ DatagramPacket classes are used. ⚫ The accept() method of ServerSocket class blocks the
⚫ The client in socket programming must know two information: console until the client is connected.
⚫ IP Address of Server, and ⚫ After the successful connection of client, it returns the
⚫ Port number. instance of Socket at server-side.

Socket class
CLIENT SERVER COMMUNICATION
⚫ A socket is simply an endpoint for communications
between the machines.
⚫ The Socket class can be used to create a socket.
ServerSocket class Creating Server:
⚫ To create the server application,
⚫ The ServerSocket class can be used to create a server
socket. ⚫ Step 1: create the instance of ServerSocket class.
⚫ This object is used to establish communication with ⚫ Step 2: use Port number for the communication between
the clients. the client and server.
⚫ Step 3: use accept() method that’s waits for the client.
⚫ Step 4: If clients connects with the given port number, it
returns an instance of Socket.
1. ServerSocket ss=new ServerSocket(6666);
Note:(6666 –IRC-internet relay chat service)
2. Socket s=ss.accept();
// establishes connection and waits for the client

Creating Client:
writeUTF() and readUTF()
⚫ To create the client application, ⚫ Unicode Translation Format
⚫ create the instance of Socket class. ⚫ The writeUTF() method of the java.io.DataOutputStream
⚫ Here, need to pass the IP address or hostname of the class
⚫ accepts a String value as a parameter and writes it in using
Server and a port number.
modified UTF-8 encoding, to the current output stream.
⚫ Here, we are using "localhost" because our server is ⚫ Therefore to write UTF-8 data to a file
running on same system. ⚫ The readUTF() method of the java.io.DataOutputStream
⚫ Coding: ⚫ reads data that is in modified UTF-8 encoding, into a String
⚫ Socket s=new Socket("localhost",6666); and returns it.
⚫ Therefore to read UTF-8 data to a file
Java InetAddress class


Java InetAddress class represents an IP address.

The java.net.InetAddress class provides methods to get the IP of any host name.
Commonly used methods of Inet Address

Example
www.google.com, www.facebook.com, etc. class
⚫ An IP address is represented by 32-bit or 128-bit unsigned number.
Method Description
⚫ InetAddress types:
public static InetAddress getByName(String host) it returns the instance of InetAddress containing

throws UnknownHostException LocalHost IP and name.
Unicast
public static InetAddress getLocalHost() throws it returns the instance of InetAdddress containing local
⚫ Multicast. UnknownHostException host name and address.


public String getHostName() it returns the host name of the IP address.
The Unicast is an identifier for a single interface whereas Multicast is an identifier
public String getHostAddress() it returns the IP address in string format.
for a set of interfaces.

⚫ InetAddress has a cache mechanism to store successful and unsuccessful host name
resolutions.

Java DatagramSocket and


example DatagramPacket
⚫ import java.io.*; •Java DatagramSocket and DatagramPacket classes are used
⚫ import java.net.*;
⚫ public class InetDemo{ for connection-less socket programming.
⚫ public static void main(String[] args){
⚫ try{ •Java DatagramSocket class represents a connection-less
⚫ InetAddress ip=InetAddress.getByName("www.google.com");
⚫ System.out.println("Host Name: "+ip.getHostName()); socket for sending and receiving datagram packets.
⚫ System.out.println("IP Address: "+ip.getHostAddress());
⚫ }catch(Exception e){ System.out.println(e); •A datagram is basically an information but there is no
⚫ }
⚫ } guarantee of its content, arrival or arrival time
⚫ }
Commonly used Constructors of
DatagramSocket class Java DatagramPacket class
•DatagramSocket() throws SocketEeption: it creates a datagram
•Java DatagramPacket is a message that can be sent or
socket and binds it with the available Port Number on the localhost
machine. received.

•DatagramSocket(int port) throws SocketEeption: it creates a • If you send multiple packet, it may arrive in any order.

datagram socket and binds it with the given Port Number. Additionally, packet delivery is not guaranteed.

•DatagramSocket(int port, InetAddress address) throws

SocketEeption: it creates a datagram socket and binds it with the


specified port number and host address.

Commonly used Constructors of //DSender.java


⚫ import java.net.*;
DatagramPacket class ⚫ public class DSender{
⚫ public static void main(String[] args) throws Exception {
•DatagramPacket(byte[] barr, int length): ⚫ DatagramSocket ds = new DatagramSocket();
⚫ String str = "Welcome java";
• it creates a datagram packet. ⚫ InetAddress ip =
InetAddress.getByName(“www.google.com");
• This constructor is used to receive the packets. ⚫
⚫ DatagramPacket dp = new
•DatagramPacket(byte[] barr, int length, DatagramPacket(str.getBytes(), str.length(), ip, 3333);
⚫ ds.send(dp);
InetAddress address, int port):
⚫ ds.close();
•it creates a datagram packet. ⚫ }
⚫ } ⚫ Java program Using DatagramPacket by
•This constructor is used to send the packets. DatagramSocket
//DReceiver.java
output
⚫ //DReceiver.java
⚫ import java.net.*;
⚫ public class DReceiver{
⚫ public static void main(String[] args) throws Exception {
⚫ DatagramSocket ds = new DatagramSocket(3333);
⚫ byte[] buf = new byte[1024];
⚫ DatagramPacket dp = new DatagramPacket(buf, 1024);
⚫ ds.receive(dp);
⚫ String str = new String(dp.getData(), 0, dp.getLength());
⚫ System.out.println(str);
⚫ ds.close();
⚫ }
⚫ }

JDBC
⚫ JDBC stands for Java Database Connectivity.
⚫ JDBC is a Java API to connect and execute the query ⚫ JDBC API to access tabular data stored in any
with the database. relational database.
⚫ It is a part of JavaSE (Java Standard Edition). ⚫ Using JDBC API, we can save, update, delete and fetch
⚫ JDBC API uses JDBC drivers to connect with the data from the database.
database. ⚫ It is like Open Database Connectivity (ODBC)
⚫ There are four types of JDBC drivers: provided by Microsoft.
⚫ JDBC-ODBC Bridge Driver,
⚫ Native Driver,
⚫ Network Protocol Driver, and
⚫ Thin Driver
JDBC interaction with Database
⚫ The current version of JDBC is 4.3.
⚫ It is the stable release since 21st September, 2017.
⚫ It is based on the X/Open SQL Call Level Interface.
⚫ The java.sql package contains classes and interfaces
for JDBC API.

Why Should We Use JDBC?

⚫ Before JDBC, ODBC API was the database API to ⚫ We can use JDBC API to handle database using Java
connect and execute the query with the database. program and can perform the following activities:
⚫ But, ODBC API uses ODBC driver which is written in ⚫ Connect to the database
C language (i.e. platform dependent and unsecured). ⚫ Execute queries and update statements to the database
⚫ That is why Java has defined its own API (JDBC API) ⚫ Retrieve the result received from the database.
that uses JDBC drivers (written in Java language).
Architecture Explanation
⚫ Application:
⚫ It is a java applet or a servlet that communicates with a data
source.
⚫ The JDBC API:
⚫ The JDBC API allows Java programs to execute SQL
statements and retrieve results.
⚫ DriverManager:
⚫ It plays an important role in the JDBC architecture.
⚫ It uses some database-specific drivers to effectively connect
enterprise applications to databases.
⚫ JDBC drivers:
⚫ To communicate with a data source through JDBC.
⚫ JDBC driver that intelligently communicates with the
respective data source.

A list of popular interfaces of JDBC


API A list of popular classes of JDBC API
⚫ Driver interface ⚫ DriverManager class
⚫ Connection interface ⚫ Blob class
⚫ Statement interface ⚫ Clob class
⚫ PreparedStatement interface ⚫ Types class
⚫ CallableStatement interface
⚫ ResultSet interface
⚫ ResultSetMetaData interface
⚫ DatabaseMetaData interface
⚫ RowSet interface
1) JDBC-ODBC bridge driver
JDBC Driver
⚫ JDBC Driver is a software component that enables java ⚫ The JDBC-ODBC bridge driver uses ODBC driver to connect to the
database.
application to interact with the database. ⚫ The JDBC-ODBC bridge driver converts JDBC method calls into the
⚫ There are 4 types of JDBC drivers:
ODBC function calls.
⚫ This is now discouraged because of thin driver.
⚫ JDBC-ODBC bridge driver ⚫ Oracle does not support the JDBC-ODBC Bridge from Java 8.
⚫ Oracle recommends that you use JDBC drivers provided by the vendor
⚫ Native-API driver (partially java driver) of your database instead of the JDBC-ODBC Bridge.
⚫ Network Protocol driver (fully java driver) ⚫ Advantages:
⚫ easy to use.
⚫ Thin driver (fully java driver) ⚫ can be easily connected to any database.
⚫ Disadvantages:
⚫ Performance degraded because JDBC method call is converted into the
ODBC function calls.
⚫ The ODBC driver needs to be installed on the client machine.

2) Native-API driver
JDBC-ODBC bridge driver
⚫ The Native API driver uses the client-side libraries of the
database.
⚫ The driver converts JDBC method calls into native calls of
the database API.
⚫ It is not written entirely in java.
⚫ Advantage:
⚫ performance upgraded than JDBC-ODBC bridge driver.
⚫ Disadvantage:
⚫ The Native driver needs to be installed on the each client
machine.
⚫ The Vendor client library needs to be installed on client
machine.
2) Native-API driver Network Protocol driver
⚫ The Network Protocol driver uses middleware (application
server).
⚫ That converts JDBC calls directly or indirectly into the
vendor-specific database protocol.
⚫ It is fully written in java.
⚫ Advantage:
⚫ No client side library is required because of application server
that can perform many tasks like auditing, load balancing,
logging etc.
⚫ Disadvantages:
⚫ Network support is required on client machine.
⚫ Requires database-specific coding to be done in the middle tier.
⚫ Maintenance of Network Protocol driver becomes costly because
it requires database-specific coding to be done in the middle
tier.

Thin driver
Network Protocol driver ⚫ The thin driver converts JDBC calls directly into the
vendor-specific database protocol.
⚫ That is why it is known as thin driver.
⚫ It is fully written in Java language.
⚫ Advantage:
⚫ Better performance than all other drivers.
⚫ No software is required at client side or server side.
⚫ Disadvantage:
⚫ Drivers depend on the Database.
Thin driver Java Database Connectivity 7 Steps

⚫ Load the JDBC driver.


⚫ Registering driver class
⚫ Creating connection to DB
⚫ Creating Statement
⚫ Executing Query
⚫ Processing Result Set
⚫ Closing connection

5 steps are Important


⚫ Register the Driver class
⚫ Create connection
⚫ Create statement
⚫ Execute queries
⚫ Close connection
aaa 2.Register the driver class
⚫ It is first an essential part to create JDBC connection.
⚫ JDBC API provides a method Class.
⚫ forName() which is used to load the driver class
explicitly.
⚫ For example,
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
⚫ Or
⚫ class.forName("oracle.jdbc.driver.OracleDriver");
Or
⚫ Class.forName("com.mysql.jdbc.Driver");

1.Load the driver class and 3.Create the connection object


⚫ The getConnection() method of DriverManager class
⚫ For connecting JAVA API to Database we must load the
is used to establish connection with the
database.Syntax of getConnection() method
driver to handle database.
⚫ IT is also said to be registering the driver class. ⚫ 1) public static Connection getConnection(String url)
throws SQLException
⚫ Database may be
⚫ 2) public static Connection getConnection(String url
⚫ Mysql
,String name,String password) throws SQLException
⚫ Oracle
4.Create the Statement object
connection coding Example
⚫ Oracle connection coding ⚫ The createStatement() method of Connection
⚫ Connection con=DriverManager.getConnection( interface is used to create statement.
⚫ "jdbc:oracle:thin:@localhost:1521:xe","system","passwo ⚫ The object of statement is responsible to execute
rd"); queries with the database.
⚫ Mysql Connection coding ⚫ Syntax of createStatement() method
⚫ Connection con = ⚫ public Statement createStatement()throws SQLExce
DriverManager.getConnection("jdbc:mysql://localhos ption
t:3306/onlinetutorialspoint","root","123456"); ⚫ Example to create the statement object
⚫ Statement stmt=con.createStatement();

5.Execute the query ⚫ executeUpdate()


⚫ Execute Sql queries : To execute the SQL commands on ⚫ When we want to run the non-select operations then
database, Statement interface provides three different we can choose executeUpdate()
methods: ⚫ int count = stmt.executeUpdate("non-select
⚫ executeUpdate() command");
⚫ executeQuery() ⚫ executeQuery()
⚫ execute() ⚫ When we want to execute select operations then we
⚫ executeQuery() can choose executeQuery()
⚫ The executeQuery() method of Statement interface is used ⚫ ResultSet rs = stmt.executeQuery("select command");
to execute queries to the database.
⚫ execute()
⚫ This method returns the object of ResultSet that can be used
to get all the records of a table. ⚫ When we want to run both select and non-select
⚫ Syntax
operations, then we can use execute()
⚫ boolean isTrue = stmt.execute ("select / non-select
⚫ public ResultSet executeQuery(String sql)throws SQLExc
eption command");
Example to execute query and
⚫ ResultSet rs=stmt.executeQuery("select * from emp"); processing result set
6.Process the ResultSet
⚫ The executed query returns the data in the form of ⚫ ResultSet rs=stmt.executeQuery("select * from emp");
ResultSet object. //print result set
⚫ To process the data we need to go through the ⚫ while(rs.next())
ResultSet.
⚫ {
⚫ Coding
⚫ System.out.println(rs.getInt(1)+" "+rs.getString(2));
⚫ while(rs.next()) ⚫ }
⚫ {
⚫ System.out.println(rs.getInt(1)+" "+rs.getString(2));
⚫ }

7.Close the connection object Closing result set, statement and


connection
⚫ By closing connection object statement and ResultSet ⚫ rs.close();
will be closed automatically. ⚫ stmt.close();
⚫ The close() method of Connection interface is used to ⚫ con.close();
close the connection.Syntax of close() method
⚫ public void close()throws SQLException
⚫ Example to close connection
⚫ con.close();
Unit-5 -NETWORKING, DATABASE
CONNETIVITY AND COLLECTIONS Collections
⚫ Establishing a simple server: ⚫ The Collection in Java is a framework that provides an
⚫ Establishing a simple client/server interaction with architecture to store and manipulate the group of objects.
stream socket and datagram socket ⚫ Java Collections using the operations such as searching,
⚫ sorting,
⚫ JDBC
⚫ insertion,
⚫ JDBC Drivers
⚫ manipulation, and
⚫ Seven steps to connect JDBC ⚫ deletion.
⚫ Collections ⚫ What is Collection in Java?
⚫ Overview of Interfaces and classes ⚫ A Collection represents a single unit of objects, i.e., a
group.

Definition Collection
⚫ Any group of individual objects which are represented ⚫ Java Collection framework provides many interfaces and classes
as a single unit is known as the collection of the ⚫ interfaces
⚫ Set
objects. ⚫ List
⚫ In Java, a separate framework named the “Collection ⚫ Queue
Framework” has been defined in JDK 1.2 which holds ⚫ Deque
all the collection classes and interface in it. ⚫ classes
⚫ ArrayList,
⚫ The Collection interface (java.util.Collection) and ⚫ Vector,
Map interface (java.util.Map) are the two main “root” ⚫ LinkedList,
interfaces of Java collection classes. ⚫ PriorityQueue,
⚫ HashSet,
⚫ LinkedHashSet,
⚫ TreeSet
Hierarchy of Collection Framework

⚫ What is a framework in Java? ⚫ The java.util package contains all


⚫ It provides readymade architecture. the classes and interfaces for the Collection
⚫ It represents a set of classes and interfaces. framework.
⚫ It is optional.
⚫ What is Collection framework?
⚫ The Collection framework represents a unified
architecture for storing and manipulating a group of
objects.
⚫ It has Interfaces and its implementations, i.e.,
⚫ classes
⚫ Algorithm

Methods of Collection interface


Iterator interface Iterable Interface

⚫ Iterator interface provides the facility of iterating the ⚫ The Iterable interface is the root interface for all the
elements in a forward direction only.Methods of collection classes.
Iterator interface ⚫ The Collection interface extends the Iterable interface
⚫ There are only three methods in the Iterator interface. and therefore all the subclasses of Collection interface
They are: also implement the Iterable interface.
⚫ It contains only one abstract method. i.e.,
⚫ Iterator<T> iterator()
⚫ It returns the iterator over the elements of type T.
Collection Interface List Interface
⚫ The Collection interface is the interface which is
implemented by all the classes in the collection ⚫ List interface is the child interface of Collection interface.
framework. ⚫ It inhibits a list type data structure in which we can store
⚫ It declares the methods that every collection will have. the ordered collection of objects.
⚫ Collection interface builds the foundation on which ⚫ It can have duplicate values.
the collection framework depends. ⚫ List interface is implemented by the classes ArrayList,
LinkedList, Vector, and Stack.
⚫ Some of the methods of Collection interface are
⚫ To instantiate the List interface, we must use :
⚫ Boolean add ( Object obj), ⚫ List <data-type> list1= new ArrayList();
⚫ Boolean addAll ( Collection c), void clear(), etc. ⚫ List <data-type> list2 = new LinkedList();
⚫ which are implemented by all the subclasses of ⚫ List <data-type> list3 = new Vector();
Collection interface. ⚫ List <data-type> list4 = new Stack();

Class Collections

⚫ java.lang.Object ⚫ The documentation for the polymorphic algorithms


⚫ java.util.Collections contained in this class generally includes a brief
⚫ description of the implementation.
public class Collections extends Object
⚫ This class consists exclusively of static methods that ⚫ Such descriptions should be regarded
operate on or return collections. as implementation notes, rather than parts of
⚫ It contains polymorphic algorithms that operate on the specification.
collections, "wrappers", which return a new collection ⚫ Implementors should feel free to substitute other
backed by a specified collection, and a few other odds and algorithms, so long as the specification itself is
ends.
adhered to.
⚫ The methods of this class all throw
a NullPointerException if the collections or class objects ⚫ (For example, the algorithm used by sort does not have
provided to them are null. to be a mergesort, but it does have to be stable.)

You might also like