KEMBAR78
Complete Java Notes | PDF | Java (Programming Language) | Class (Computer Programming)
0% found this document useful (0 votes)
9 views351 pages

Complete Java Notes

The document provides an overview of Java programming, detailing its evolution from earlier languages like C and C++, and its development at Sun Microsystems. It highlights Java's key features such as platform independence, object-oriented design, and robust security, along with its various versions and applications in web and mobile development. Additionally, it discusses the advantages of Java, including scalability, community support, and regular updates, making it a preferred choice for enterprise applications.

Uploaded by

vt35609
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)
9 views351 pages

Complete Java Notes

The document provides an overview of Java programming, detailing its evolution from earlier languages like C and C++, and its development at Sun Microsystems. It highlights Java's key features such as platform independence, object-oriented design, and robust security, along with its various versions and applications in web and mobile development. Additionally, it discusses the advantages of Java, including scalability, community support, and regular updates, making it a preferred choice for enterprise applications.

Uploaded by

vt35609
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/ 351

Java Programming

Unit I
Basics of Java Programming

Mr. Neeraj Kumar Srivastava


Assistant Professor
Department of Computer Applications
Background
• Computer language innovation and
development occurs for two fundamental
reasons:
– To adapt to changing environments and uses
– To implement improvements in the art of
programming
• The development of Java was driven by both in
equal measures
• Many Java features are inherited from the
earlier languages: B , C , C++

Prepared By: Mr. Neeraj Kumar Srivastava 2


Background
Before Java: C Language-
• Designed by Dennis Ritchie in 1970s
• Before C: BASIC, COBOL, FORTRAN, PASCAL
• Features of C Language:
– structured
– efficient
– high-level language that could replace assembly
code when creating systems programs
• Designed, implemented and tested by
programmers
Prepared By: Mr. Neeraj Kumar Srivastava 3
Background
Before Java: C++
• Designed by Bjarne Stroustrup in 1979
• Object-oriented programming language
• Features of OOP:
– Encapsulation
– Abstraction
– Inheritance
– Polymorphism
• Extends features of C language by adding object-
oriented features
Prepared By: Mr. Neeraj Kumar Srivastava 4
Evolution (History) of Java
• Java started out as a research project
• Objective: to develop software for consumer electronics
• Research began in 1991 as the Green Project at Sun
Microsystems (Now Sun Microsystems is a subsidiary of Oracle
Corporation)
• Project was assigned to James Gosling, a veteran of
classic network software design with Patrick
Naughton, Chris Warth, Ed Frank, and Mike Sheridan
• The team started writing programs in C++ for
embedding into, toasters, washing machines ,VCR’s
• Aim was to make these appliances more “intelligent”

Prepared By: Mr. Neeraj Kumar Srivastava 5


Evolution (History) of Java
Problems with C++:
– C++ is powerful, but also dangerous
– The power and popularity of C derived from the extensive
use of pointers (however, any incorrect use of pointers can cause
memory leaks, leading the program to crash. In a complex program,
such memory leaks are often hard to detect)
– However, users do not expect toasters or washing
machine to crash
– A design for consumer electronics has to be robust
– Replacing pointers by references, and automating memory
management was the proposed solution

Prepared By: Mr. Neeraj Kumar Srivastava 6


Evolution (History) of Java
• Research efforts birthed a new language OAK ( A tree
outside of the window of James Gosling’s office at Sun)
• It avoided potentially dangerous constructs in C++,
such as pointers, pointer arithmetic, operator
overloading etc.
• Developed as an embedded programming language
(which would enable embedded system application)
• Architecture neutrality (Platform independence)
– Hardware chips are evolving rapidly
– Different CPU’s are used as controllers
– As better chips become available, older chips become obsolete and
their production is stopped
– Manufacturers of toasters and washing machines would like to use
the chips available off the shelf, and would not like to reinvest in
compiler development every two-three years

Prepared By: Mr. Neeraj Kumar Srivastava 7


Evolution (History) of Java
• Language was created with 5 main goals:
– Should be object oriented
– A single representation of a program could be
executed on multiple operating systems (i.e. write
once, run anywhere)
– Should fully support network programming
– Should execute code from remote sources securely
– Should be easy to use
• Introduced automatic memory management,
freeing the programmer to concentrate on
other things

Prepared By: Mr. Neeraj Kumar Srivastava 8


Evolution (History) of Java
• It was soon realized that these design goals of
consumer electronics perfectly suited an ideal
programming language for the Internet and
WWW, which should be:
– object-oriented (& support GUI)
– robust
– architecture neutral
• OAK was “re-targeted” for the Internet (The team was
expanded to include Bill Joy (developer of Unix), Arthur van
Hoff, Jonathan Payne, Frank Yellin, Tim Lindholm etc.)
• An early web browser called WebRunner (later
renamed as HotJava) was written in Oak in 1996

Prepared By: Mr. Neeraj Kumar Srivastava 9


Evolution (History) of Java
• Internet programming presented a BIG business
opportunity (much bigger than programming for
consumer electronics)
• Oak was later renamed as Java in 1997
– A common story is that the name Java relates to the place
from where the development team got its coffee
– The name Java survived the trade mark search
• Java is available as jdk
• It is an open source software

Prepared By: Mr. Neeraj Kumar Srivastava 10


Introduction to Java
• A high-level, object-oriented programming
language
• Widely used for building applications across
various platforms
• Developed by James Gosling at Sun Microsystems
in the mid 90s
• Known for its platform independence (meaning
programs written in Java can run on any device or OS that has
the Java Virtual Machine (JVM) installed)
• Follows the principle of Write Once, Run
Anywhere (WORA)
Prepared By: Mr. Neeraj Kumar Srivastava 11
Introduction of Java

James Gosling
A Canadian computer scientist, best known as the founder and lead
designer behind the Java programming language
Prepared By: Mr. Neeraj Kumar Srivastava 12
Introduction of Java

Logo of Java
Prepared By: Mr. Neeraj Kumar Srivastava 13
Java Platforms
• There are three main platforms for Java:

– Java SE (Java Platform, Standard Edition)


• Runs on desktops and laptops

– Java ME (Java Platform, Micro Edition)


• Runs on mobile devices such as cell phones

– Java EE (Java Platform, Enterprise Edition)


• Runs on servers

Prepared By: Mr. Neeraj Kumar Srivastava 14


Versions of Java

• Core Java Versions (JDK)

– JDK 1.x (1996–1999) – Basics (JDK 1.0, 1.1)


– J2SE 1.2–1.4 (1998–2002) – Collections, Swing,
JDBC
– Java SE 5 (2004) – Generics, Enhanced for-loop
– Java SE 6 (2006) – Performance improvements
Prepared By: Mr. Neeraj Kumar Srivastava 15
Versions of Java
• Modern Java Versions
– Java SE 7 (2011) – Try-with-resources, Diamond operator
– Java SE 8 (2014) – Lambda, Streams, Default Methods
– Java SE 9 (2017) – Module System (Project Jigsaw)
– Java SE 10 (2018) – var for local variables
– Java SE 11 (2018 LTS) – Long-Term Support, var in
Lambda
– Java SE 12–16 (2019–2021) – Switch expressions,
Records
– Java SE 17 (2021 LTS) – Sealed classes, Pattern Matching
– Java SE 18–20 (2022–2023) – Minor updates, Preview
features
– Java SE 21 (2023 LTS) – Virtual Threads (Project Loom),
Sequenced Collections
Prepared By: Mr. Neeraj Kumar Srivastava 16
Versions of Java

• Enterprise Java
– J2EE (1999–2017) – Servlets, JSP, EJB, JMS

– Jakarta EE (2018–present) – Successor of Java EE

• Mobile & Embedded Java


– J2ME (2000s) – Mobile Java (outdated)

– Java ME (Current) – Embedded and IoT devices

Prepared By: Mr. Neeraj Kumar Srivastava 17


Features of Java
– Object Oriented Programming Language
– Platform Independent
– Simplicity
– Robustness
– Security
– Distributed
– Multithreading
– Portability
– High Performance

Prepared By: Mr. Neeraj Kumar Srivastava 18


Java Buzzwords
• Describe key features of Java
• The key considerations were summed up by
the Java Team in the following list of
Buzzwords:
⧿Simple ⧿Multithreading
⧿Secure ⧿Portable
⧿Object Oriented ⧿Robust
⧿Architecture-Neutral ⧿Interpreted
⧿High Performance ⧿Distributed
⧿Dynamic ⧿ Platform Independent
Prepared By: Mr. Neeraj Kumar Srivastava 19
Java Buzzwords
• Simple
– Java simplifies programming by eliminating complex
features like pointers and operator overloading, making
it more accessible than languages like C++
• Secure
– Java has built-in security mechanisms, including
classloaders, bytecode verification, and a security
manager, which help prevent unauthorized access and
vulnerabilities
• Object Oriented
– Java follows the principles of object-oriented
programming (OOP), such as encapsulation, inheritance,
and polymorphism, allowing for modular and reusable
code

Prepared By: Mr. Neeraj Kumar Srivastava 20


Java Buzzwords
• Architecture-Neutral
– Since Java bytecode is not tied to any specific
hardware architecture, programs can be executed
across different devices seamlessly
• High Performance
– Java balances interpretation and compilation with
Just-In-Time (JIT) compilation, which boosts
execution speed while maintaining flexibility
• Dynamic
– Java can dynamically load classes at runtime, making
it highly adaptable and extensible

Prepared By: Mr. Neeraj Kumar Srivastava 21


Java Buzzwords
• Multithreading
– Java supports multithreading, allowing concurrent
execution of tasks to improve performance and
responsiveness
• Portable
– Java is designed to be platform-independent,
meaning applications written in Java can run on any
device or operating system without modification
• Robust
– Java has strong memory management, automatic
garbage collection, and exception handling to
prevent crashes

Prepared By: Mr. Neeraj Kumar Srivastava 22


Java Buzzwords
• Interpreted
– Java is both interpreted (via the JVM) and compiled
(using Just-In-Time (JIT) compilation) for optimized
performance
• Distributed
– Java has built-in support for distributed computing
with APIs like RMI (Remote Method Invocation) and
CORBA
• Platform Independent
– Java code runs on any platform without modification
with the help of Java Virtual Machine (JVM) and its
Write Once, Run Anywhere (WORA) principle

Prepared By: Mr. Neeraj Kumar Srivastava 23


Java Terminology
• Java Development Kit (JDK):
– It contains one (or more) JRE's along with the
various development tools like the Java source
compilers, bundling and deployment tools,
debuggers, development libraries, etc.
• Java Virtual Machine (JVM):
– An abstract machine architecture specified by the
Java Virtual Machine Specification
– Interprets the byte code into the machine code
depending upon the underlying OS and hardware
combination
– JVM is platform dependent (It uses the class libraries,
and other supporting files provided in JRE)
Prepared By: Mr. Neeraj Kumar Srivastava 24
Java Terminology
• Java Runtime Environment (JRE):
– A runtime environment, which implements Java
Virtual Machine
– Provides all class libraries and other facilities
necessary to execute Java programs
– This is the software on our computer that
actually runs Java programs
– JRE = JVM + Java Packages Classes (like util,
math, lang, awt, swing etc.) +runtime libraries

Prepared By: Mr. Neeraj Kumar Srivastava 25


Advantages of Java
• Scalability
– Java is widely used in large-scale enterprise applications,
cloud computing, and microservices due to its ability to
handle growing demands
• Extensive Community Support
– A large developer community ensures continuous
updates, support, and availability of open-source tools
and frameworks
• Backward Compatibility
– Newer Java versions maintain compatibility with older
code, ensuring long-term usability
• Flexibility
– Used in web development, mobile applications (Android),
cloud computing, IoT, and big data applications
Prepared By: Mr. Neeraj Kumar Srivastava 26
Advantages of Java
• Development Tools
– Java offers powerful IDEs like IntelliJ IDEA, Eclipse, and
NetBeans, enhancing productivity
• Enterprise-Friendly
– Frameworks like Spring, Hibernate, and Jakarta EE make
Java a preferred choice for large business applications
• Regular Updates
– Java receives frequent updates with performance
enhancements, security fixes, and new features, keeping it
modern and efficient

Prepared By: Mr. Neeraj Kumar Srivastava 27


C++ Vs Java

Prepared By: Mr. Neeraj Kumar Srivastava 28


C++ Vs Java

Prepared By: Mr. Neeraj Kumar Srivastava 29


C++ Vs Java

Prepared By: Mr. Neeraj Kumar Srivastava 30


Java and Internet
• Applets (Legacy Use)
– Java introduced applets (small applications embedded in web
browsers), though they are now obsolete due to security
concerns and modern web technologies
• Networking Capabilities
– Java provides built-in networking support through the java.net
package, making it easy to develop client-server applications,
web services, and network-based tools
• Web Development
– Java is widely used in backend development through
frameworks like Spring Boot, Jakarta EE, and Servlets/JSP,
enabling dynamic and scalable web applications
• Security in Web Applications
– Java offers robust security mechanisms such as encryption,
authentication, and sandboxing to protect web applications
from threats
Prepared By: Mr. Neeraj Kumar Srivastava 31
Java and Internet
• Cloud Computing
– Java is extensively used in cloud environments due to its
scalability, portability, and strong community support,
powering platforms like AWS, Google Cloud, and Azure
• API and Web Services
– Java supports RESTful and SOAP-based web services using
technologies like JAX-RS, JAX-WS, and Spring REST,
making it a key language for API development
• Android Development
– Java is the primary language for Android applications,
making it a dominant force in mobile internet
applications
• Enterprise Applications
– Java is used in banking, e-commerce, and enterprise-level
web applications
Prepared By: Mr. Neeraj Kumar Srivastava 32
Java Support System
• Java Virtual Machine (JVM)
– Converts Java bytecode into machine-specific code,
enabling platform independence
• Java Runtime Environment (JRE)
– Provides libraries and JVM needed to run Java
applications
• Java Development Kit (JDK)
– Includes JRE, compiler (javac), and development tools for
writing Java programs
• Automatic Memory Management
– Java’s Garbage Collector (GC) handles memory allocation
and deallocation
• Multithreading Support
– Java allows concurrent execution of multiple tasks for
efficient performance
Prepared By: Mr. Neeraj Kumar Srivastava 33
Java Support System
• Exception Handling
– Robust error-handling mechanism with try-catch-
finally blocks to prevent crashes
• Security Framework
– Java provides encryption, authentication, and access
control for secure applications
• Rich Standard Library
– Java offers extensive built-in libraries for networking,
database, GUI, and more
• Community & Updates
– A strong developer community and regular updates
ensure continued support and improvements
Prepared By: Mr. Neeraj Kumar Srivastava 34
Java Environment
• Development tools-part of java development kit (JDK)
• Classes and methods-part of Java Standard Library (JSL),
also known as Application Programming Interface (API)
Java Development Kit (JDK):
I. Appletviewer ( for viewing applets)
II. Javac (Compiler)
III. Java (Interpreter)
IV. Javap (Java disassembler)
V. Javah (for C header files)
VI. Javadoc ( for creating HTML description)
VII. Jdb (Java Debugger)

Prepared By: Mr. Neeraj Kumar Srivastava 35


Java Environment
Application Package Interface (API)
– Contains hundreds of classes and methods grouped
into several functional packages:
I. Language Support Package
II. Utility Packages
III. Input/Output Packages
IV. Networking Packages
V. AWT Package
VI. Applet Package
Prepared By: Mr. Neeraj Kumar Srivastava 36
Java Virtual Machine (JVM)
• An engine that provides a runtime environment to
execute Java applications
• Converts Java bytecode into machine-specific code so
that Java programs can run on any device or operating
system that has a compatible JVM
• JVM is an essential part of the Java Runtime
Environment (JRE) and is responsible for the cross-
platform compatibility of Java

Bytecode:
– An intermediate, platform-independent code that the Java
compiler (javac) generates after compiling a Java source file
(.java)
– A low-level representation of Java code but is not directly
executable by the operating system
– Executed by the Java Virtual Machine (JVM), which translates
it into machine code specific
Prepared toKumar
By: Mr. Neeraj theSrivastava
underlying hardware 37
Java Virtual Machine (JVM)
Key Functions of JVM:
– Loads Java Bytecode – Compiled Java code (.class files) is
loaded into the JVM
– Interprets or Compiles Code – JVM interprets the bytecode
line-by-line or uses Just-In-Time (JIT) compilation to
convert bytecode into native machine code for better
performance
– Memory Management – Handles memory allocation and
garbage collection to remove unused objects
– Security – Provides a secure execution environment by
preventing unauthorized access to memory and resources
– Platform Independence – Java applications can run on
different platforms without modification, as long as the
platform has a compatible JVM

Prepared By: Mr. Neeraj Kumar Srivastava 38


Java Virtual Machine (JVM)
Components of JVM:
– Class Loader – Loads Java class files into memory.
– Runtime Memory Areas – Includes heap (for
object storage), stack (for method execution),
and method area (for class metadata).
– Execution Engine – Includes interpreters and JIT
compiler for executing bytecode.
– Garbage Collector – Manages automatic memory
deallocation

Prepared By: Mr. Neeraj Kumar Srivastava 39


Java Virtual Machine (JVM)

Prepared By: Mr. Neeraj Kumar Srivastava 40


Java Program Execution Process
• Java programs normally undergo with following
five phases:

– Edit:
• Programmer writes program (and stores program on disk)
– Compile:
• Compiler creates bytecodes from program
– Load:
• Class loader stores bytecodes in memory
– Verify:
• Verifier ensures bytecodes do not violate security
requirements
– Execute:
• Interpreter translates bytecodes into machine language

Prepared By: Mr. Neeraj Kumar Srivastava 41


Java Program Execution Process

Prepared By: Mr. Neeraj Kumar Srivastava 42


Java Program Execution Process

Prepared By: Mr. Neeraj Kumar Srivastava 43


Java Program Execution Process

Prepared By: Mr. Neeraj Kumar Srivastava 44


Java Program Structure

Prepared By: Mr. Neeraj Kumar Srivastava 45


A Sample Java Program
• A source file is officially called a compilation unit
• It is a text file that contains one or more class
definitions
• Java compiler requires that a source file must be
saved with .java extension
• In Java, all code must reside inside a class
• When Java source code is compiled:
– Each individual class is put into its own output file named
after the class and using the .class extension
– It is a good idea to save our Java source files with same
name as the class they contain
– Hence, the name of the source file will match the name of
the .class file

Prepared By: Mr. Neeraj Kumar Srivastava 46


A Sample Java Program

Prepared By: Mr. Neeraj Kumar Srivastava 47


Compiling a Java Program
• To compile the program, execute the compiler javac, specifying
the name of the source file on the command line:
C:\> javac Example.java
• It will create a file called Example.class that contains the
bytecode version of the program
• The output produced by javac is not directly executable
• To actually execute the program, we must use the Java
application launcher called java
• Pass the class name as a command-line argument with java
command:
C:\> java Example

• The output is as follows:


This is a sample java program.

Prepared By: Mr. Neeraj Kumar Srivastava 48


The main() Function
public static void main(String args[])
• Public Keyword:
– an access modifier that makes the member accessible
by code outside the class
– main( ) must be declared as public, since it must be
called by code outside of its class when the program is
started
• Static Keyword:
– allows main( ) to be called without having to
instantiate a particular instance of the class
– This is necessary since main( ) is called by the Java
Virtual Machine before any objects are made
• Void Keyword:
– void simply tells the compiler that main( ) does not
return a value
Prepared By: Mr. Neeraj Kumar Srivastava 49
The main() Function
• main( ) is the method called when a Java
application begins
• Java is case-sensitive Language
• Hence, Main is different from main (if we type
Main instead of main, the compiler would
generate the error)
• main() receives only one parameter:
String[ ] args
• Declares a parameter named args, which is an
array of instances of the class String
• args receives any command- line arguments
present when the program is executed

Prepared By: Mr. Neeraj Kumar Srivastava 50


The print()/println() Function
System.out.println("This is a sample Java program.");

• Produces output the string:


“This is a simple Java program.”
• Output is actually accomplished by the built-in
print()/println( ) method
– System is a predefined class that provides access to the
system
– out is the output stream that is connected to the console
the println( ) statement ends with a semicolon

Note: We can use printf() function (in java also) for


formatted I/O
Prepared By: Mr. Neeraj Kumar Srivastava 51
Tokens of Java

Prepared By: Mr. Neeraj Kumar Srivastava 52


Java Statements

Prepared By: Mr. Neeraj Kumar Srivastava 53


Java Statements
Control statements:
• Used to control the flow of execution based on
conditions and loops
• Help in decision-making, looping, and jumping to
different parts of the program
• Control statements are divided into three groups:
– Selection statements: allow the program to choose
different parts of the execution based on the outcome of
an expression
– iteration statements: enable program execution to repeat
one or more statements
– jump statements: enable your program to execute in a
non-linear fashion

Prepared By: Mr. Neeraj Kumar Srivastava 54


Java Statements

Prepared By: Mr. Neeraj Kumar Srivastava 55


Java Statements
for each loop:
• Also called as enhanced for loop
• Used to iterate over arrays and collections
without using an index
• Simpler and more readable compared to a
traditional for loop
Syntax:
for (dataType variable : collection)
{
// Code to execute
}

Prepared By: Mr. Neeraj Kumar Srivastava 56


Java Statements
Where-
– dataType: The type of elements in the collection (e.g.: int,
String)
– Variable: A temporary variable that holds each element
– Collection: The array or collection to iterate over
Example:
public class ForEachExample
{
public static void main(String[] args)
{
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers)
{
System.out.println(num);
}
}
}
Prepared By: Mr. Neeraj Kumar Srivastava 57
Java Statements
Jump Statements:
• Java jump statements enable transfer of control to
other parts of program
• Java provides three jump statements:
– break
– continue
– return
• In addition, Java supports exception handling that can
also alter the control flow of a program

Prepared By: Mr. Neeraj Kumar Srivastava 58


Data Types in Java

Prepared By: Mr. Neeraj Kumar Srivastava 59


Data Types in Java

Prepared By: Mr. Neeraj Kumar Srivastava 60


Constants and Variables in Java
• Constants:
– A constant is a variable which value cannot be
changed once assigned
– Remains fixed throughout the execution of the
program
– Constants are typically used to define values that
should remain unchanged, such as:
• mathematical constants (PI)
• configuration values
• default settings

Prepared By: Mr. Neeraj Kumar Srivastava 61


Constants and Variables in Java
• Constants:
– In Java, we use the final keyword to declare a constant
Syntax:
– final dataType CONSTANT_NAME = value;
Example:
– final double PI = 3.14159; // Declaring a constant
– Static keyword allows the constant to be accessed without
creating an instance of the class
Example:
– public static final int MAX_USERS = 100;
• Note:
– UPPER_CASE_NAMING is the convention for symbolic
constants
– It is often used as Symbolic Constants

Prepared By: Mr. Neeraj Kumar Srivastava 62


Constants and Variables in Java
• Types of Constants in Java:
– Numeric Constants
• Example: final int MAX_AGE = 100;
– Character Constants
• Example: final char GRADE = 'A';
– String Constants
• Example: final String MESSAGE = "Hello, Java!";
– Boolean Constants
• Example: final boolean IS_ACTIVE = true;

Prepared By: Mr. Neeraj Kumar Srivastava 63


Constants and Variables in Java
• Variable:
– A variable is a named memory location used to
store data that can be changed during program
execution
– Acts as a container for storing values
Syntax:
• dataType variableName = value;
Example:
• int age = 25; // 'age' is a variable of type int storing the value 25
• double pi = 3.14159; // 'pi' is a variable of type double

Prepared By: Mr. Neeraj Kumar Srivastava 64


Constants and Variables in Java
Important terms of variable declaration:
– Declaration: How to assign a type to a variable
– Initialization: How to give an initial value to a variable
– Scope: How the variable is visible to other parts of the program
– Lifetime: How the variable is created, used and destroyed
– Type conversion: How Java handles automatic type
conversion
– Type casting: How the type of a variable can be narrowed
down
– Type promotion: How the type of a variable can be expanded

Prepared By: Mr. Neeraj Kumar Srivastava 65


Type Casting and Type Conversion

• Type casting refers to converting one type to


another
• Done in following two ways:
– Implicit type conversion:
• Carried out by compiler automatically
– Explicit type conversion:
• Carried out by programmer using casting explicitly
• Syntax:
<targetVariable>= (targetType) value;

Prepared By: Mr. Neeraj Kumar Srivastava 66


Type Casting and Type Conversion

• Types of Direction of Type Conversion:


– Widening Type Conversion (Casting Up)
• Smaller Data Type to Larger Data Type
• Implicit conversion by the compiler, automatically

byte -> short, int, long, float, double


short -> int, long, float,
double char -> int, long,
float, double int -> long,
float, double
long -> float, double
float -> double

Prepared By: Mr. Neeraj Kumar Srivastava 67


Type Casting and Type Conversion

• Types of Direction of Type Conversion:


– Narrowing Type Conversion (Casting Down)
• Larger Data Type to Smaller Data Type
• Programmer should describe the conversion, explicitly

byte -> char


short -> byte, char
char -> byte, short
int -> byte, short, char
long -> byte, short, char, int
float -> byte, short, char, int, long
double -> byte, short, char, int, long, float

Prepared By: Mr. Neeraj Kumar Srivastava 68


Type Casting and Type Conversion

• Points to remember while type promotion:

– byte and short are always promoted to int


– if one operand is long, the whole expression is
promoted to long
– if one operand is float, the entire expression is
promoted to float
– if any operand is double, the result is double

Prepared By: Mr. Neeraj Kumar Srivastava 69


Constants and Variables in Java

Prepared By: Mr. Neeraj Kumar Srivastava 70


Constants and Variables in Java
• Local Variables
– Declared inside a method, constructor, or block
– Accessible only within that method or block
– Must be initialized before use
• Example:
public class Example
{
public void show()
{
int localVar = 10; // Local variable
System.out.println(localVar);
}
}

Prepared By: Mr. Neeraj Kumar Srivastava 71


Constants and Variables in Java
• Instance Variables (Non-Static Variables)
– Declared inside a class but outside any method
– Each object gets its own copy of instance variables
– Automatically initialized with default values
• Example:
public class Person
{
String name; // Instance variable
int age;
public void display() {
System.out.println("Name: " + name + ", Age: " + age); }
}

Prepared By: Mr. Neeraj Kumar Srivastava 72


Constants and Variables in Java
• Class Variables (Static Variables)
– Declared using the static keyword
– Shared among all objects of a class
– Stored in the method area of memory
– Can be accessed using the class name
• Example:
public class Employee
{
static String company = "Tech Corp"; // Static variable
public static void main(String[] args)
{
System.out.println("Company: " + Employee.company);
}
}

Prepared By: Mr. Neeraj Kumar Srivastava 73


Scope of Variables in Java

Prepared By: Mr. Neeraj Kumar Srivastava 74


Operators in Java
• An operator in Java is a special symbol that
performs operations on variables and values
• Operators are used to manipulate data, perform
calculations, and control program flow
• Types of operators in Java are:

Prepared By: Mr. Neeraj Kumar Srivastava 75


Operators in Java

Prepared By: Mr. Neeraj Kumar Srivastava 76


Operators in Java

Prepared By: Mr. Neeraj Kumar Srivastava 77


Operators in Java

Prepared By: Mr. Neeraj Kumar Srivastava 78


Operators in Java

Prepared By: Mr. Neeraj Kumar Srivastava 79


Operators in Java
• Ternary Operator
– Shortens conditional statements
variable = (condition) ? value_if_true : value_if_false;

• Instanceof Operator
– Checks if an object is an instance of a class

class Cat {}
class Dog {}
Dog d = new Dog();
System.out.println(d instanceof Cat); // false

Prepared By: Mr. Neeraj Kumar Srivastava 80


Expression Evaluation in JAVA
Expression:
• A combination of variables, operators, literals,
and method calls, is called an Expression
• Building blocks of Java programs, used in
calculations, assignments, conditions, loops
etc.
• Always evaluates to a single value
• Can be a simple arithmetic operation, a
comparison, a method call, or even an object
creation

Prepared By: Mr. Neeraj Kumar Srivastava 81


Expression Evaluation in JAVA
public class ExpressionExample {
public static void main(String[] args) { Output:
int a = 10, b = 5, c = 20; Sum: 110
Is sum greater than 100? true
// Arithmetic Expression Logical result: false
int sum = a + b * c; // sum = 10 + (5 * 20) = 110 Message: Large number
System.out.println("Sum: " + sum);
Breakdown of Expressions
// Relational Expression
boolean isGreater = sum > 100; // true used:
System.out.println("Is sum greater than 100? " + isGreater); • Arithmetic Expression
• Relational Expression
// Logical Expression • Logical Expression
boolean result = (a < b) && (b < c); // false && true = false • Ternary Expression
System.out.println("Logical result: " + result);

// Ternary Expression
String message = (sum > 100) ? "Large number" : "Small number";
System.out.println("Message: " + message);
}
}

Prepared By: Mr. Neeraj Kumar Srivastava 82


End of Unit I

Thank You
Prepared By: Neeraj Kumar Srivastava 83
Java Programming

Unit II
Classes and Inheritance

Mr. Neeraj Kumar Srivastava


Assistant Professor
Department of Computer Applications
Characteristics of OOPS
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
• Classes and Objects
• Message Passing
• Dynamic Binding

Prepared By: Neeraj Kumar Srivastava 2


Encapsulation
• One of the fundamental principles of OOPS
• It refers to bundling of:
– data (variables) and
– methods (functions) that operate on the data
• Combines data and methods into a single
unit (class)
• While restricting direct access to some
certain details

Prepared By: Neeraj Kumar Srivastava 3


Encapsulation
• Key Points:
– Data Hiding: The internal state of an object is
hidden from outside interference by using private
variables.
– Controlled Access: Public getter and setter methods
provide controlled access to the class's fields.
– Improved Maintainability: Code is easier to
manage, update, and debug.
– Increased Security: Prevents unauthorized access
and modification of data.
– Enhances Reusability: Encapsulation makes the
class more modular and reusable.

Prepared By: Neeraj Kumar Srivastava 4


Encapsulation

Prepared By: Neeraj Kumar Srivastava 5


Abstraction
• An object-oriented programming (OOP)
concept
• Focuses upon level of accessibility of
information
• Exposes only the relevant functionalities while
implementation details are kept hidden
• Simplifies software development by allowing
users to interact with objects through a well-
defined interface without knowing the
underlying details

Prepared By: Neeraj Kumar Srivastava 6


Abstraction
Key Points:
– Hides complexity by providing a simple and clear
interface
– Focuses on behavior rather than the implementation
details
– Achieved using abstract classes and interfaces in
programming languages like Java, C++, and Python
– Improves code readability, maintainability, and
modularity
– Encourages loose coupling by reducing dependencies
between different components
Prepared By: Neeraj Kumar Srivastava 7
Abstraction
Key Points:
– Restricts direct access to implementation details,
increasing security
– Helps in scalability by allowing changes in
implementation without affecting users
– Used in real-world applications, such as ATMs (users
interact with a machine without knowing its internal
processing)
– Example:
• Smartphone provides an easy-to-use interface with apps
and buttons, but the user doesn’t need to understand how
the internal circuits, processors, and software work

Prepared By: Neeraj Kumar Srivastava 8


Inheritance
• The ability to adopt attributes and methods
from parent to its children
• Promotes reusability of code
Types:
– Single Inheritance
– Multilevel Inheritance
– Hierarchal Inheritance
Note:
Java does not support multiple inheritance using
classes to avoid ambiguity, but it can be achieved
using interfaces
Prepared By: Neeraj Kumar Srivastava 9
Polymorphism
• Polymorphism means “many forms”
• Allows an object to behave differently based on the
context
• Enhances flexibility and scalability in code

Types of Polymorphism in Java:

– Compile-Time Polymorphism (Method Overloading)


• Multiple methods in the same class with the same name but
different parameters

– Runtime Polymorphism (Method Overriding)


• A child class provides a different implementation of a method
already defined in its parent class

Prepared By: Neeraj Kumar Srivastava 10


Class and Objects
Class:

• Fundamental OOP Building Block:


– Essential for object-oriented programming in Java
• Blueprint/Template:
– Defines the structure and behavior for objects
• Data (Fields/Attributes):
– Variables holding object information (e.g., color, name)
• Behavior (Methods):
– Functions defining what objects can do (e.g., start, calculate)
• Object Factory:
– Used to create multiple individual objects (instances)

Prepared By: Neeraj Kumar Srivastava 11


Class and Objects
• A class contains:

– Fields: Object data/characteristics.


– Methods: Object behaviors/actions.
– Constructors: Initialize new objects.
– Nested Classes: Classes within a class.
– Interfaces: Contracts for behavior.

Prepared By: Neeraj Kumar Srivastava 12


Class and Objects
• Object:
– Real-world entity: Represents a concrete thing
– Instance of a class: Created based on a class blueprint
– Has state: Stores data through its attributes (fields)
– Has behavior: Can perform actions defined by its
methods
– Unique identity: Each object is distinct in memory.
– Brings a class to life: Makes the abstract class concrete
– Multiple objects from one class: You can create many
instances
– Own data, shared behavior: Each object has its own
attribute values but uses the methods defined in its class

Prepared By: Neeraj Kumar Srivastava 13


Class and Objects
• Different ways to create an object:
– By new keyword
– By newInstance() methods
– By clone() method
– By deserialization
– By factory method

Prepared By: Neeraj Kumar Srivastava 14


Class and Objects
• Anonymous Object:
– An object that is created without an explicit
name or reference variable
– We use it only once, right at the point of
creation, and then it becomes eligible for
garbage collection
– Syntax:
new ClassName([arguments]);
– Useful for one-time use, method arguments, or
simple returns
– Reduces code verbosity for single-use scenarios
Prepared By: Neeraj Kumar Srivastava 15
Class and Objects
• Anonymous Object Example:
class MessagePrinter
{
void printMessage(String message)
{
System.out.println("Message: " + message);
}
}

Prepared By: Neeraj Kumar Srivastava 16


Class and Objects
• Anonymous Object Example:
public class Test
{
public static void main(String[] args)
{
// Using a named object
MessagePrinter namedPrinter = new MessagePrinter();
namedPrinter.printMessage("Hello, named object!");

// Using an anonymous object


new MessagePrinter().printMessage("Hello, anonymous object!");
}
}

Prepared By: Neeraj Kumar Srivastava 17


Class and Objects
• Creating multiple objects of same type
class Car
{
String model;
String color;
public void setCar(String model, String color)
{
this.model = model;
this.color = color;
}
public void displayDetails()
{
System.out.println("Model: " + model + ", Color: " + color);
}
}
Prepared By: Neeraj Kumar Srivastava 18
Class and Objects
• Creating multiple objects of same type
public class Garage
{
public static void main(String[] args)
{
// Creating multiple objects
Car car1 = new Car(), car2 = new Car();
car1.setCar(“Sedan”, “Red”);
car2.setCar(“SUV”, “Black”);
car1.displayDetails();
car2.displayDetails();
}
} Prepared By: Neeraj Kumar Srivastava 19
Class and Objects
• Object Destruction:
• A program accumulates memory through its
execution
• Two mechanisms to free memory that is no
longer needed by program are:
– Manual – used in C/C++
– Automatic – used in Java
• In Java, when an object is no longer accessible
through any variable, it is eventually removed
from the memory by the garbage collector
• Garbage collector is parts of the Java Run-Time
Environment
Prepared By: Neeraj Kumar Srivastava 20
Class and Objects
• Ways to initialize an object:
– By reference variable
– By method()
– By constructor

Prepared By: Neeraj Kumar Srivastava 21


Abstract Method
Definition:
– A method declared without an implementation (no body)
– Ends with a semicolon ; instead of a method body
– Abstract methods can only exist in abstract classes or
interfaces
– All subclasses (non-abstract) must provide an implementation
for the abstract method
– Used to enforce that subclasses implement specific methods

Syntax:
– abstract returnType methodName();

Example:
– abstract void area();

Prepared By: Neeraj Kumar Srivastava 22


Abstract Method
Example:
abstract class Animal
{
abstract void sound(); // abstract method
}

class Dog extends Animal


{
void sound()
{
System.out.println("Woof");
}
}

Prepared By: Neeraj Kumar Srivastava 23


Abstract Method
Example:
class Test
{
public static void main(String[] args)
{
Animal myObject= new Dog();
myObject.sound();
}
}

Output: Woof
Prepared By: Neeraj Kumar Srivastava 24
Static Members
• Belong to the class, not to any specific object
• Declared using static Keyword
• Stored in the method area of JVM memory
• Allocated only once when the class is loaded
• Since static methods do not belong to a
specific object, they cannot use this
(instance reference) or super (parent
reference)

Prepared By: Neeraj Kumar Srivastava 25


Static Members
• Types:
– Static Variables:
• Shared among all instances of a class
– Static Methods:
• Can be called without creating an object
– Static Blocks:
• Used for initialization of static data

Prepared By: Neeraj Kumar Srivastava 26


Static Variable
• A class-level variable shared among all
instances of the class
• Stored in the method area and allocated
only once when the class is loaded
• Any changes to the static variable reflect
across all objects

Prepared By: Neeraj Kumar Srivastava 27


Static Variable
Example:
class Counter
{
static int count = 0; // Static variable

Counter()
{
count++; // Increments the static variable
}

void showCount()
{
System.out.println("Count: " + count);
}
}
Prepared By: Neeraj Kumar Srivastava 28
Static Variable
Example:
public class Test
{
public static void main(String[] args)
{
Counter obj1 = new Counter();
Counter obj2 = new Counter();
Counter obj3 = new Counter();

obj1.showCount(); // Output: Count: 3


obj2.showCount(); // Output: Count: 3
obj3.showCount(); // Output: Count: 3
}
}

Prepared By: Neeraj Kumar Srivastava 29


Static Method
• Belongs to the class rather than any specific
instance (object)
• Can be called using the class name instead
of an object
• Since static methods do not belong to an
object, they cannot access instance variables
or methods directly
• Static methods can only work with static
variables and other static methods
Prepared By: Neeraj Kumar Srivastava 30
Static Method
Example:
class MathUtil class Test
{ {
// Static method public static void main(String[] args)
static int square(int num) {
{ // Calling static method using class name
return num * num; int result = MathUtil.square(5);
} System.out.println("Square of 5: " + result);
} }
}

Output: Square of 5: 25

Prepared By: Neeraj Kumar Srivastava 31


Static Method
• Restrictions:
– Static methods can only access static variables,
not instance (non-static) variables
– Static methods cannot invoke instance methods
directly
– Since static methods do not belong to an
instance, they cannot use this or super
– Static methods do not support runtime
polymorphism; they are hidden, not overridden
– Static methods can call only static variables and
other static methods

Prepared By: Neeraj Kumar Srivastava 32


Java Static Block
• A block of code inside a class that runs once
when the class is loaded into memory
• Written inside a class but outside methods
• Runs before the main() method and before
any object is created
• Typically used to initialize static variables
• If a class has multiple static blocks, they
execute in the order they appear in a class

Prepared By: Neeraj Kumar Srivastava 33


Java Static Block
Example 1: Basic static block execution
class Example
{
static
{
System.out.println("Static Block Executed");
}

public static void main(String[] args)


{
System.out.println("Main Method Executed");
}
}
Output: Static Block Executed
Main Method Executed
Prepared By: Neeraj Kumar Srivastava 34
Java Static Block
Example 2: Initializing static variable
class Example
{
static int value;
static
{
value = 50;
System.out.println("Static Block: Initializing value");
}
public static void main(String[] args)
{
System.out.println("Main Method: Value = " + value);
}
}

Prepared By: Neeraj Kumar Srivastava 35


Java Static Block
Example 3: Multiple static blocks
class Example
{
static
{
System.out.println("Static Block 1");
}
static
{
System.out.println("Static Block 2");
}

public static void main(String[] args)


{
System.out.println("Main Method Executed");
}
}
Prepared By: Neeraj Kumar Srivastava 36
Garbage Collection
• A process of automatically reclaiming
memory occupied by objects that are no
longer in use is called Garbage Collection
• Java’s GC runs in the background and frees
unused objects to prevent memory leaks
• Unlike C/C++, Java does not require manual
memory management, GC handles it
• Removes unreferenced objects from the
heap to free up space
Prepared By: Neeraj Kumar Srivastava 37
Garbage Collection
• Runs when needed, but we can explicitly use it
using:
– System.gc(); // Suggests garbage collection
• GC invokes finalize() method
• Objects become eligible for GC when no active
references exist
• Java provides
– Serial GC,
– Parallel GC,
– CMS GC
– G1 GC
• each optimized for different applications

Prepared By: Neeraj Kumar Srivastava 38


Garbage Collection
Example:
class Example
{
protected void finalize()
{
System.out.println("Garbage Collected");
}

public static void main(String[] args)


{
Example obj1 = new Example();
Example obj2 = new Example();

obj1 = null; // Making object eligible for GC


obj2 = null;

System.gc(); // Requesting GC
}
}

Output: Garbage Collected


Garbage Collected

Prepared By: Neeraj Kumar Srivastava 39


Java Inheritance
• A mechanism in Java where one class
(child/subclass) acquires the properties and
behaviors of another class (parent/superclass)
• Promotes code reusability and reduces
redundancy by allowing child classes to use
existing functionalities
• The main idea behind inheritance is to create
new classes that are built upon existing classes
• We can reuse the attributes and methods of
parent class while adding new attributes and
methods to current class
Prepared By: Neeraj Kumar Srivastava 40
Java Inheritance

Prepared By: Neeraj Kumar Srivastava 41


Java Inheritance
• Represents IS-A Relationship which is also
known as Parent-Child Relationship
• In Java, inheritance is used for Method
Overriding, hence, to achieve Runtime
Polymorphism

• Key Benefits of Inheritance


– Code Reusability
– Maintainability
– Improved Readability

Prepared By: Neeraj Kumar Srivastava 42


Java Inheritance

Prepared By: Neeraj Kumar Srivastava 43


Java Inheritance
Syntax –
The extends keyword is used to inherit from
a class:

class Parent class Child extends Parent


{ {
//code for Parent //code for child
} }

Prepared By: Neeraj Kumar Srivastava 44


Java Inheritance
Example of Inheritance in Java
class Animal
{
void makeSound()
{
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal


{
void bark()
{
System.out.println("Dog barks");
}
}

Prepared By: Neeraj Kumar Srivastava 45


Java Inheritance
Example of Inheritance in Java
public class Test
{
public static void main(String[] args)
{
Dog myDog = new Dog();
myDog.makeSound(); // Inherited method
myDog.bark(); // Dog's own method
}
}

Prepared By: Neeraj Kumar Srivastava 46


Java Inheritance
• Types of Inheritance in Java:
– Single Inheritance – One class inherits another
– Multilevel Inheritance – A child inherits from a
parent, and another child inherits from it
– Hierarchical Inheritance – Multiple child classes
inherit from the same parent

• Multiple Inheritance (Class Level) – Not


supported directly through classes due to
ambiguity issues

Prepared By: Neeraj Kumar Srivastava 47


Java Inheritance

Prepared By: Neeraj Kumar Srivastava 48


Single Inheritance
// Parent class (Base Class)
class Animal
{
void eat()
{
System.out.println("Animals eats");
}
}
// Child class (Derived Class) inheriting from Animal
class Dog extends Animal
{
void bark()
{
System.out.println("Dog barks");
}
}
Prepared By: Neeraj Kumar Srivastava 49
Single Inheritance
// Main class to test inheritance
public class SingleInheritanceExample
{
public static void main(String[] args)
{
Dog myDog = new Dog();
myDog.eat(); // Inherited method from Animal class
myDog.bark(); // Method in Dog class
}
}

Output:

Animal eats
Dog barks

Prepared By: Neeraj Kumar Srivastava 50


Multi-Level Inheritance
// Parent class (Base Class)
class Animal
{
void eat()
{
System.out.println("Animals eats");
}
}
// Child class (Derived Class) inheriting from Animal
class Dog extends Animal
{
void bark()
{
System.out.println("Dog barks");
}
}
Prepared By: Neeraj Kumar Srivastava 51
Multi-Level Inheritance
// Child class (Derived Class) inheriting from Dog
Class Puppy extends Dog
{
void weep()
{
System.out.println(“Puppy weeps");
}
}

Prepared By: Neeraj Kumar Srivastava 52


Multi-Level Inheritance
// Main class to test inheritance
public class TestInheritance
{
public static void main(String[] args)
{
Puppy myPuppy = new Puppy();
myPuppy.eat(); // Inherited method from Animal class
myPuppy.bark(); // Inherited method from Dog class
myPuppy.weep(); //Method in Puppy class
}
}

Output:

Animal eats
Dog barks
Puppy weeps
Prepared By: Neeraj Kumar Srivastava 53
Hierarchical Inheritance
// Parent class (Base Class)
class Animal
{
void eat()
{
System.out.println("Animals eats");
}
}
// Child class (Derived Class) inheriting from Animal
class Dog extends Animal
{
void bark()
{
System.out.println("Dog barks");
}
}
Prepared By: Neeraj Kumar Srivastava 54
Hierarchical Inheritance
// Child class (Derived Class) inheriting from Animal
Class Cat extends Animal
{
void meow()
{
System.out.println(“Cat meows");
}
}

Prepared By: Neeraj Kumar Srivastava 55


Hierarchical Inheritance
// Main class to test inheritance
public class TestInheritance
{
public static void main(String[] args)
{
Cat myCat = new Cat();
myCat.eat(); // Inherited method from Animal class
myCat.meow(); // Method from Cat class
myCat.bark(); //Compile Time error
}
}

Output:

Animal eats
Cat meows

Prepared By: Neeraj Kumar Srivastava 56


Multiple Inheritance
• Multiple inheritance can cause ambiguity, when two
parent classes have methods with the same signature
• Java does not support multiple inheritance directly for the
following reasons:
– Maintains Simplicity
• Eliminates the complexity of method resolution and conflicts
– Ensures Reliability
• Prevents issues arising from different parent classes modifying
shared state inconsistently
– Encourages Composition
• Java promotes interface-based design and composition over
inheritance
– Supports Interfaces Instead
• Java allows multiple interface implementation to achieve similar
functionality without ambiguity
– Improves Maintainability
• Easier to manage and debug without multiple inheritance
complexities Prepared By: Neeraj Kumar Srivastava 57
Multiple Inheritance
class A class B
{ {
void show() void show()
{ {
System.out.println(“Hello"); System.out.println(“Welcome");
} }
} }

class C extends A,B //Suppose, if it were


{
public static void main(String[] args)
{
C myObject = new C();
myObject.show(); //which method will be invoked
}
}
Output: Compile Time Error
Prepared By: Neeraj Kumar Srivastava 58
Constructor and Inheritance
• Constructors are not inherited but can be
called using super()
• A child class constructor must call a parent
class constructor (implicitly or explicitly)
• If a parent class has only parameterized
constructors, the child class must explicitly call
one using super(arguments)
• If no constructor is defined in the child class,
Java provides a default constructor that calls
the parent’s default constructor
• The super() call must be the first statement in
the child class constructor
Prepared By: Neeraj Kumar Srivastava 59
Constructor and Inheritance
• Constructors cannot be overridden, but they
can be overloaded within the same class
• If the parent class has a private constructor, the
child class cannot instantiate it
• A constructor cannot be static or final because
it is tied to object creation
• Abstract classes can have constructors, and
they are called when a subclass object is
created
• Interfaces do not have constructors because
they cannot be instantiated directly

Prepared By: Neeraj Kumar Srivastava 60


Method Overriding in Java
• If a subclass has the same method as declared
in the parent class, it is known as Method
Overriding
• A subclass can override a method from the
parent class to provide a specific
implementation
• Used for Runtime Polymorphism
• Super Keyword is used to access the parent
class constructor, methods, or variables inside
a child class

Prepared By: Neeraj Kumar Srivastava 61


Method Overriding in Java

Prepared By: Neeraj Kumar Srivastava 62


Method Overriding in Java
• A Real World Example of Java Method
Overriding
– Consider a scenario where Bank is a class that
provides functionality to get the rate of interest.]
– However, the rate of interest varies according to
banks
– For example, SBI, ICICI and AXIS banks could
provide 8.2%, 7.9%, and 9.6% rate of interest.

Prepared By: Neeraj Kumar Srivastava 63


Method Overriding in Java

Prepared By: Neeraj Kumar Srivastava 64


Method Overriding in Java
// Parent class // Child class - SBI Bank
class Bank class SBI extends Bank
{ {
// Method to be overridden // Overriding method
double getRateOfInterest() double getRateOfInterest()
{ {
return 0.0; // Default interest rate return 8.2; // SBI's interest rate
} }
} }

// Child class - ICICI Bank // Child class - AXIS Bank


class ICICI extends Bank Class AXIS extends Bank
{ {
// Overriding method // Overriding method
double getRateOfInterest() double getRateOfInterest()
{ {
return 7.9; // ICICI's interest rate return 9.6; // AXIS's interest rate
} }
} }
Prepared By: Neeraj Kumar Srivastava 65
Method Overriding in Java
// Main class

public class MethodOverridingExample


{
public static void main(String[] args)
{
Bank s = new SBI();
Bank i = new ICICI();
Bank a = new AXIS();

System.out.println("SBI Rate of Interest: " + s.getRateOfInterest() + "%");


System.out.println(“ICICI Rate of Interest: " + i.getRateOfInterest() + "%");
System.out.println(“AXIS Rate of Interest: " + a.getRateOfInterest() + "%");
}
}

Prepared By: Neeraj Kumar Srivastava 66


Method Overriding in Java
• Important Questions:
– Que: Can we override static method?
• No, a static method cannot be overridden. It can be proved
by runtime polymorphism.
– Que: Why can we not override static method?
• It is because the static method is bound with class whereas
instance method is bound with an object. Static belongs to
the class area, and an instance belongs to the heap area.
– Que: Can we override java main method?
• No, because the main is a static method.
– Que: Differentiate between Method Overloading and
Method Overriding.
•? Prepared By: Neeraj Kumar Srivastava 67
Final Keyword in Java
• A final keyword used to restrict the user
• Can be applied to variables, methods, and
classes
– 1. Final Variable
• Value cannot be changed once assigned
• Acts like a constant
– 2. Final Method
• Cannot be overridden by subclasses
• Useful for preserving the behavior of the method
– 3. Final Class
• Cannot be inherited
• Prevents other classes from extending it

Prepared By: Neeraj Kumar Srivastava 68


Final Variable
public class FinalVariableExample
{
public static void main(String[] args)
{
final int x = 10; //final variable
System.out.println("Value of x: " + x);
x = 20; // ❌ Error
System.out.println("Value of x: " + x);
}
}

Output: Error-cannot assign a value to final variable

Prepared By: Neeraj Kumar Srivastava 69


Final Method
class Animal
{
final void sound()
{
System.out.println("Animal makes sound");
}
}

class Dog extends Animal


{
void sound() //❌ Error
{
System.out.println("Dog barks");
}
}
Output: Error- Cannot override final method
Prepared By: Neeraj Kumar Srivastava 70
Final Class
final class Vehicle
{
void display()
{ System.out.println("This is a vehicle"); }
}

class Car extends Vehicle //❌ Error


{

}
public class FinalClassExample
{
public static void main(String[] args)
{
Vehicle v = new Vehicle();
v.display();
}
}
Output: Error: Cannot inherit from
Prepared By: final class
Neeraj Kumar Srivastava 71
Blank Final Variable
• A final variable that is not initialized at the time
of declaration is known as blank final variable
• Often initialized at the time of creating object
and once initialized may not be changed
– For example:
• PAN number of an employee
• AADHAR number of a student
• Enrollment number of a students
• Account number of a customer, etc.
• Can be initialized only in constructor

Prepared By: Neeraj Kumar Srivastava 72


Blank Final Variable
class Student
{
final int rollNumber; // Blank final variable
Student(int roll) // Constructor
{
rollNumber = roll; // must assign value here
}
void display()
{
rollNumber = roll; // not allowed here
System.out.println("Roll Number: " + rollNumber);
}
}

public class Test


{
public static void main(String[] args)
{
Student s1 = new Student(101);
s1.display();
}
}

Prepared By: Neeraj Kumar Srivastava 73


Static Blank Final Variable
• A static final variable, not initialized at the time of declaration is known
as static blank final variable
• Can be initialized only in static block.

Example of static blank final variable


classA
{
static final int data; //static blank final variable
static
{
data=50;
}
public static void main(String[] args)
{
System.out.println(A.data);
}
}
Prepared By: Neeraj Kumar Srivastava 74
Final Parameter
• If we declare any parameter as final, we cannot change its value
class Bike
{
int cube(final int n)
{
n=n+2; //can't be changed as n is a final variable
n=n*n*n;
}
public static void main(String[] args)
{
Bike b=new Bike();
b.cube(5);
}
}

Output: Compile Time Prepared


ErrorBy: Neeraj Kumar Srivastava 75
Super Keyword in Java
• A reference variable, which is used to refer
immediate parent class
• Whenever an instance of subclass is created,
an instance of parent class is created
implicitly referred by super keyword
• Use of super keyword:
– To access instance variable of immediate parent
– To access instance method of immediate parent
– To access the constructor of immediate parent

Prepared By: Neeraj Kumar Srivastava 76


Accessing Instance Variable
class Animal
{
String type = "Animal";
}
class Dog extends Animal
{
String type = "Dog";
void printType()
{
System.out.println("Child class type: " + type);
System.out.println("Parent class type: " + super.type); // Access parent variable
}
}
public class TestVariable
{
public static void main(String[] args)
{
Dog d = new Dog();
d.printType();
}
}
Output: Child class type: Dog
Parent class type: Animal
Prepared By: Neeraj Kumar Srivastava 77
Accessing Instance Method
class Animal
{
void sound()
{
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal
{
void sound()
{
super.sound(); // Call parent class method
System.out.println("Dog barks");
}
}
class TestMethod
{
public static void main(String[] args)
{
Dog d = new Dog();
d.sound();
}
}

Output: Animal makes sound


Dog barks Prepared By: Neeraj Kumar Srivastava 78
Accessing Constructor
class Animal
{
Animal()
{
System.out.println("Animal constructor called");
}
}

class Dog extends Animal


{
Dog()
{
super(); // Calls parent constructor as first instruction
System.out.println("Dog constructor called");
}
}
public class TestConstructor
{
public static void main(String[] args)
{
Dog d = new Dog();
}
}

Note: super() must be the first instruction.


Output: Animal constructor called
Dog constructor called Prepared By: Neeraj Kumar Srivastava 79
Accessing Constructor
• As default constructor is provided by compiler
automatically, if there is no constructor
• It also adds super() as the first statement
class Animal class Dog extends Animal
{ {
Animal() Dog()
{ {
System.out.println("animal is created"); System.out.println("dog is created");
} }
} }
Jnnkl
Class TestSuper
{
Kljk
{
public static void main(String[] args)

Zklcvjkl
}
Dogd=newDog();

}
K;cvj;k
Output : animal is created dog is created

Prepared By: Neeraj Kumar Srivastava 80


Accessing Constructor
Note: super() is added in each class constructor
automatically by compiler if there is no
super().

Prepared By: Neeraj Kumar Srivastava 81


Real use of super Keyword
class Person class Emp extends Person
{ {
int id; float salary;
String name; Emp(int id,String name,float salary)
Person(int id,String name) {
{ super(id,name); //reusing parent constructor
this.id=id; this.salary=salary;
this.name=name; }
} void display()
} {
System.out.println(id+""+name+""+salary);
}
}
classTestSuper
{
public static void main(String[] args)
{
Emp e=new Emp(1,"ankit",45000f);
e.display();
}
}

Output: 1 ankit 45000


Prepared By: Neeraj Kumar Srivastava 82
this Keyword in Java

Prepared By: Neeraj Kumar Srivastava 83


finalize Method in Java
• A method called by Garbage Collector just
before the deletion/destroying the object
which is eligible for Garbage Collection
• Performs clean-up activity
– Clean-up activity means:
• Closing the resources associated with that object like
Database Connection
• Closing network connection (resource de-allocation)
• Remember it is not a reserved keyword
• Once the finalize method completes, Garbage
Collector immediately destroys that object

Prepared By: Neeraj Kumar Srivastava 84


finalize Method in Java
• Object class contains the finalize method
• Object is the super class of all java classes
• finalize method is available for every java
class
• Garbage Collector can call the finalize
method on any java object
Syntax:
protected void finalize throws Throwable{ }

Prepared By: Neeraj Kumar Srivastava 85


finalize Method in Java
Que: Why finalize method is used()?
Ans:
• finalize() method releases system resources
before the garbage collector runs for a
specific object
• JVM allows finalize() to be invoked only
once per object

Prepared By: Neeraj Kumar Srivastava 86


finalize Method in Java
class JavafinalizeExample
{
protected void finalize()
{
System.out.println("finalizemethodcalled");
}
public static void main(String[] args)
{
JavafinalizeExample obj= new JavafinalizeExample();
System.out.println(obj.hashCode());
obj=null;//callinggarbagecollector
System.gc();
System.out.println(“End of Garbage Collection");
}
}
Output: 2018699554
finalize method called
End of Garbage
Prepared By:Collection
Neeraj Kumar Srivastava 87
Abstract Class in Java
Abstraction in Java:
• Abstraction is a process of hiding the
implementation details and showing only
functionality to the user
• Abstraction lets us focus on what the object
does instead of how it does it
Ways to achieve Abstraction:
1. Abstract class (0 to 100%)
2. Interface (100%)
Prepared By: Neeraj Kumar Srivastava 88
Abstract Class in Java
• A class which is declared with the abstract
keyword is known as an abstract class in Java
• Contains abstract and non-abstract methods
(method with the body)
• Cannot be instantiated
• Can have constructors and static methods also
• Can have final methods which will force the
subclass not to change body of method
Syntax:
abstract class Test {}

Prepared By: Neeraj Kumar Srivastava 89


End of Unit II

Thank You
Prepared By: Neeraj Kumar Srivastava 90
Java Programming

Unit III
Array, Interface and Exception Handling

Mr. Neeraj Kumar Srivastava


Assistant Professor
Department of Computer Applications
Array in Java
• Collection of elements of similar data type
• Stored at contiguous locations in memory
• In Java, array is an object
• A fixed set of elements can be stored
• An indexed based data structure
• Elements can be accessed directly

Prepared By: Neeraj Kumar Srivastava 2


Array in Java
Advantages:
– Code Optimization: It makes the code optimized, we
can retrieve or sort the data efficiently
– Random access: We can get any data located at an
index position
Limitations:
– Size Limit:
• fixed number of elements in the array
• doesn't grow its size at runtime
• To solve this problem, collection framework is used in Java
which grows automatically
Prepared By: Neeraj Kumar Srivastava 3
Types of Array
• Mainly two types:
– Single Dimensional:
• Normally, elements are organized in form of single
row

– Multi Dimensional:
• Elements are organized in form of matrix having rows
and columns

Prepared By: Neeraj Kumar Srivastava 4


Single Dimensional Array
Declaration:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation:

arrayRefVar=new datatype[size];

Prepared By: Neeraj Kumar Srivastava 5


Single Dimensional Array
class TestArray
{
public static void main(String[] args)
{
int a[]=new int[5]; //declaration and instantiation
//initialization
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}

Output: 10 20 70 40 50
Prepared By: Neeraj Kumar Srivastava 6
Single Dimensional Array
class TestArray
{
public static void main(String args[])
{
//declaration, instantiation and initialization
int a[]={33,3,4,5};
//traversing array
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
Output: 33 3 4 5
Prepared By: Neeraj Kumar Srivastava 7
Single Dimensional Array
Accessing array elements using for each loop:
class TestArray
{
public static void main(String[] args)
{
int arr[]={33,3,4,5};
//traversing array using for-each loop
for(int i:arr)
System.out.println(i);
}
}

Output: 33 3 4 5
Prepared By: Neeraj Kumar Srivastava 8
Single Dimensional Array
Passing an array to method:
class TestArray
{
//creating a method which receives an array as a parameter
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5}; //declaring and initializing an array
min(a); //passing array to method
}
}
Output: 3
Prepared By: Neeraj Kumar Srivastava 9
Single Dimensional Array
Returning an array from the method:
class TestReturnArray
{
//creating method which returns an array
static int[] get()
{
return new int[]{10,30,50,90,60};
}
public static void main(String args[])
{
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
Output: 10 30 50 90 60 Prepared By: Neeraj Kumar Srivastava 10
Anonymous Array in Java
Java supports the feature of an anonymous array, so we don't need to declare
the array while passing an array to the method:
public class TestAnonymousArray
{
//creating a method which receives an array as a parameter
static void printArray(int arr[])
{
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[])
{
printArray(new int[]{10,22,44,66}); //passing anonymous array to method
}
}

Output: 10 22 44 66
Prepared By: Neeraj Kumar Srivastava 11
Array Exception in Java
• JVM throws following exception:

ArrayIndexOutOfBoundsException

• if length of the array:


– in negative,
– equal to the array size
– greater than the array size

Prepared By: Neeraj Kumar Srivastava 12


Array Exception in Java
public class TestArrayException
{
public static void main(String args[])
{
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++)
System.out.println(arr[i]);
}
}

Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException:
4 at TestArrayException.main(TestArrayException.java:5)

Prepared By: Neeraj Kumar Srivastava 13


Multidimensional Array
Declaration:
dataType[][] arrayRefVar; (or)
dataType [][] arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Instantiation:
//3 row and 3 column
int[][] arr=new int[3][3];

Prepared By: Neeraj Kumar Srivastava 14


Multidimensional Array
Example:
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Prepared By: Neeraj Kumar Srivastava 15


Multidimensional Array
class TestArray
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
1 2 3
Output: 2 4 5
4 4 5 Prepared By: Neeraj Kumar Srivastava 16
Jagged Array in Java
• An array of arrays with different number of
columns
• In other words, an array having odd number of
columns in a 2D array
1 2 4
2 4 6 8
2 6
3 7 9 4 1
3 7 9

Jagged Array
Prepared By: Neeraj Kumar Srivastava 17
Jagged Array in Java
class TestJaggedArray //printing the data of a jagged array
{ for (int i=0; i<arr.length; i++)
public static void main(String[] args) {
{ for (int j=0; j<arr[i].length; j++)
//declaring a 2D array with odd columns {
int arr[][] = new int[3][]; System.out.print(arr[i][j]+" ");
arr[0] = new int[3]; }
arr[1] = new int[4]; System.out.println();//new line
arr[2] = new int[2]; }
//initializing a jagged array } // end of main
int count = 0; } //end of class
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

Output: 375
9641
28
Prepared By: Neeraj Kumar Srivastava 18
Copy Operation on Array
• To copy an array onto another, the arraycopy()
method of System class is used
Syntax:
public static void arraycopy(Object src, int
srcPos,Object dest, int destPos, int length)
– Object src: The source object
– Int srcPos: The position from source object
– Object Des: The destination object
– Int destPos: The position in destination object
– Int length: The number of characters to be copied

Prepared By: Neeraj Kumar Srivastava 19


Copy Operation on Array
class TestArrayCopy
{
public static void main(String[] args)
{
//declaring a source array
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e‘, 'i', 'n', 'a', 't', 'e', 'd' };
//declaring a destination array
char[] copyTo = new char[7];
//copying array
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
//printing the destination array
System.out.println(String.valueOf(copyTo));
}
}

Output: caffein
Prepared By: Neeraj Kumar Srivastava 20
Wrapper Classes
• Wraps the primitive data types, that is why it is
known as wrapper classes
• Provides the mechanism to convert primitive
into object and object into primitive types
• Since J2SE 5.0, autoboxing and unboxing
features work automatically
– autoboxing: automatic conversion of primitive into
an object
– unboxing: automatic conversion of object into an
primitive

Prepared By: Neeraj Kumar Srivastava 21


Autoboxing
public class AutoboxingExample
{
public static void main(String args[])
{
//Converting int into Integer
int a=20;
//converting int into Integer explicitly
Integer i=Integer.valueOf(a);
Integer j=a; //autoboxing
System.out.println(a+" "+i+" "+j);
}
}

Output: 20 20 20
Prepared By: Neeraj Kumar Srivastava 22
Unboxing
public class UnboxingExample
{
public static void main(String args[])
{
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue(); //converting Integer to int explicitly
int j=a; //unboxing
System.out.println(a+" "+i+" "+j);
}
}

Output: 3 3 3

Prepared By: Neeraj Kumar Srivastava 23


Wrapper Class
• The eight classes of the java.lang package are
known as wrapper classes in Java
• The list of eight wrapper classes are given
below:

Primitive Type Wrapper Class


boolean char Boolean
byte short int Character
long float Byte Short
double Integer Long
Float Double

Prepared By: Neeraj Kumar Srivastava 24


Use of Wrapper Class in Java
• Change the value in Method
– Java supports only call by value
– So, if we pass a primitive value, it will not change the
original value
– But, if we convert the primitive value in an object, it
will change the original value.
• Serialization
– We need to convert the objects into streams to
perform the serialization

Prepared By: Neeraj Kumar Srivastava 25


Use of Wrapper Class in Java
• Synchronization
– Java synchronization works with objects in
Multithreading
• java.util package
– Provides the utility classes to deal with objects
• Collection Framework
– Java collection framework works with objects only
– All classes of the collection framework (ArrayList,
LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects
only
Prepared By: Neeraj Kumar Srivastava 26
Vector in Java
• Vector is like the dynamic array
• Can grow or shrink its size, dynamically
• Unlike array, we can store n-number of elements
in it as there is no size limit
• It is a part of Java Collection framework since
Java 1.2.
• It is found in the java.util package and implements
the List interface
• We can use all the methods of List interface here

Prepared By: Neeraj Kumar Srivastava 27


Vector in Java
• It is recommended to use the Vector class in
the thread-safe implementation only
• If we don't need to use the thread-safe
implementation, we should use the ArrayList
• ArrayList will perform better in such case
• The Iterators returned by the Vector class are
fail-fast
• In case of concurrent modification, it fails and
throws following exception:
ConcurrentModificationException
Prepared By: Neeraj Kumar Srivastava 28
Vector in Java
• It is similar to the ArrayList, but with two
differences-
– Vector is synchronized
– Contains many legacy methods that are not the part
of a collections framework
• Syntax:
public class Vector<E>
extends Object<E>
implements List<E>, Cloneable, Serializable

Prepared By: Neeraj Kumar Srivastava 29


Vector Constructors in Java
S.No. Constructor Description
1 vector() It constructs an empty vector with the
default size as 10.

2 vector(int It constructs an empty vector with the


initialCapacity) specified initial capacity and with its
capacity increment equal to zero.
3 vector(int initialCapacity, It constructs an empty vector with the
int capacityIncrement) specified initial capacity and capacity
increment.
4 Vector( Collection<? It constructs a vector that contains the
extends E> c) elements of a collection c.

Prepared By: Neeraj Kumar Srivastava 30


Vector in Java
import java.util.*;
public class VectorExample
{
public static void main(String args[])
{
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
System.out.println("Elements are: "+vec);
}
}

Output:
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Prepared By: Neeraj Kumar Srivastava 31
String in Java
• Generally, String is a sequence of characters,
but in Java, string is an object
• Represents a sequence of characters values
• java.lang.String class is used to create a string
object
• An array of characters works same as Java
string
Example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch); //is same as:
String s="javatpoint";
Prepared By: Neeraj Kumar Srivastava 32
String in Java
• Java String class provides a lot of methods to
perform operations on string such as:
– compare()
– concat()
– equals()
– split()
– length()
– replace()
– compareTo()
– intern(),
– substring() etc.

Prepared By: Neeraj Kumar Srivastava 33


String in Java
• There are two ways to create String object:
1. By string literal
2. By new keyword

Prepared By: Neeraj Kumar Srivastava 34


Using String Literal
• Java String literal is created by using double
quotes
• Example:
– String s=“BCA 4th Semester";
Note:
– Each time we create a string literal, the JVM checks
the "string constant pool" first. If the string already
exists in the pool, a reference to the pooled instance
is returned. If the string doesn't exist in the pool, a
new string instance is created and placed in the
pool.
Prepared By: Neeraj Kumar Srivastava 35
Using String Literal

Example:

String s1= “Welcome”;


String s2= “Welcome”;

Prepared By: Neeraj Kumar Srivastava 36


Using new Keyword
• String s=new String("Welcome");

Note:
– In such case, JVM will create a new string object in
normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant
pool
• The variable s will refer to the object in a
heap (non-pool)

Prepared By: Neeraj Kumar Srivastava 37


Using new Keyword
public class StringExample
{
public static void main(String args[])
{
String s1="java"; //creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
//converting char array to string
String s2=new String(ch);
//creating java string by new keyword
String s3=new String("example");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Output: java
strings
example
Prepared By: Neeraj Kumar Srivastava 38
Immutable String in Java
• In java, string objects are immutable. Immutable simply means
unmodifiable or unchangeable
• Once string object is created its data or state can't be changed
instead a new string object is created

class TestImmutableString
{
public static void main(String args[])
{
String s="Sachin";
s.concat(" Tendulkar");
System.out.println(s);
}
}

Output: Sachin
Prepared By: Neeraj Kumar Srivastava 39
Immutable String in Java

Prepared By: Neeraj Kumar Srivastava 40


Immutable String in Java
• In the above figure, two objects are created but reference variable s still
refers to "Sachin" not to "Sachin Tendulkar”
• Instead, if we explicitly assign it to the reference variable, it will refer to
"Sachin Tendulkar" object
For example:
class Testimmutablestring
{
public static void main(String args[])
{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}

Output: Sachin Tendulkar


(In such case, s points to the "Sachin Tendulkar". Please notice that still
sachin object is not modified)
Prepared By: Neeraj Kumar Srivastava 41
Immutable String in Java
• Why string objects are immutable in java?
– Because java uses the concept of string literal
– Suppose there are 5 reference variables,all referes to one object
"sachin".
– If one reference variable changes the value of the object, it will be
affected to all the reference variables.
– That is why, string objects are immutable in java

Prepared By: Neeraj Kumar Srivastava 42


Character Extraction
charAt (): Retrieves a single character from string
ch = “abc”.charAt(1);
getChar(): Retrieves multiple characters from string
getChars(int sourceStart, int sourceEnd, char target [], int targetStart)
– sourceStart- the beginning of the substring
– sourceEnd- one past the end of the desired substring
– target – destination array of characters
– targetStart – index at which the substring will be
copied.

Prepared By: Neeraj Kumar Srivastava 43


Character Extraction
Example:
String s = “abcdefghijklmnop”;
int start =10, end = 14;
char st [] = new char [end-start];
s.getChars (start, end, st, 0);
System.out.println(st);

Output: klmn
Prepared By: Neeraj Kumar Srivastava 44
String Comparison
• equals()
– boolean equals(String str)
– str is the String object being compared with the
invoking String object
– Case sensitive comparison
• equalsIgnoreCase()
– boolean equalsIgnoreCase(String str)
– str is the String object being compared with the
invoking String object
– Not case sensitive

Prepared By: Neeraj Kumar Srivastava 45


String Comparison
Example:
String s1 = “Hello”;
String s2 = “HELLO”;

System.out.println ( s1 + “ equals” +s2 + s1.equals(s2));


System.out.println ( s1 + “ equals “ +s2 +s1.equalsIgnoreCase(s2));

Output:
Hello equals HELLO false
Hello equals HELLO true

Prepared By: Neeraj Kumar Srivastava 46


String Comparison
• StartsWith () and endsWith ():
– “Football”. endsWith ( “ball”); //true
– “Football”. startsWith (“wood”); //false
• regionMatches():
Boolean regionMatches ( int startIndex, String str2, int str2Index, int numchars)

– compare a specifice region inside a string with another specific


region in another string
– startIndex- specifies the beginning index of the invoking object
– str2Index- specifies the beginning index of the object str2
– numchars – specifies the number of characters to be compared

Prepared By: Neeraj Kumar Srivastava 47


String Comparison
• compareTo():
– int compareTo (String str)
– less than 0:
• if invoking string is less than str
– greater than 0:
• if invoking string is greater than str
– 0:
• if equal
– case sensitive

Prepared By: Neeraj Kumar Srivastava 48


String Comparison
• equals () method compares the characters within a
String object
• == operator compares two object references to see
whether they refer to the same object

Example:

String s1 = “hello”;
String s2 = new String(s1);
System.out.println(s1 + “ equals “+s2 + s1.equals(s2));
System.out.println(s1 + “ equals “+s2 + (s1==s2));

Output:
hello equals hello true
hello equals hello false
Prepared By: Neeraj Kumar Srivastava 49
Searching with String
• indexOf() – searches for the first occurrence of
a character or substring
– indexOf (int ch, int startIndex);

• lastIndexOf() – searches for the last occurrence


of a character or substring
– lastIndexOf (int ch, int startIndex);

Note:
These methods return the index at which
the character or the substring is found or return
-1 on failure.
Prepared By: Neeraj Kumar Srivastava 50
Searching with String
Example:
String s = “ This is a Java Program”;
s.indexOf( ‘J’); ---10
s.indexOf( “Program”); ---15
s.indexOf( ‘a’, 9); ---11

Prepared By: Neeraj Kumar Srivastava 51


String Modification
• substring():
– String substring( int startIndex);
– String substring( int startIndex, int endIndex);
• concat():
– String concat(String str);
• replace():
– String replace( char original, char replacement);
• trim():
– String trim();
– Example: String s=“ Hello “.trim();
Prepared By: Neeraj Kumar Srivastava 52
Mutable String in Java
• A string that can be modified or changed is
known as mutable string
• To create a mutable string in Java, we can
use following two classes:
– StringBuffer Class
– StringBuilder Class

Prepared By: Neeraj Kumar Srivastava 53


Java StringBuffer Class
• Java StringBuffer class is used to create
mutable
(modifiable) string
• It represents growable and writeable character
sequences
• The StringBuffer class in java is same as String
class except it is mutable i.e. it can be changed
Note:
– Java StringBuffer class is thread-safe i.e. multiple
threads cannot access it simultaneously
– So it is safe and will result in an order

Prepared By: Neeraj Kumar Srivastava 54


Java StringBuffer Class
• Constructors:
1. StringBuffer ()
– Reserves space for 16 characters
2. StringBuffer ( int size)
– Reserves space for given size
3. StringBuffer (String str)
– String argument is used to set the initial
content and also reserves space 16 more
characters

Prepared By: Neeraj Kumar Srivastava 55


Java StringBuffer Class
• Methods:
length () and capacity():
– StringBuffer st = new StringBuffer (“Hello”);
– System.out.println(“length:” +st.length());
//length: 5
– System.out.println(“capacity:” +st.capacity());
//capacity: 21
charAt () and setCharAt():
– char charAt( int position);
– void setCharAt( int postion, char ch);
getChars():
– void getChars( int sourceStart, int sourceEnd, char
target [], int targetStart)
Prepared By: Neeraj Kumar Srivastava 56
Java StringBuffer Class
• Methods:
insert():
– It is an overloaded functions.
– It calls String.valueOf() to obtain the string
representation of the value it is called with.
– StringBuffer insert( int index, String str);
reverse ():
– StringBuffer reverse();
Example:
StringBuffer st = new StringBuffer(“ I Java!”);
System.out.println(st.insert(2, “like ”)); //I like Java!
System.out.println(st.reverse()); //!avaJ ekil I

Prepared By: Neeraj Kumar Srivastava 57


Java StringBuffer Class
• Methods
delete() and deleteCharAt()
– StringBuffer delete( int startIndex, int endIndex);
– StringBuffer deleteCharAt( int pos);
replace ()
– StringBuffer replace(int startIndex, int endIndex,
String str);
Example:
StringBuffer st = new StringBuffer(“This is a test.”);
System.out.println(st.replace(5,7, “was”); //This wasa
test
System.out.println(st.delete(4, 8)); //This a test
System.out.println(st.deleteCharAt(0)); // his a test
Prepared By: Neeraj Kumar Srivastava 58
Java StringBuffer Class
• Methods:
append ():
– It is an overloaded functions.
– It calls String.valueOf() to obtain the string
representation of the value it is called with.
– StringBuffer append(String str);
Example:
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb); //prints Hello Java
Prepared By: Neeraj Kumar Srivastava 59
Java StringBuilder Class
• Java StringBuilder class is used to create
mutable (modifiable) string
• The Java StringBuilder class is same as
StringBuffer class except that it is non-
synchronized
• It is available since JDK 1.5

Prepared By: Neeraj Kumar Srivastava 60


Java StringBuilder Class
• StringBuilder append() method:
– The StringBuilder append() method concatenates
the given argument with this string

Example:
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb); //prints Hello Java

Prepared By: Neeraj Kumar Srivastava 61


Java StringBuilder Class
• StringBuilder insert() method
– The StringBuilder insert() method inserts the given
string with this string at the given position.

Example:
StringBuilder sb=new StringBuilder("Hello ");
sb.insert(1,"Java"); //now original string is changed
System.out.println(sb); //prints HJavaello

Prepared By: Neeraj Kumar Srivastava 62


StringBuffer vs String

Prepared By: Neeraj Kumar Srivastava 63


Java Interface
• A blueprint of a class
• Contains static, constants and abstract
methods
• The interface in Java is a mechanism to
achieve abstraction
• There can be only abstract methods in the
Java interface (no method body)
• It is used to achieve multiple inheritance in
Java
Prepared By: Neeraj Kumar Srivastava 64
Java Interface
• Java Interface also represents the IS-A
relationship
• It cannot be instantiated just like the
abstract class
• Since Java 8, we can have default and static
methods in an interface
• Since Java 9, we can have private methods in
an interface

Prepared By: Neeraj Kumar Srivastava 65


Java Interface

Prepared By: Neeraj Kumar Srivastava 66


Java Interface
• It provides total abstraction means that-
– all the methods in an interface are declared with the empty
body
– all the fields are public, static and final by default
• An interface is declared by using the interface keyword
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}

Prepared By: Neeraj Kumar Srivastava 67


Java Interface
• Note:
– A class that implements an interface must
implement all the methods declared in the
interface
– The Java compiler adds public and abstract
keywords before the interface method
– Moreover, it adds public, static and final
keywords before data members

Prepared By: Neeraj Kumar Srivastava 68


Java Interface

Prepared By: Neeraj Kumar Srivastava 69


Java Interface

Prepared By: Neeraj Kumar Srivastava 70


Java Interface
Example:
interface printable
{
void print();
}
class Test implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
Test obj = new Test();
obj.print();
}
}
Prepared By: Neeraj Kumar Srivastava 71
Java Interface
Bank Example:
interface Bank return 9.7f;
{ }
float rateOfInterest(); }
}
class SBI implements Bank class TestInterface
{ {
public float rateOfInterest() public static void main(String[] args)
{ {
return 9.15f; Bank b=new SBI();
} System.out.println("ROI: +b.rateOfInterest());
} }
class PNB implements Bank }
{
public float rateOfInterest()
{
Prepared By: Neeraj Kumar Srivastava 72
Multiple Inheritance through Interface

Prepared By: Neeraj Kumar Srivastava 73


Multiple Inheritance through Interface
interface Printable class Test implements Printable,Showable
{ {
void print(); public void print()
} {
System.out.println("Hello");
}
interface Showable public void show()
{ {
void show(); System.out.println("Welcome");
}
}
public static void main(String args[])
{
Test obj = new Test();
obj.print();
obj.show();
}
}
Prepared By: Neeraj Kumar Srivastava 74
Interface Inheritance
interface Printable class TestInterface implements Showable
{ {
void print(); public void print()
} {
System.out.println("Hello");
}
interface Showable extends Printable public void show()
{ {
void show(); System.out.println("Welcome");
} }
public static void main(String args[])
{
TestInterface4 obj = new
TestInterface4();
obj.print();
obj.show();
}
}

Prepared By: Neeraj Kumar Srivastava 75


Default Method in Interface
• Since Java 8, we can have method body in interface, But we need to
make it default method

interface Drawable
{
void draw();
default void msg()
{
System.out.println("default method");
}
}
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}

Prepared By: Neeraj Kumar Srivastava 76


Nested Interface in Java
• An interface can have another interface, which
is known as a nested interface
For example:
interface printable
{
void print();
interface MessagePrintable
{
void msg();
}
}

Prepared By: Neeraj Kumar Srivastava 77


Nested Interface in Java
import java.util.*; class A
interface Test {
{ public static void main(String[] args)
interface Yes {
Test.Yes obj;
{
Testing t = new Testing();
void show();
obj = t; obj.show();
} }
} }
class Testing implements Test.Yes
{ In this example, access specifier is
public void show() public even if we have not written
{ public. If we try to change access
System.out.println("show method of specifier of interface to anything
interface"); other than public, we get compiler
} error.
}

Prepared By: Neeraj Kumar Srivastava 78


Interface within a Class
import java.util.*; class A
class Test {
{ public static void main(String[] args)
interface Yes {
{ Test.Yes obj;
void show(); Testing t = new Testing();
} obj=t;
}
obj.show();
class Testing implements Test.Yes
}
{
}
public void show()
{
System.out.println("show method of interface");
}
}

Prepared By: Neeraj Kumar Srivastava 79


Abstract Class Vs Interface

Prepared By: Neeraj Kumar Srivastava 80


Exception Handling in Java
• Exception Handling is a mechanism to handle
runtime errors such as-
– ClassNotFoundException
– IOException
– SQLException
– RemoteException, etc.
• The core advantage of exception handling is to
maintain the normal flow of the application
• An exception normally disrupts the normal
flow of the application that is why we use
exception handling
Prepared By: Neeraj Kumar Srivastava 81
Types of Exception in Java

Prepared By: Neeraj Kumar Srivastava 82


Types of Exception in Java
• Checked Exception:
– The classes which directly inherit Throwable class except
RuntimeException and Error are known as checked exceptions
– e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time
• Unchecked Exception:
– The classes which inherit RuntimeException are known as
unchecked exceptions e.g. ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
– Unchecked exceptions are not checked at compile-time, but they
are checked at runtime
• Error:
– Error is irrecoverable e.g. OutOfMemoryError,
VirtualMachineError, AssertionError etc.

Prepared By: Neeraj Kumar Srivastava 83


Common Scenarios of Exception in Java
• ArithmeticException:
– If we divide any number by zero, there occurs an
ArithmeticException.
• NullPointerException:
– If we have a null value in any variable, performing any
operation on the variable throws a
NullPointerException
• NumberFormatException:
– The wrong formatting of any value may occur
NumberFormatException. Suppose I have
– a string variable that has characters, converting this
variable into digit will occur NumberFormatException.
Prepared By: Neeraj Kumar Srivastava 84
Common Scenarios of Exception in Java
• ArrayIndexOutOfBoundsException:
– If we try to move at wrong index, it would result
in ArrayIndexOutOfBoundsException

Prepared By: Neeraj Kumar Srivastava 85


Exception Keywords

Prepared By: Neeraj Kumar Srivastava 86


Exception Keywords

Prepared By: Neeraj Kumar Srivastava 87


Exception Keywords
• Java try block must be followed by either
catch or finally block:
Syntax of try-catch block Syntax of try-finally block
try try
{ {
//code that may throw an exception //code that may throw an exception
} }
catch(Exception_class_Name ref) finally
{ {

} }

Prepared By: Neeraj Kumar Srivastava 88


Exception Keywords

Prepared By: Neeraj Kumar Srivastava 89


Exception Example
public class JavaExceptionExample
{
public static void main(String args[])
{
try
{
//code that may raise exception
int data=100/0; //will raise an arithmetic exception
}
catch(ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program
}
}

Prepared By: Neeraj Kumar Srivastava 90


Exception Keywords
• try Block
– Used to enclose the code that might throw an
exception
– It must be used within the method
– If an exception occurs at the particular statement
of try block, the rest of the block code will not
execute
– Hence, it is recommended not to keep the code in
try block that will not throw an exception

Prepared By: Neeraj Kumar Srivastava 91


Exception Keywords
• catch Block
– Used to handle the Exception by declaring the type
of exception within the parameter
– The declared exception must be the parent class
exception ( i.e., Exception) or the generated
exception type
– However, the good approach is to declare the
generated type of exception
– The catch block must be used after the try block
only
– We can use multiple catch blocks with a single try
block

Prepared By: Neeraj Kumar Srivastava 92


Exception Keywords
• catch Block
– Prior to Java 7, we had to catch only one
exception type in each catch block
– So whenever we needed to handle more than one
specific exception, but take same/different actions
for all exceptions
– Hence, we had to have more than one catch block
containing the same code

Prepared By: Neeraj Kumar Srivastava 93


Exception Handling
import java.util.Scanner;
public class Test
{
public static void main(String args[])
{
Scanner scn = new Scanner(System.in);
try
{
int n = Integer.parseInt(scn.nextLine());
if (99%n == 0)
System.out.println(n + " is a factor of 99");
}
Prepared By: Neeraj Kumar Srivastava 94
Exception Handling
catch (ArithmeticException ex)
{
System.out.println("Arithm etic " + ex);
}
catch (NumberFormatException ex)
{
System.out.println("Numbe r Format Exception " + ex);
}
} //main ends
} //class ends

Prepared By: Neeraj Kumar Srivastava 95


Exception Handling
• Possible output cases:
– First Input case: 0
• Output: Exception encountered
java.lang.ArithmeticException: Divide by zero
– Second Input case: javaprogramming
• Output: Exception encountered
java.lang.NumberFormatException: For input string:
“javaprogramming”
– Third Input case: 9
• Output: 9 is a factor of 99

Prepared By: Neeraj Kumar Srivastava 96


Exception Handling
• Malticatch
– Starting from Java 7.0, it is possible for a single catch
block to catch multiple exceptions by separating each
with | (pipe symbol) in catch block.
• Example
catch (NumberFormatException | ArithmeticException ex)
{
System.out.println("Exception encountered " + ex);
}

Prepared By: Neeraj Kumar Srivastava 97


Exception Handling
• Possible output cases:
– First Input case: 0
• Output: Exception encountered
java.lang.ArithmeticException: Divide by zero
– Second Input case: javaprogramming
• Output: Exception encountered
java.lang.NumberFormatException: For input string:
“javaprogramming”
– Third Input case: 9
• Output: 9 is a factor of 99

Prepared By: Neeraj Kumar Srivastava 98


Nested try Block in Java
• The try block within a try block is known as
nested try block in java
• Sometimes a situation may arise where a part
of a block may cause one error and the entire
block itself may cause another error
• In such cases, exception handlers have to be
nested

Prepared By: Neeraj Kumar Srivastava 99


Nested try Block in Java
Syntax:
....
try
{
//statement
try
{
//statement;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Prepared By: Neeraj Kumar Srivastava 100
Nested try Block in Java
class TestExcep
{
public static void main(String args[])
{
try{
try{
System.out.println("going to divide");
int b =39/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
Prepared By: Neeraj Kumar Srivastava 101
Nested try Block in Java
try{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement);
}
catch(Exception e)
{
System.out.println("handeled");
}
System.out.println("normal flow..");
}
Prepared By: Neeraj Kumar Srivastava 102
finally Block in Java
• Java finally block is a block that is used to
execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether
exception is handled or not
• Java finally block follows try or catch block
• Finally block in java can be used to put
"cleanup" code such as closing a file, closing
connection etc.

Prepared By: Neeraj Kumar Srivastava 103


finally Block in Java
class TestFinallyBlock
{ Output:
public static void main(String args[])
{ No exception
try{
int data=25/5;
System.out.println(data); 5
} finally block always executed
rest of the code
catch(NullPointerException e)
{
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
} Prepared By: Neeraj Kumar Srivastava 104
finally Block in Java
class TestFinallyBlock
Output:
{
public static void main(String args[]) Exception Occurred and
handled
{
try{
Exception in thread main
int data=25/0;
java.lang.ArithmeticException: / by zero
System.out.println(data);
finally block always executed
}
rest of the code
catch(ArithmeticException e)
{
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
} Prepared By: Neeraj Kumar Srivastava 105
finally Block in Java
class TestFinallyBlock Output:
{ Exception Occurred but Not
public static void main(String args[]) Handled
{
try{
int data=25/0; finally block always executed
System.out.println(data); Exception in thread main
} java.lang.ArithmeticException: / by zero
catch(NullPointerException e)
{
System.out.println(e);
}
finally{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
} Prepared By: Neeraj Kumar Srivastava 106
finally Block in Java
• Rule:
– For each try block there can be zero or more
catch blocks, but only one finally block
• Note:
– The finally block will not be executed if program
exits(either by calling System.exit() or by causing
a fatal error that causes the process to abort).

Prepared By: Neeraj Kumar Srivastava 107


End of Unit III

Thank You

Prepared By: Neeraj Kumar Srivastava 108


Java Programming

Unit IV
Thread Concepts, Package and Applets

Mr. Neeraj Kumar Srivastava


Assistant Professor
Department of Computer Applications
Thread Concepts

Prepared By: Neeraj Kumar Srivastava 2


Multitasking
• The ability of a system to perform multiple
tasks simultaneously
• Helps to optimize CPU utilization by executing
more than one task at a time
• Types:
– Process-based
– Thread-based multitasking
• Thread-based multitasking allows multiple
threads to run concurrently
• Improves performance and responsiveness,
especially in real-time applications
Prepared By: Neeraj Kumar Srivastava 3
Multitasking

Prepared By: Neeraj Kumar Srivastava 4


Multithreading
• A programming technique, where multiple
threads run concurrently within a single
process
• Each thread is a lightweight, independent path
of execution
• Allows simultaneous execution of two or more
parts of a program for maximum efficiency
• Enhances performance in CPU-intensive and
real-time applications
• Threads share the same memory space, which
makes communication between them faster.
Prepared By: Neeraj Kumar Srivastava 5
Multithreading
• Helps in building responsive applications,
like smooth-running GUIs
• Java provides synchronization mechanisms
to handle thread safety and avoid conflicts
• Thread management can be done using
thread pools for better resource utilization
• Multithreading is widely used in-
– Servers
– Games
– Real-time systems

Prepared By: Neeraj Kumar Srivastava 6


Process and Threads

Prepared By: Neeraj Kumar Srivastava 7


Process and Threads

Prepared By: Neeraj Kumar Srivastava 8


Advantages of Multithreading
• Improved Performance:
– Multiple threads can execute tasks simultaneously,
making better use of CPU resources and reducing
execution time
• Responsiveness:
– Applications (especially GUI-based) remain
responsive, as background tasks can run without
freezing the user interface
• Resource Sharing:
– Threads within the same process share memory and
resources, which allows efficient communication and
data exchange between them
Prepared By: Neeraj Kumar Srivastava 9
Threads in Java
• A lightweight sub-process, the smallest unit of
execution in Java
• Java supports multithreading by allowing
multiple threads to run concurrently
• Each thread has its own execution path but
shares the same memory space with other
threads
• Threads can run in parallel on multi-core
processors, boosting performance
• Java allows thread priorities to control the
order of thread execution
Prepared By: Neeraj Kumar Srivastava 10
Creating Threads in Java
• There are two ways to create our own
Thread object
– Using Thread Class (Create a subclass of the
Thread class and instantiate a new object of that
class)
– Implementing the Runnable interface
• In both cases the run() method should be
implemented

Prepared By: Neeraj Kumar Srivastava 11


Thread Methods
• void start()
– Creates a new thread and makes it runnable
– This method can be called only once
– The thread moves from New state to the
Runnable state
– When the thread gets a chance to execute, its
target run() method will run
• void run()
– The new thread begins its life inside this
method
Prepared By: Neeraj Kumar Srivastava 12
Thread Methods
• yield()
– Causes the currently executing thread object to
temporarily pause and allow other threads to
execute
– Allow only threads of the same priority to run
• sleep(int m)/sleep(int m,int n)
– The thread sleeps for m milliseconds, plus n
nanoseconds

Prepared By: Neeraj Kumar Srivastava 13


Thread Methods
• void stop()
– Terminates the thread execution
– Once a thread is stopped, it cannot be
restarted by start() method
Syntax
public final void stop()
public final void stop(Throwable obj)
Parameter
obj : The Throwable object to be thrown
Return
This method does not return any value

Prepared By: Neeraj Kumar Srivastava 14


Java Threads Example
• Using Thread Class:
public class MyThread extends Thread
{
public void run ()
{
System.out.println(“Thread is running…..”);
}
public static void main(String args[])
{
MyThread th=new MyThread();
th.start();
}
}

Output: Thread is running...


Prepared By: Neeraj Kumar Srivastava 15
Runnable Interface
• The Runnable interface should be implemented by
any class whose instances are intended to be
executed by a thread
• Runnable interface have only one method named
run().
– public void run()
– Used to perform action for a thread

Prepared By: Neeraj Kumar Srivastava 16


Java Threads Example
• Implementing Runnable Interface
public class MyThread implements Runnable
{
public void run ()
{
System.out.println(“Thread is running…..”);
}
public static void main(String args[])
{
MyThread th=new MyThread();
Thread t = new Thread(th);
t.start();
}
}

Output: Thread is running...

Prepared By: Neeraj Kumar Srivastava 17


Thread Life Cycle
• A thread can be in one of the five states during its
lifetime
• According to SUN Java, there are only 4 states in
thread life cycle in java (i.e.: new, runnable, non-
runnable and terminated)
• But for better understanding the threads, we
consider following 5 states:
– New
– Runnable
– Running
– Non-Runnable (Blocked)
– Terminated
• The life cycle of the thread in java is controlled by
JVM
Prepared By: Neeraj Kumar Srivastava 18
Thread Life Cycle

Prepared By: Neeraj Kumar Srivastava 19


Thread Life Cycle
• New:
– The thread is in new state if you create an instance of Thread
class but before the invocation of start() method
• Runnable:
– The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be the
running thread
• Running:
– The thread is in running state if the thread scheduler has
selected it
• Non-Runnable (Blocked):
– This is the state when the thread is still alive, but is currently
not eligible to run
• Terminated:
– A thread is in terminated or dead state when its run() method
exits
Prepared By: Neeraj Kumar Srivastava 20
Thread Priority
• Each thread has a priority between 1 and 10
– Thread.MIN_PRIORITY = 1
– Thread.NORM_PRIORITY = 5 (default priority)
– Thread.MAX_PRIORITY = 10
• Higher priority threads may get CPU
preference
• Priority is inherited from the parent thread
• JVM does not guarantee priority-based
scheduling
Prepared By: Neeraj Kumar Srivastava 21
Thread Priority
• Priorities help in suggesting thread
importance
• Priority affects thread scheduling, not
execution order
• Threads with same priority follow round-
robin execution
• Priority can be changed anytime before
start
• Real-time OS may respect priorities more
strictly
Prepared By: Neeraj Kumar Srivastava 22
Thread Priority
class MyThread extends Thread {
public void run() {
System.out.println(getName() + " is running with priority " + getPriority());
}
}
class ThreadPriorityDemo {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.setPriority(Thread.MIN_PRIORITY); // 1
t2.setPriority(Thread.NORM_PRIORITY); // 5
t3.setPriority(Thread.MAX_PRIORITY); // 10
t1.start();
t2.start();
Output (Sample):
t3.start();
Thread-0 is running with priority 1
}
Thread-1 is running with priority 5
}
Thread-2 is running with priority 10
Prepared By: Neeraj Kumar Srivastava 23
Thread Exception
class MyThread extends Thread {
public void run() {
try {
System.out.println("Thread running: " + getName());
int result = 10 / 0; // This will cause ArithmeticException
} catch (Exception e) {
System.out.println("Exception caught in thread: " + e);
}
}
}
public class ThreadExceptionDemo {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
} Output:
} Thread running: Thread-0
Exception caught in thread: java.lang.ArithmeticException: / by zero
Prepared By: Neeraj Kumar Srivastava 24
Synchronization
• Synchronization in java is the capability to control
the access of multiple threads to any shared
resource
• Java Synchronization is better option where we
want to allow only one thread to access the shared
resource
• The synchronization is mainly used:
– To prevent thread interference
– To prevent consistency problem
• There are two types of synchronization:
– Process Synchronization
– Thread Synchronization
Prepared By: Neeraj Kumar Srivastava 25
Thread Synchronization in Java
• There are two types of thread synchronization:

– Mutual Exclusive
• Synchronized method
• Synchronized block
• static synchronization

– Cooperation
• Inter-Thread Communication

Prepared By: Neeraj Kumar Srivastava 26


Thread Synchronization in Java
class Counter { public class SyncDemo {
int count = 0; public static void main(String[]
synchronized void increment() { args) throws
count++; InterruptedException {
} Counter counter = new
Counter();
} MyThread t1 = new
class MyThread extends Thread { MyThread(counter);
Counter c; MyThread t2 = new
MyThread(Counter c) { MyThread(counter);
this.c = c; t1.start();
} t2.start();
public void run() { t1.join();
for (int i = 0; i < 1000; i++) { t2.join();
c.increment(); System.out.println("Final
} Count: " + counter.count);
} }
} }
Prepared By: Neeraj Kumar Srivastava 27
Java Packages

Prepared By: Neeraj Kumar Srivastava 28


Package: Putting Classes Together
• A Java package is a collection of related
classes and interfaces
• It acts as a namespace to avoid class name
conflicts
• Packages help in organizing code logically
and cleanly.
• They support modularity and reusability in
Java applications
• Packages can be built-in (like java.util,
java.io) or user-defined
Prepared By: Neeraj Kumar Srivastava 29
Package: Putting Classes Together
• A class belongs to a package using the
package keyword at the top of the file
• We can import classes from other packages
using the import statement
• Packages provide access control (via public,
protected, default access)
• Sub-packages are separate packages, even if
nested in structure
• The folder structure of our project should
match the package structure
Prepared By: Neeraj Kumar Srivastava 30
Importance of Package
• Prevents name conflicts between classes
• Helps in organizing related classes
• Improves code reusability and maintenance
• Provides access control using modifiers
• Supports modular development in large
projects
• Enhances code readability by grouping
related classes
• Provides a structured namespace, avoiding
clutter in large applications
Prepared By: Neeraj Kumar Srivastava 31
Java Foundation Packages
• java.lang
– Automatically imported in every Java program
– Contains essential classes like String, Math, Integer,
Thread, Object, etc.
• java.util
– Utility classes like collections (ArrayList, HashMap), Date,
Random, etc.
• java.io
– Classes for input and output operations like File,
InputStream, OutputStream, Reader, Writer, etc.
• java.net
– Provides classes for networking (like Socket, URL,
HttpURLConnection)
Prepared By: Neeraj Kumar Srivastava 32
Java Foundation Package
• java.sql
– Supports database operations via JDBC (Connection,
Statement, ResultSet)
• java.text
– Classes for text formatting and parsing (DateFormat,
NumberFormat)
• java.awt
– Abstract Window Toolkit for building graphical user
interfaces (GUIs)
• javax.swing
– Lightweight GUI components built on top of AWT
(JFrame, JButton, etc.)
Prepared By: Neeraj Kumar Srivastava 33
Java System Packages

Prepared By: Neeraj Kumar Srivastava 34


Accessing Classes from Packages
• There are two ways of accessing the classes
stored in packages:
– Using fully qualified class name
• java.lang.Math.sqrt(x);
– Import package and use class name directly
• import java.lang.Math
• Math.sqrt(x);
• Selected or all classes in packages can be
imported:
– import package.class;
– import package.*;
• Implicit in all programs: import java.lang.*;
• Package statement(s) must appear first
Prepared By: Neeraj Kumar Srivastava 35
Creating Package
• package keyword is used to create a new package in
Java
• Should be the first statement of Java source code
followed by one or more classes
• Syntax:
package myPackage;
public class ClassA
{
// class body
}
Note:
class ClassB Package name is “myPackage” and classes are
{ considered as part of this package; The code
// class body is saved in a file called “ClassA.java” and
located in a directory called “myPackage”.
}
Prepared By: Neeraj Kumar Srivastava 36
Creating Package
• Creating your own package involves the
following steps:-
– Declare the package at the begining of a file
– Define the class that is tobe put in the package
and declare it PUBLIC
– Create a subdirectory under the directory where
the main source file are stored
– Store the listing as the classname.java file in the
sub-directory created
– Compile the file and this will create .class file the
directory
Prepared By: Neeraj Kumar Srivastava 37
Creating Sub-Package
• Classes in one ore more source files can be part of
the same package
• As packages in Java are organized hierarchically,
sub- packages can be created as follows:
– package myPackage.Math
– package myPackage.secondPakage.thirdPackage
• Store “thirdPackage” in a subdirectory named
“myPackage\secondPackage”
• Store “secondPackage” and “Math” class in a
subdirectory “myPackage”

Prepared By: Neeraj Kumar Srivastava 38


Using A Package
• Let us store the following code in a file named
“ClassA.java” within subdirectory named “myPackage”
within the current directory (say “abc”)-
package myPackage;
public class ClassA
{
// class body
public void display()
{
System.out.println("Hello, I am ClassA");
}
}
class ClassB
{
// class body
}

Prepared By: Neeraj Kumar Srivastava 39


Using A Package
• Within the current directory (“abc”) store
the following code in a file named
“ClassX.java”-
import myPackage.ClassA;
public class ClassX
{
public static void main(String args[])
{
ClassA objA = new ClassA();
objA.display();
}
}
Prepared By: Neeraj Kumar Srivastava 40
Compile and Run
• When ClassX.java is compiled, the compiler places
.class file in current directly
• If .class file of ClassA in subdirectory “myPackage”
is not found, it compiles ClassA also
– Note: It does not include code of ClassA into
ClassX
• When the program ClassX runs, java loader looks
for ClassA.class file in a package called
“myPackage” and loads it

Prepared By: Neeraj Kumar Srivastava 41


Visibility Revisited
• Public keyword applied to a class, makes it
available/visible everywhere. Applied to a
method or variable, completely visible.
• Private fields or methods for a class only
visible within that class. Private members
are not visible within subclasses, and are
not inherited.
• Protected members of a class are visible
within the class, subclasses and also within
all classes that are in the same package as
that class.
Prepared By: Neeraj Kumar Srivastava 42
Visibility Modifiers

Accessible to: public protected Package private


(default)

Same Class Yes Yes Yes Yes

Class in package Yes Yes Yes No

Subclass in Yes Yes No No


different package

Non-subclass Yes No No No
different package

Prepared By: Neeraj Kumar Srivastava 43


Adding Class to a Package
• Consider an existing package that contains a
class called “Teacher”:
package pack1;
public class Teacher
{
// class body
}
• This class is stored in Teacher.java file within
a directory called pack1
• How do we add a new public class called
“Student” to this package?
Prepared By: Neeraj Kumar Srivastava 44
Handling Naming Clashes
• When packages are developed by different
organizations, it is possible that multiple
packages will have classes with the same
name, leading to name classing-
package package
pack1; pack2;
class Teacher class Student

class Student class Courses

Prepared By: Neeraj Kumar Srivastava 45


Handling Naming Clashes
• In Java, name classing is resolved by
accessing classes with the same name in
multiple packages by their fully qualified
name.
• Example:
import pack1.*;
import pack2.*;
pack1.Student student1;
pack2.Student student2;
Teacher teacher1;
Courses course1;
Prepared By: Neeraj Kumar Srivastava 46
Extending a Class from Package
• A new class called “Professor” can be
created by extending the “Teacher” class
defined the package “pack1” as follows:

import pack1.Teacher;
public class Professor extends Teacher
{
// body of Professor class
// It is able to inherit public and protected members,
// but not private or default members of Teacher class
}

Prepared By: Neeraj Kumar Srivastava 47


Summary
• Packages allow grouping of related classes
into a single unit
• Packages are organized in hierarchical
structure
• Packages handle name classing issues
• Packages can be accessed or inherited
without actual copy of code to each
program

Prepared By: Neeraj Kumar Srivastava 48


Java Applets

Prepared By: Neeraj Kumar Srivastava 49


Introduction
• A small Java program that runs in a web
browser
• Embedded into an HTML page using the
<applet> or <object> tag
• Run on the client side and are executed by the
Java Virtual Machine (JVM) in the browser
• Typically used for interactive features like
animations, games, or dynamic graphics
• Must extend the java.applet.Applet class or
javax.swing.JApplet
Prepared By: Neeraj Kumar Srivastava 50
Introduction
• Do not have a main() method like standalone
Java applications
• They are sandboxed for security, meaning they
have limited access to system resources
• To run an applet, a Java-enabled browser or
applet viewer tool is required (like
appletviewer in JDK)
• Have lifecycle methods: init(), start(), stop(),
and destroy()
• Deprecated now and not supported in most
modern browsers due to security concerns
Prepared By: Neeraj Kumar Srivastava 51
Types of Applets
1. Local Applet:
• Stored on the user’s own computer and not on a web
server. It is loaded into the browser using the file
system path.
Key Points:
– Uses the file:// URL scheme.
– Requires no internet connection.
– Ideal for testing or learning purposes during
development.
– Typically run using tools like appletviewer or by opening
the HTML file in a Java-enabled browser.
Example:
– A developer creates an applet to simulate a calculator
and runs it locally while testing functionality
Prepared By: Neeraj Kumar Srivastava 52
Types of Applets
2. Remote Applet:
• A remote applet resides on a web server and is
accessed through a URL over the internet or
intranet.
Key Points:
– Uses http:// or https:// protocol.
– The HTML page contains a reference to the applet’s .class
or .jar file hosted online.
– Requires a Java-enabled web browser or the Java Plug-in
to run.
– Once widely used in early web-based Java applications for
adding interactivity.
Example:
– A weather forecasting applet embedded in a webpage,
fetching live data and displaying graphics dynamically.
Prepared By: Neeraj Kumar Srivastava 53
Applications Vs Applets

Prepared By: Neeraj Kumar Srivastava 54


Writing Applet
• It includes the following steps:
– Creating a source code
– Compiling the source code
– Designing the web page using HTML tag
– Adding APPLET tag in HTML coding
– Running the applet by using appletviewer

Prepared By: Neeraj Kumar Srivastava 55


Applet Example
import java.applet.*;
import java.awt,*;
public class MyApplet extends Applet
{
String name;
public void init()
{
name=“Neeraj Kumar Srivastava";
}
pubic void paint(Graphics g)
{
g.drawString(name,100,100);
}
}
• Compile the source code by using JAVAC compiler

Prepared By: Neeraj Kumar Srivastava 56


Applet Example
• Now, we will write the following HTML code to run the applet:
<html>
<body>
<applet code=“MyApplet.class" height="500" width="500">
</applet>
</body>
</html>

• Save this code with extension MyApplet.html


• Now run this html file by using following command-
APPLETVIEWER MyApplet.html
Output:
Neeraj Kumar Srivastava

Prepared By: Neeraj Kumar Srivastava 57


Life Cycle of an Applet

Prepared By: Neeraj Kumar Srivastava 58


Life Cycle of an Applet
• Key Transitions in the Diagram:
– init() → Born
– start() → Running (from Born or Idle)
– paint() → Called repeatedly while in Running
state (for drawing)
– stop() → Moves to Idle
– start() (again) → Resumes to Running from Idle
– destroy() → Final transition to Dead

Prepared By: Neeraj Kumar Srivastava 59


Life Cycle of an Applet
1. Born (Initialization State)
– Method: init()
– The applet enters this state when it is first loaded by the
browser or applet viewer.
– Resources are initialized here (UI components, variables,
etc.).
2. Running State
– Method: start()
– After initialization, the applet moves into the running
state.
– In this state, the applet is active and can perform tasks
like animations or calculations.
– The paint() method is also called during this state to
render visuals.
Prepared By: Neeraj Kumar Srivastava 60
Life Cycle of an Applet
3. Idle State (Stopped)
– Method: stop()
– The applet moves to this state when the user
navigates away from the page or minimizes the
window.
– It pauses activities such as animations, threads,
or network connections.
– The applet can return to the Running state
through the start() method again.

Prepared By: Neeraj Kumar Srivastava 61


Life Cycle of an Applet
4. Dead State (Destroyed)
– Method: destroy()
– The applet transitions to this final state when it is
unloaded from memory (e.g., browser closed).
– This is where the applet performs clean-up
activities like releasing resources or closing files.

Prepared By: Neeraj Kumar Srivastava 62


Structure of an Applet Program
public class MyApplet extends Applet
{
public void init()
{}
public void start()
{}
public void paint(Graphics g)
{}
}

Prepared By: Neeraj Kumar Srivastava 63


Working with Parameters in Applet
• Parameters are passed to applets in NAME
and VALUE pairs in <PARAM> tags between
the opening and closing APPLET tags
• Inside the applet, we read the values passed
through the PARAM tags with the
getParameter() method of the
java.applet.Applet class
• getParameter() method takes one string
argument that represents the name

Prepared By: Neeraj Kumar Srivastava 64


Working with Parameters in Applet
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet {
String str;
public void init(){
str=getParameter("NAME");
if(str==null)
str="HELLO";
else
str="HELLO" + str;
}
public void paint(Graphics g){
g.drawString(str,50,50);
}
}
Prepared By: Neeraj Kumar Srivastava 65
Working with Parameters in Applet
HTML CODE:

<HTML>
<BODY>
<APPLET CODE=“MyApplet.class”height=100 width= 100>
<PARAM NAME="NAME" VALUE="JAVA">
</APPLET>
</BODY>
</HTML>

Note:
In this code if the param tag with NAME is found it will display
the value on the Applet window. If there is even a single mistake
is done in typing the parameter name, it will only display HELLO.

Prepared By: Neeraj Kumar Srivastava 66


Working with numbers in Applets
import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet {
int x, y, sum;
public void init(){
x=10;
y=20;
sum = x+y;
}
public void paint(Graphics g){
g.drawString(String.valueOf(sum),150,150);
}
}

Prepared By: Neeraj Kumar Srivastava 67


Getting User Input in Applet
import java.awt.*; public boolean action(Event e, Object o)
import java.applet.*; {
repaint();
public class UserInput extends Applet return true;
{ }
TextField t1,t2;
public void init() } //class ends
{
t1=new TextField(10);
t2=new TextField(10);
add(t1);
add(t2);
}
public void paint(Graphics g)
{
t1.setLocation(120,70);
t2.setLocation(120,100);
s=Integer.parseInt(t1.getText());
s1=Integer.parseInt(t2.getText());
s2=s+s1;
g.drawString(String.valueOf(s2),80,150);
} Prepared By: Neeraj Kumar Srivastava 68
Largest of Three Numbers program
using Applet
import java.awt.*; c=Integer.parseInt(t2.getText());
import java.applet.*; large = Math.max(b, c);
large= Math.max(a, large);
public class LargestNumber extends Applet
{ res = "The largest number is: " +large;
TextField t1,t2, t3; g.drawString(String.valueOf(res),80,150);
}
String res;
public void init() public boolean action(Event e, Object o)
{ {
t1=new TextField(10); repaint();
t2=new TextField(10); return true;
t3=new TextField(10); }
add(t1);
add(t2); } //class ends
add(t3);
}
public void paint(Graphics g)
{
int a,b,c;
a=Integer.parseInt(t1.getText());
b=Integer.parseInt(t2.getText());
Prepared By: Neeraj Kumar Srivastava 69
“Believe you can and you're halfway there”
By: Theodore Roosevelt

End of Unit IV

Thank You
Prepared By: Neeraj Kumar Srivastava 70

You might also like