CSE 208
JAVA PROGRAMMING
[Link]
SAP / ICT / SOC
SASTRA
COURSE OBJECTIVES
LEARNING OUTCOMES
SYLLABUS
REFERENCE BOOKS
PREREQUISITE
JAVA BASICS
8/27/2021 4:52:27 PM CSE 208 – Java Programming 2
To help the learners to
Develop Java console applications using packages,
interfaces, classes, exception handling mechanism,
and Collections framework.
Develop multi-threaded applications using Java thread
model.
Design GUI using Swing controls and event handling
mechanism.
8/27/2021 4:52:27 PM CSE 208 – Java Programming 3
¥ The learner will be able to
¥ Design Classes to model real world objects using
inheritance
¥ Create Classes using Packages, Interfaces and Exception
Handling
¥ Develop applications using Threads and Files
¥ Create programs for event handling
¥ Design applications using collection framework
¥ Create applications Using Swing
8/27/2021 4:52:27 PM CSE 208 – Java Programming 4
Unit - I
¥ Introduction:
¥ History and Evolution of Java - Overview of Java -
Data types, Variables and Arrays - Operators -
Control Statements - Introducing Classes - A closer
look at Methods and Classes - Inheritance. Packages
and Interfaces - Exception Handling
8/27/2021 4:52:27 PM CSE 208 – Java Programming 5
Unit - II
¥ Multithreaded Programming:
¥ Java Thread Model - The Main Thread - Creating a
Thread - Creating Multiple Threads - Thread
Priorities - Synchronization.
¥ I/O:
¥ I/O Basics - Reading Console Input - Writing Console
Output.
¥ String Handling:
¥ String - String Buffer - String Builder
8/27/2021 4:52:27 PM CSE 208 – Java Programming 6
Unit - III
¥ Collections Framework:
¥ Collection Interfaces - Collection, List, Set, Sorted
Set - Collection Classes - Array List, Hash Set, Tree
Set - Accessing a collection via an Iterator - Working
with Maps - Comparators.
¥ Event Handling:
¥ Introduction - Event Delegation - Model - Event
classes - Sources of Events - Event Listener -
Adapter Classes - Inner Classes in Event Handling
8/27/2021 4:52:27 PM CSE 208 – Java Programming 7
Unit - IV
¥ Introducing GUI Programming with Swing:
¥ Introducing Swing - Exploring Swing - Introducing
Swing Menus
8/27/2021 4:52:27 PM CSE 208 – Java Programming 8
TEXT BOOK
¥ Herbert Schildt
¥ The Complete Reference JAVA,
¥ Tata McGraw Hill,
¥ Eleventh Edition,
¥ 2019.
8/27/2021 4:52:27 PM CSE 208 – Java Programming 9
REFERENCES
¥ Harvey M. Deitel and Paul J. Deitel. JAVA: How to Program,
Prentice Hall, Ninth Edition, 2012.
¥ Kathy Sierra and Bert Bates. Head First Java, OReilly, Second
Edition, 2009.
8/27/2021 4:52:27 PM CSE 208 – Java Programming 10
¥ Tuesday – 5th hour
¥ Wednesday – 8th hour
¥ Friday – 5th & 6th hour
¥ Saturday – 2nd hour
¥ manikandan@[Link]
¥ Whatsapp group
8/27/2021 4:52:27 PM CSE 208 – Java Programming 11
Internal Assessment
Maximum marks - 25.
20 marks for CIA
5 marks for Lab assignments.
For the award of 20 marks
Three CIA tests.
All three tests are compulsory.
Each test duration - 60 minutes
20 marks maximum.
Average of marks scored in the three CIA tests shall
be considered for award of 20 marks.
CIA tests - regular class hours.
8/27/2021 4:52:27 PM CSE 208 – Java Programming 12
End Semester Exam
¥ Problem Based Assessment
¥ 3 hours
¥ 1 scenario Based Question
8/27/2021 4:52:28 PM CSE 208 – Java Programming 13
Giving credit where credit is due
¥ Most of the lecture notes are based on
Materials
¥ Text Book
¥ Tutorials and Presentations
¥ Images from web
¥ I have modified them and added new slides
8/27/2021 4:52:28 PM CSE 208 – Java Programming 14
¥ Programming Fundamentals
¥ C
¥ C++
8/27/2021 4:52:28 PM CSE 208 – Java Programming 15
5
Questions?
8/27/2021 4:52:28 PM CSE 208 – Java Programming16 16
8/27/2021 4:52:28 PM CSE 208 – Java Programming 17
Top Programming Languages 2021
8/27/2021 4:52:28 PM CSE 208 – Java Programming 18
[Link]
8/27/2021 4:52:28 PM CSE 208 – Java Programming 19
Why Do People Use Java?
8/27/2021 4:52:28 PM CSE 208 – Java Programming 20
Why Do People Use Java?
¥ There are many programming languages available today
¥ This is the usual first question of newcomers.
¥ The choice of development tools is sometimes based on unique
constraints or personal preference.
8/27/2021 4:52:28 PM CSE 208 – Java Programming 21
The primary factor cited by java users
¥ Program portability
¥ Support libraries
¥ Component integration
8/27/2021 4:52:28 PM CSE 208 – Java Programming 22
Traditional programs
vs
JAVA programs
8/27/2021 4:52:28 PM CSE 208 – Java Programming 23
Compiled Programs
With Different Operating Systems
Windows
compiler
Executable (Windows)
Mac OS
Computer compiler
program
Executable (Mac)
UNIX
compiler
Executable (UNIX)
A High Level View
Of
Translating/Executing Java Programs
Stage 1: Compilation
[Link] Java compiler [Link]
(javac)
Java program Java bytecode
(generic binary)
8/27/2021 4:52:28 PM CSE 208 – Java Programming 25
A High Level View
Of
Translating/Executing Java Programs (2)
Stage 2: Interpreting and executing the byte code
Machine language
instruction (UNIX)
[Link] Java interpreter Machine language
(java) instruction (Windows)
Java bytecode
(generic binary)
Machine language
instruction (Apple)
8/27/2021 4:52:28 PM CSE 208 – Java Programming 26
Java: Write Once, Run Anywhere
8/27/2021 4:52:28 PM CSE 208 – Java Programming 27
Java: Write Once, Run Anywhere
¥ Consequence of Java’s history: platform-independence
Click on link to Applet
Web page stored
Mac user running Safari on Unix server
Virtual machine translates byte
code to native Mac code and the
Applet is run
Byte code is
downloaded
Windows user running Internet Explorer
Byte code (part of web page)
Java: Write Once, Run Anywhere
¥ Consequence of Java’s history: platform-independent
Web page stored on Unix server
Mac user running Safari
Click on link to Applet
Byte code is downloaded
Windows user running Internet Explorer
Virtual machine translates
byte code to native Windows code
and the Applet is run
Java: Write Once, Run Anywhere (2)
¥ But Java can also create standard (non-web based) programs
Kung Fu Panda 2: THQ
Examples of mobile Java games: [Link]
8/27/2021 4:52:28 PM CSE 208 – Java Programming 30
Java Applications
¥ We can develop two types of Java programs:
¥ Stand-alone applications
¥ Web applications (applets)
8/27/2021 4:52:28 PM CSE 208 – Java Programming 31
Applications v/s Applets
¥ Different ways to run a Java executable are:
¥ Application
¥ A stand-alone program that can be invoked from
command line .
¥ A program that has a “main” method.
¥ Applet
¥ A program embedded in a web page , to be run
when the page is browsed .
¥ A program that contains no “main” method
8/27/2021 4:52:28 PM CSE 208 – Java Programming 32
Applets v/s Applications
¥ Different ways to run a Java executable are
¥ Application:
¥ Executed by the Java interpreter.
¥ Applet
¥ Java enabled web browser.
8/27/2021 4:52:28 PM CSE 208 – Java Programming 33
C++ vs Java
Structure of Java program
Simple Java Program
8/27/2021 4:52:28 PM CSE 208 – Java Programming 34
Structure of Java program
8/27/2021 4:52:28 PM CSE 208 – Java Programming 35
Creating, Compiling and Running
Java Programs
8/27/2021 4:52:29 PM CSE 208 – Java Programming 36
Creating, Compiling And Running Java
Programs
Java program Type it in with the text editor of your choice
[Link]
(Unix file)
Java compiler
javac
Java byte code
[Link]
To compile the program at the (UNIX file)
command line type "javac
[Link]"
Java Interpreter
java
To run the interpreter, at the
8/27/2021 4:52:29 PM commandCSE 208
line – Java
type "javaProgramming 37
filename"
Compiling The Smallest Java Program
[Link]
public class Smallest
Type “javac
{ [Link]”
public static void main (String[] args)
{
}
}
javac
[Link]
(Java byte code)
10000100000001000
00100100000001001
: :
8/27/2021 4:52:29 PM CSE 208 – Java Programming 38
Running The Smallest Java Program
[Link]
(Java byte code)
10000100000001000
00100100000001001
: :
java
Type “java Smallest” (Platform/Operating specific binary
10100111000001000
00100111001111001
: :
8/27/2021 4:52:29 PM CSE 208 – Java Programming 39
A Simple Java Program(1)
public class Hello
{
public static void main(String[] args)
{
[Link]("Hello Java");
}
}
Compile: javac [Link]
Execute : java Hello
8/27/2021 4:52:29 PM CSE 208 – Java Programming 40
A Simple Java Program(2)
class Add
{
public static void main(String args[])
{
int a,b,c;
a=10;b=20;
c=a+b;
[Link](“The Result is”+c);
} Compile: javac [Link]
} Execute : java Add
8/27/2021 4:52:29 PM CSE 208 – Java Programming 41
Some Simple Programs in java
¥ Area of a Square
¥ Simple Interest Calculation
¥ Sum and average of 3 numbers
8/27/2021 4:52:29 PM CSE 208 – Java Programming 42
8/27/2021 4:52:29 PM CSE 208 – Java Programming 43
CSE 208
JAVA PROGRAMMING
[Link]
SAP / ICT / SOC
SASTRA
C++ vs Java
History of Java
Evolution of Java
Interactive Input
8/28/2021 10:56:50 AM CSE 208 – Java Programming 2
C++ vs JAVA
8/28/2021 10:56:51 AM CSE 208 – Java Programming 3
Java better than C++ ?
¥ No Typedefs, Defines, or Preprocessor
¥ No Global Variables
¥ No Goto statements
¥ No Pointers
¥ No Multiple Inheritance
¥ No Operator Overloading
¥ No Destructor
8/28/2021 10:56:51 AM CSE 208 – Java Programming 4
Java better than C++ ?
¥ No Templates
¥ No Scope ResolutionOperator
¥ Single Argument for main()
¥ Strings are objects
¥ One array can be assigned to another
8/28/2021 10:56:51 AM CSE 208 – Java Programming 5
Inventor of the Java programming
language ?
8/28/2021 10:56:51 AM CSE 208 – Java Programming 6
James Gosling
¥ Conceived by James Gosling, Patrik Naughton,
Chris Wrath, Ed Frank and Mike Sheridan
¥ James Gosling is generally credited as the
inventor of the Java programming language
¥ He was the first designer of Java and
implemented its original compiler and virtual
machine
¥ He is also known as the Father of Java
8/28/2021 10:56:51 AM CSE 208 – Java Programming 7
History of Java
8/28/2021 10:56:51 AM CSE 208 – Java Programming 8
History of Java
¥ In the early 1990's, putting
intelligence into home appliances
was thought to be the next "hot"
technology.
¥ Examples of intelligent home
appliances:
¥ Coffee pots and lights that can
be controlled by a computer's
programs.
¥ Televisions that can be
controlled by an interactive
television device's programs.
8/28/2021 10:56:51 AM CSE 208 – Java Programming 9
History of Java
¥ Anticipating a strong market for
such things, Sun Microsystems in
1991 funded a research project
(code named Green) whose goal
was to develop software for
intelligent home appliances.
¥ An intelligent home appliance's
intelligence comes from its
embedded processor chips and
the software that runs on the
processor chips.
8/28/2021 10:56:51 AM CSE 208 – Java Programming 10
History of Java
¥ Appliance processor chips
change often because engineers
continually find ways to make
them smaller, less expensive,
and more powerful.
¥ To handle the frequent turnover
of new chips, appliance software
must be extremely portable.
8/28/2021 10:56:51 AM CSE 208 – Java Programming 11
It was meant to!!
A programming language for appliances!
Must Run on Any Architecture
pretty
Program Java Java portable
in Java Compiler Bytecode
Java Virtual Machine Java Virtual Machine
History of Java
¥ Initial Idea – 1991
¥ 18 months to develop the first working version
¥ Initially named as Oak
¥ Renamed as Java in 1995
8/28/2021 10:56:51 AM CSE 208 – Java Programming 14
Java Editions
¥ J2SE, J2ME, and J2EE
¥ Java Standard Edition (J2SE)
J2SE can be used to develop client-side standalone
applications or applets.
¥ Java Enterprise Edition (J2EE)
J2EE can be used to develop server-side applications such
as Java servlets and Java ServerPages.
¥ Java Micro Edition (J2ME).
J2ME can be used to develop applications for mobile
devices such as cell phones.
8/28/2021 10:56:51 AM CSE 208 – Java Programming 15
JDK Evolution
8/28/2021 10:56:51 AM CSE 208 – Java Programming 16
JDK Evolution
8/28/2021 10:56:51 AM CSE 208 – Java Programming 17
JVM, JRE & JDK
¥ JVM (Java Virtual Machine) - abstract machine, Not exist physically, provides a
runtime environment in which Java bytecode can be executed.
¥ JRE(Java Runtime Environment) - provides the runtime environment,
implementation of JVM, physically exists, contains a set of libraries + other files that
JVM uses at runtime.
¥ JDK(Java Development Kit) - Software development environment which is used to
develop Java applications and applets, physically exists, contains JRE +
development tools.
8/28/2021 10:56:51 AM CSE 208 – Java Programming 18
A Simple Java Program(3)
nextLine()
nextLong()
nextDouble()
Program to Demonstrate Interactive Input
[Link]
[Link]
8/28/2021 10:56:51 AM CSE 208 – Java Programming 19
Classes and Objects
8/28/2021 10:56:51 AM CSE 208 – Java Programming 20
8/28/2021 10:56:52 AM CSE 208 – Java Programming 21
Introducing Classes
[Link]
SAP / ICT / SOC
SASTRA
Two Programming Paradigms
The Three OOP Principles
Class Fundamentals
Declaring Objects
Assigning Object Reference Variables
8/31/2021 2:02:17 PM CSE 208 – Java Programming 2
Programming Paradigms
It is an approach to classify the programming languages.
Procedure oriented programming
Object oriented programming
Imperative Programming
Declarative Programming
Structured Programming
Concurrent Programming
8/31/2021 2:02:17 PM CSE 208 – Java Programming 3
Procedure oriented programming
Emphasis on Algorithms
Large Programs divided
into Functions
Functions share Global
data
Employs Top-Down
approach in program
design
8/31/2021 2:02:17 PM CSE 208 – Java Programming 4
Object oriented programming
Emphasis on Data
Large Programs divided into objects
Data is hidden
Employs Bottom-up approach in program design
8/31/2021 2:02:17 PM CSE 208 – Java Programming 5
Three OOP Principles
8/31/2021 2:02:17 PM CSE 208 – Java Programming 6
Abstraction
Data Abstraction is the property by
virtue of which only the essential details
are displayed to the user.
The non-essentials details are not
displayed to the user.
Data Abstraction may also be defined as
the process of identifying only the
required characteristics of an object
ignoring the irrelevant
In java, abstraction is achieved
by interfaces and abstract classes.
8/31/2021 2:02:17 PM CSE 208 – Java Programming 7
Data Encapsulation
Encapsulation - that binds together
code and the data
Encapsulation - keeps code and data
safe from outside interference and
misuse.
Encapsulation is as a protective wrapper
that prevents the code and data from
being arbitrarily accessed by other code
defined outside the wrapper.
Access to the code and data inside the
wrapper is tightly controlled through a
well-defined interface.
In Java, the basis of encapsulation is
the class
8/31/2021 2:02:17 PM CSE 208 – Java Programming 8
Inheritance
Inheritance is the process by which one
object acquires the properties of another
object.
Inheritance supports the concept of
hierarchical classification.
Without - Each object would need to
define all of its characteristics explicitly.
Using inheritance - an object need only
define those qualities that make it unique
within its class.
It can inherit its general attributes from
its parent.
8/31/2021 2:02:17 PM CSE 208 – Java Programming 9
Inheritance - Types
8/31/2021 2:02:17 PM CSE 208 – Java Programming 10
Polymorphism
8/31/2021 2:02:17 PM CSE 208 – Java Programming 11
Class - Introduction
¥ Java is a true OO language and therefore the
underlying structure of all Java programs is classes.
¥ Anything we wish to represent in Java must be
encapsulated in a class that defines the “state” and
“behaviour” of the basic program components known
as objects.
8/31/2021 2:02:17 PM CSE 208 – Java Programming 12
What is a Class?
¥ A class defines a new data type.
¥ Once defined, this new type can be used to create objects of
that type.
¥ A class is a template for an object, and an object is an
instance of a class.
8/31/2021 2:02:17 PM CSE 208 – Java Programming 13
Class - Example
8/31/2021 2:02:17 PM CSE 208 – Java Programming 14
General form of a class
8/31/2021 2:02:18 PM CSE 208 – Java Programming 15
A Simple Class
class Circle
{
int radius;
void area()
{
}
Three Types
}//class Class – Instance Variables
Class – Methods
Class – Instance variables & Methods
8/31/2021 2:02:18 PM CSE 208 – Java Programming 16
Class - Instance Variables
class Simpleinterest
{
int principal;
int number_of_years;
int rate_of_interest;
}//class
8/31/2021 2:02:18 PM CSE 208 – Java Programming 17
Class - Method
class Simpleinterestdemo
{
public static void main(string args[])
{
}//class
8/31/2021 2:02:18 PM CSE 208 – Java Programming 18
Class - Instance Variables & Method
class NewSimpleinterest
{
int principal;
int number_of_years;
int rate_of_interest;
public static void main(string args[])
{
}//main
}//class
8/31/2021 2:02:18 PM CSE 208 – Java Programming 19
Declaring Objects
8/31/2021 2:02:18 PM CSE 208 – Java Programming 20
Declaring Objects
¥ Declare the Circle class, have created a new data type
¥ Can define variables (objects) of that type:
8/31/2021 2:02:18 PM CSE 208 – Java Programming 21
Objects - Example
8/31/2021 2:02:18 PM CSE 208 – Java Programming 22
Declaring Objects cont.
Circle aCircle; Circle bCircle;
aCircle, bCircle simply refers to an object of type Circle, not
an object itself.
aCircle bCircle
null null
Points to nothing (Null Reference) Points to nothing (Null Reference)
8/31/2021 2:02:18 PM CSE 208 – Java Programming 23
Creating objects of a class
Objects are created dynamically using the new keyword.
aCircle and bCircle refer to Circle objects
Circle aCircle; //declare reference to object
Allocates a circle Object
aCircle = new Circle() ; bCircle = new Circle() ;
8/31/2021 2:02:18 PM CSE 208 – Java Programming 24
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
Before Assignment After Assignment
aCircle bCircle aCircle bCircle
P Q P Q
Accessing Object/Circle
Data
¥ Similar to C syntax for accessing data defined in a class.
[Link]
[Link](parameter-list)
Circle aCircle = new Circle();
[Link] = 1.0
8/31/2021 2:02:18 PM CSE 208 – Java Programming 27
Using Circle Class
class Circle
{
double radius,area;
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
[Link] = 5;
aCircle .area=3.14* [Link]* [Link];
[Link](aCircle .area);
}
}
8/31/2021 2:02:18 PM CSE 208 – Java Programming 28
We have discussed:
POP vs OOP
How to define a class
How to create objects
8/31/2021 2:02:18 PM CSE 208 – Java Programming 29
¥ Lexical Issues
¥ Features of Java
8/31/2021 2:02:18 PM CSE 208 – Java Programming 30
CSE 208
JAVA
PROGRAMMING
[Link]
SAP / ICT / SOC
SASTRA
¥ Lexical Issues
¥ Features of Java
9/1/2021 5:24:24 PM CSE 208 – Java Programming 2
Review
Question!!!!
9/1/2021 5:24:25 PM CSE 208 – Java Programming 3
Question - 1
1. What will be the result of running the following
program?
9/1/2021 5:24:25 PM CSE 208 – Java Programming 4
Question - 2
Java Supports operator overloading?
Yes
No
¥ [Link](“The Result is”+c);
9/1/2021 5:24:25 PM CSE 208 – Java Programming 5
Question - 3
¥ Why do we need compiler to execute the
program ?
¥ Which errors are identified by the compiler?
9/1/2021 5:24:25 PM CSE 208 – Java Programming 6
Lexical Issues
9/1/2021 5:24:25 PM CSE 208 – Java Programming 7
Lexical Issues
¥ Atomic elements of Java.
¥ Java programs are a collection of
White Space
Identifiers
Comments
Literals
Operators
Separators
Keywords
9/1/2021 5:24:25 PM CSE 208 – Java Programming 8
Lexical Issues
¥ Java is a free-form language.
9/1/2021 5:24:25 PM CSE 208 – Java Programming 9
Lexical Issues
Whitespace
¥ For example, the program could have been written all on one
line or in any other strange way you felt like typing it.
¥ In Java, whitespace is a space, tab, or newline.
9/1/2021 5:24:25 PM CSE 208 – Java Programming 10
Lexical Issues
public class Hello { public static void main() { Valid Program
[Link]("Hello Java"); } }
Not Valid
publicclassHello { public static void main() {
[Link]("Hello Java"); } }
9/1/2021 5:24:25 PM CSE 208 – Java Programming 11
Lexical Issues
Identifiers
¥ Identifiers are used for class names, method names, and variable
names.
¥ An identifier may be any descriptive sequence of uppercase and
lowercase letters, numbers, or the underscore and dollar-sign
characters.
¥ They must not begin with a number.
¥ Java is case-sensitive, so VALUE is a different identifier than
Value.
9/1/2021 5:24:25 PM CSE 208 – Java Programming 12
Lexical Issues
Identifiers
¥ Some examples of valid identifiers are:
AvgTemp
count
a4
$test
this_is_ok
¥ Invalid variable names include:
2count
high-temp
Not/ok
9/1/2021 5:24:25 PM CSE 208 – Java Programming 13
Lexical Issues
Literals
¥ A constant value in Java is created by using a literal
representation of it.
¥ For example, here are some literals:
100 98.6 ‘X’ “This is a test”
¥ Left to right, the first literal specifies an integer, the next is a
floating-point value, the third is a character constant, and the
last is a string.
9/1/2021 5:24:25 PM CSE 208 – Java Programming 14
Lexical Issues
Comments
¥ There are three types of comments defined by Java. You
already know two: single-line and multiline. The third type is
called a documentation comment.
¥ This type of comment is used to produce an HTML file that
documents your program.
¥ The documentation comment begins with a /** and ends with
a */.
9/1/2021 5:24:25 PM CSE 208 – Java Programming 15
Lexical Issues
Separators
¥ In Java, there are a few characters that are used as
separators.
¥ The most commonly used separator in Java is the semicolon.
9/1/2021 5:24:25 PM CSE 208 – Java Programming 16
9/1/2021 5:24:25 PM CSE 208 – Java Programming 17
Lexical Issues
The Java Keywords
¥ There are 61 reserved keywords currently defined in the
Java language
¥ The keywords const and goto are reserved but not used.
9/1/2021 5:24:25 PM CSE 208 – Java Programming 18
Characteristics of Java
9/1/2021 5:24:25 PM CSE 208 – Java Programming 19
Characteristics of Java
¥ Java Is Simple
¥ Java Is Object-Oriented
¥ Java Is Distributed
¥ Java Is Interpreted
¥ Java Is Robust
¥ Java Is Secure
¥ Java Is Architecture-Neutral
¥ Java Is Portable
¥ Java Is Multithreaded
9/1/2021 5:24:25 PM CSE 208 – Java Programming 20
Characteristics of Java
¥ Java Is Simple Easy to learn and use effectively
¥ Java Is Object-Oriented Some Programming experience –
find difficult to learn.
¥ Java Is Distributed Inherits C syntax
¥ Java Is Interpreted Inherits C++ Object oriented
features
¥ Java Is Robust
¥ Java Is Secure
¥ Java Is Architecture-
Neutral
¥ Java Is Portable
¥ Java Is Multithreaded
9/1/2021 5:24:25 PM CSE 208 – Java Programming 21
Characteristics of Java
¥ Java Is Simple Not designed to be source code
compatible
¥ Java Is Object-Oriented
Freedom to design
¥ Java Is Distributed
¥ Java Is Interpreted Outcome – clean, usable,
pragmatic approach to objects
¥ Java Is Robust
¥ Java Is Secure
¥ Java Is Architecture-
Neutral
¥ Java Is Portable
¥ Java Is Multithreaded
9/1/2021 5:24:25 PM CSE 208 – Java Programming 22
Characteristics of Java
¥ Java Is Simple Distributed computing involves
several computers working
¥ Java Is Object-Oriented together on a network.
¥ Java Is Distributed Java is designed to make
¥ Java Is Interpreted distributed computing easy.
¥ Java Is Robust Since networking capability is
inherently integrated into Java,
¥ Java Is Secure writing network programs is like
sending and receiving data to
¥ Java Is Architecture-
and from a file.
Neutral
¥ Java Is Portable
¥ Java Is Multithreaded
9/1/2021 5:24:25 PM CSE 208 – Java Programming 23
Characteristics of Java
¥ Java Is Simple You need an interpreter to run
Java programs.
¥ Java Is Object-Oriented
The programs are compiled into
¥ Java Is Distributed the Java Virtual Machine code
¥ Java Is Interpreted called byte code.
¥ Java Is Robust The byte code is machine-
independent and can run on any
¥ Java Is Secure machine that has a Java
interpreter, which is part of the
¥ Java Is Architecture-
Java Virtual Machine (JVM).
Neutral
¥ Java Is Portable
¥ Java Is Multithreaded
9/1/2021 5:24:26 PM CSE 208 – Java Programming 24
Characteristics of Java
¥ Java Is Simple Memory Management Mistakes
Mishandles Exceptional
¥ Java Is Object-Oriented conditions
¥ Java Is Distributed Garbage Collection Mechanism
¥ Java Is Interpreted
Java compilers can detect many
¥ Java Is Robust problems that would first show
up at execution time in other
¥ Java Is Secure languages.
¥ Java Is Architecture-
Java has a runtime exception-
Neutral handling feature to provide
¥ Java Is Portable programming support for
robustness.
¥ Java Is Multithreaded
9/1/2021 5:24:26 PM CSE 208 – Java Programming 25
Characteristics of Java
¥ Java Is Simple
¥ Java Is Object-Oriented
¥ Java Is Distributed
¥ Java Is Interpreted Java implements several security
mechanisms to protect your system
¥ Java Is Robust against harm caused by stray
programs.
¥ Java Is Secure
¥ Java Is Architecture-
Neutral
¥ Java Is Portable
¥ Java Is Multithreaded
9/1/2021 5:24:26 PM CSE 208 – Java Programming 26
Characteristics of Java
¥ Java Is Simple
¥ Java Is Object-Oriented
¥ Java Is Distributed
¥ Java Is Interpreted
¥ Java Is Robust
¥ Java Is Secure Write once, run anywhere
¥ Java Is Architecture- With a Java Virtual Machine
Neutral (JVM), you can write one program
that will run on any platform.
¥ Java Is Portable
¥ Java Is Multithreaded
9/1/2021 5:24:26 PM CSE 208 – Java Programming 27
Characteristics of Java
¥ Java Is Simple
¥ Java Is Object-Oriented
¥ Java Is Distributed
¥ Java Is Interpreted
¥ Java Is Robust
Because Java is architecture
¥ Java Is Secure neutral, Java programs are
portable. They can be run on any
¥ Java Is Architecture- platform without being
Neutral recompiled.
¥ Java Is Portable
¥ Java Is Multithreaded
9/1/2021 5:24:26 PM CSE 208 – Java Programming 28
Characteristics of Java
¥ Java Is Simple
¥ Java Is Object-Oriented
¥ Java Is Distributed
¥ Java Is Interpreted
¥ Java Is Robust
Multithread programming is
¥ Java Is Secure smoothly integrated in Java, whereas
in other languages you have to call
¥ Java Is Architecture- procedures specific to the operating
Neutral system to enable multithreading.
¥ Java Is Portable
¥ Java Is Multithreaded
9/1/2021 5:24:26 PM CSE 208 – Java Programming 29
Methods and Constructors
9/1/2021 5:24:26 PM CSE 208 – Java Programming 30
Introducing Classes - II
[Link]
SAP / ICT / SOC
SASTRA
Introducing Methods
Constructors
Parameterized Constructors
Instance Variable Hiding
“this” – keyword
Garbage Collection Mechanism
9/3/2021 7:08:28 PM CSE 208 – Java Programming 2
Introducing Methods
9/3/2021 7:08:28 PM CSE 208 – Java Programming 3
Adding Methods
¥ Methods are declared inside the body of the
class but immediately after the declaration of
instance variables.
¥ The general form of a method declaration is:
type MethodName (parameter-list)
{
Method-body;
//return value
}
9/3/2021 7:08:28 PM CSE 208 – Java Programming 4
Adding Methods to Class Circle
class Circle
{
double r; // radius of circle
//Method to compute circumference and area
void circumference()
{
[Link](2*3.14*r);
}
Method Body
void area()
{
[Link](3.14 * r * r);
}
}
Method - Returning a Value
class Circle
{
double r; // radius of circle
//Method to compute area
double area()
{
double area=3.14 * r * r Method that
return area; returns a value
}
}
Method – that takes parameters
class Circle
{
double r; // radius of circle
//Method to compute area
void area(double x)
{ Method that
[Link](3.14 * x * x); takes parameter
}
}
Constructor
9/3/2021 7:08:28 PM CSE 208 – Java Programming 8
Constructor – Need ?
It can be tedious to initialize all of the variables in a class each
time an instance is created.
Use a method
Invoke the method
Initialize – when the object is created
Java allows objects to initialize themselves when they are
created.
This automatic initialization is performed through the use of a
constructor.
9/3/2021 7:08:28 PM CSE 208 – Java Programming 9
Constructor
A constructor initializes an object immediately upon creation.
Constructor has the same name as the class
Constructor is syntactically similar to a method.
no return type
not even void.
The implicit return type of a class constructor is the class type
itself.
Once defined
the constructor is automatically called when the object
is created.
9/3/2021 7:08:28 PM CSE 208 – Java Programming 10
Constructor - Example
class Circle
{
double radius,area;
Circle()
{ Constructor
radius=5;
}
void computeArea()
{
area=3.14* radius* radius; User defined method
[Link](area);
}
9/3/2021 7:08:28 PM CSE 208 – Java Programming 11
Constructor - Example
public static void main(String args[])
{
Circle aCircle = new Circle(); Constructor
[Link](); Invocation
}
}
E:\slides\Java - 2020\Unit - I>javac [Link]
E:\slides\Java - 2020\Unit - I>java Circle
78.5
9/3/2021 7:08:28 PM CSE 208 – Java Programming 12
Parameterized Constructor - Example
class Circle
{
double radius,area;
Circle(double r)
{ Constructor
radius=r;
}
void computeArea()
{
area=3.14* radius* radius; User defined method
[Link](area);
}
9/3/2021 7:08:28 PM CSE 208 – Java Programming 13
Parameterized Constructor - Example
public static void main(String args[])
{
Circle aCircle = new Circle(5); Parameterized
[Link](); Constructor
} Invocation
}
9/3/2021 7:08:28 PM CSE 208 – Java Programming 14
Instance Variable Hiding
class Circle
{
double radius,area; Local Variable name is
same as Instance
Circle(double radius) variable
{ Local variable hides
radius=radius; instance variable
}
void computeArea()
{
area=3.14* radius* radius; User defined method
[Link](area);
}
9/3/2021 7:08:28 PM CSE 208 – Java Programming 15
Instance Variable Hiding
public static void main(String args[])
{
Circle aCircle = new Circle(5); Parameterized
[Link](); Constructor
} Invocation
}
E:\slides\Java - 2020\Unit - I>javac [Link]
E:\slides\Java - 2020\Unit - I>java Circle
0.0
9/3/2021 7:08:28 PM CSE 208 – Java Programming 16
The this Keyword
class Circle
{
double radius,area;
Prefix the instance
Circle(double radius) variable with the
{ keyword “this”
[Link]=radius;
}
void computeArea()
{
area=3.14* radius* radius; User defined method
[Link](area);
}
9/3/2021 7:08:28 PM CSE 208 – Java Programming 17
The this Keyword
public static void main(String args[])
{
Circle aCircle = new Circle(5); Parameterized
[Link](); Constructor
} Invocation
}
E:\slides\Java - 2020\Unit - I>javac [Link]
E:\slides\Java - 2020\Unit - I>java Circle
78.5
9/3/2021 7:08:28 PM CSE 208 – Java Programming 18
Garbage collection Mechanism
objects are dynamically allocated by using the new operator
How such objects are destroyed and their memory released
for later reallocation?
In C++ - allocated objects must be manually released by use
of a delete operator.
Java handles deallocation automatically.
The technique that accomplishes this is called garbage
collection.
9/3/2021 7:08:29 PM CSE 208 – Java Programming 19
Garbage collection Mechanism
¥ It works like this when no references to an object exist, that
object is assumed to be no longer needed, and the memory
occupied by the object can be reclaimed.
¥ There is no need to explicitly destroy objects.
¥ Garbage collection only occurs sporadically (if at all) during
the execution of your program.
¥ It will not occur simply because one or more objects exist that
are no longer used.
¥ Furthermore, different Java run-time implementations will take
varying approaches to garbage collection, but for the most
part, you should not have to think about it while writing your
programs.
9/3/2021 7:08:29 PM CSE 208 – Java Programming 20
We have discussed:
How to add methods to
classes?
Types of methods
Constructorand
Parameterized constructor
Instance variable hiding –
solution
Garbage collection
mechanism
9/3/2021 7:08:29 PM CSE 208 – Java Programming 21
Method Overloading
9/3/2021 7:08:29 PM CSE 208 – Java Programming 22
¥ Area of a Square
¥ Simple Interest Calculation
¥ Sum and average of 3 numbers
9/3/2021 7:08:29 PM CSE 208 – Java Programming 23
CSE 208
JAVA PROGRAMMING
[Link]
SAP / ICT / SOC
SASTRA
Data Types
Variables
Constants
CSE 208 – Java Programming 2
Need for a Data Type?
¥ Two Purposes
¥ To guard against programming errors
¥ To specify the desired degree of numerical precision
CSE 208 – Java Programming 3
Primitive Data Types
CSE 208 – Java Programming 4
Data Types
Modern programming languages
Java supports several types of data.
You may use these types to declare variables
and to create arrays
CSE 208 – Java Programming 5
Data Types
Java Is a strongly typed language
Variable has a type
Expression has a type
All assignments
Explicit or via parameter passing are checked for type
compatibility
No automatic conversion of conflicting data types
CSE 208 – Java Programming 6
Data Types
A=123;
B=456.789
C=false;
int a;
a=“sastra”; void add(int a, int b)
{
}
int a; add(123,45.67)
a=123.456;
CSE 208 – Java Programming 7
Simple Types
¥ There are exactly eight primitive data types in Java
Four of them represent integers:
byte, short, int, long
Two of them represent floating point numbers:
float, double
One of them represents characters:
char
And one of them represents boolean values:
boolean
CSE 208 – Java Programming 8
Some Built-In Types Of Variables In Java
Type Description
byte 8 bit signed integer
short 16 but signed integer
int 32 bit signed integer
long 64 bit signed integer
float 32 bit signed real number
double 64 bit signed real number
char 16 bit Unicode character (ASCII and beyond)
boolean 1 bit true or false value
String A sequence of characters between double quotes ("")
Numeric Primitive Data
¥ The difference between the various numeric primitive types is their size,
and therefore the values they can store:
Type Storage Min Value Max Value
byte 8 bits -128 127
short 16 bits -32,768 32,767
int 32 bits -2,147,483,648 2,147,483,647
long 64 bits < -9 x 1018 > 9 x 1018
float 32 bits +/- 3.4 x 1038 with 7 significant digits
double 64 bits +/- 1.7 x 10308 with 15 significant digits
CSE 208 – Java Programming 10
Characters
¥ A char variable stores a single character from the Unicode character set
¥ A character set is an ordered list of characters, and each character
corresponds to a unique number
¥ The Unicode character set uses sixteen bits per character, allowing for
65,536 unique characters
¥ It is an international character set, containing symbols and characters from
many world languages(Latin, Greek, Arabic)
¥ Character literals are delimited by single quotes:
'a' 'X' '7' '$' ',' '\n'
CSE 208 – Java Programming 11
Boolean
¥ A boolean value represents a true or false
condition
¥ A boolean can also be used to represent any
two states, such as a light bulb being on or off
¥ The reserved words true and false are
the only valid values for a boolean type
boolean done = false;
CSE 208 – Java Programming 12
CSE 208 – Java Programming 13
Variables
¥ A variable is a name for a location in memory
¥ A variable must be declared, specifying the variable's name
and the type of information that will be held in it
data type variable name
int total;
int count, temp, result;
Multiple variables can be created in one declaration
CSE 208 – Java Programming 14
Variables
Types of Variables:
¥ Local variables
¥ Instance variables
¥ Class/Static variables
CSE 208 – Java Programming 15
Variables
Local variables public class Hello
{
Declared in methods, public static void main(String a[])
constructors, or blocks, {
Created when the method, private int a;
constructor or block is [Link](a);
entered and the variable will }
}
be destroyed once it exits
the method, constructor, or
E:\slides\Java - 2021\>javac [Link]
block. [Link]: error: illegal start of
expression
Access modifiers cannot be private int a;
used for local variables. ^
1 error
CSE 208 – Java Programming 16
Variables
Local variables
Visible only within the declared method, constructor, or block.
No default value for local variables(should be declared and an
initial value should be assigned before the first use).
public class Hello
{ E:\slides\Java - 2021>javac [Link]
public static void main(String a[]) [Link]: error: variable a might not have been
{ initialized
[Link](a);
int a; ^
[Link](a); 1 error
}
}
CSE 208 – Java Programming 17
Variables
Instance variables
¥ Instance variables are declared in a class, but outside a method,
constructor or any block.
¥ Instance variables can be declared in class level
¥ Access modifiers can be given for instance variables.
¥ Values can be assigned during the declaration or within the
constructor.
public class Hello
{
private int a;
public static void main(String args[])
{
[Link](a);
}
}
CSE 208 – Java Programming 18
Variables
Instance variables
The instance variables are visible for all methods, constructors
and block in the class.
Normally, it is recommended to make these variables private
(access level).
However, visibility for subclasses can be given for these
variables with the use of access modifiers.
CSE 208 – Java Programming 19
Variables
Instance variables public class Hello
Instance variables have default {
values. private int a;
For numbers, boolean b;
double c;
the default value is 0,
Booleans it is false, and void show()
object references it is null. {
[Link](a);
[Link](b);
[Link](c);
}
E:\slides\Java - 2021\>java Hello public static void main(String args[])
0 {
Hello h=new Hello();
false [Link]();
0.0 }
}
CSE 208 – Java Programming 20
Variables
¥ Class/Static Variables
Class variables also known as static variables are
declared with the static keyword in a class, but outside a
method, constructor or a block.
There would only be one copy of each class variable per
class, regardless of how many objects are created from it.
Static variables are created when the program starts and
destroyed when the program stops.
Visibility is similar to instance variables.
However, most static variables are declared public since
they must be available for users of the class.
CSE 208 – Java Programming 21
Variables
¥ Class/Static Variables
Default values are same as instance variables.
Values can be assigned during the declaration or within the
constructor.
Additionally, values can be assigned in special static
initializer blocks.
Static variables can be accessed by calling with the class
name [Link].
CSE 208 – Java Programming 22
Variables
public class Variable
{
private static int a;
public static void main(String args[])
{
[Link](a);
}
}
E:\slides\Java - 2021\Unit - I>java Variable
0
CSE 208 – Java Programming 23
Variables
public class Variable
{
private static int a;
static
{
a=12345;
}
public static void main(String args[])
{
[Link](a);
}
}
E:\slides\Java - 2021\Unit - I>java Variable
12345
CSE 208 – Java Programming 24
CSE 208 – Java Programming 25
Constants
A constant is an identifier that is similar to a variable except
that it holds one value for its entire existence
The compiler will issue an error if you try to change a constant
In Java, we use the final modifier to declare a constant
final int MIN_HEIGHT = 69;
const int MIN_HEIGHT = 69;
CSE 208 – Java Programming 26
Data Types
Variables
Local variables
Instance variables
Class/Static variables
Constants
CSE 208 – Java Programming 27
Data Conversion
Arrays
CSE 208 – Java Programming 28
CSE 208
JAVA
PROGRAMMING
[Link]
SAP / ICT / SOC
SASTRA
Data Conversion
Arrays
Operators
9/7/2021 1:56:52 PM CSE 208 – Java Programming 2
Data Conversions
9/7/2021 1:56:52 PM CSE 208 – Java Programming 3
Data Conversions
¥ It is fairly common to assign a value of one type to a variable
of another type
¥ Sometimes it is convenient to convert data from one type to
another
¥ For example, we may want to treat an integer as a floating
point value during a computation
¥ Conversions must be handled carefully to avoid losing
information
9/7/2021 1:56:52 PM CSE 208 – Java Programming 4
Data Conversions
Widening conversions
are safest because they tend to go from a small data type
to a larger one (such as a short to an int)
Narrowing conversions
can lose information because they tend to go from a large
data type to a smaller one (such as an int to a short)
9/7/2021 1:56:52 PM CSE 208 – Java Programming 5
Data Conversions
¥ In Java, data conversions can occur in three ways:
Assignment conversion
Arithmetic promotion
Casting
9/7/2021 1:56:52 PM CSE 208 – Java Programming 6
Assignment Conversion
public class DataConversion
¥ Assignment
{
conversion
public static void main(String args[])
occurs when a
{
value of one
short s;
type is assigned
byte b=123;
to a variable of
s=b;
another
[Link](s);
¥ Only widening }
conversions can }
happen via
assignment
E:\slides\Java - 2021>java DataConversion
123
9/7/2021 1:56:52 PM CSE 208 – Java Programming 7
Assignment Conversion
public class DataConversion
{
public static void main(String args[])
{
short s=123;
byte b;
b=s;
[Link](b);
}
} E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: incompatible types: possible lossy conversion from
short to byte
b=s;
^
1 error
9/7/2021 1:56:52 PM CSE 208 – Java Programming 8
Data Conversions
¥ Arithmetic promotion happens automatically when operators in
expressions convert their operands
public class TypePromotion
{
public static void main(String args[])
{
short s=123;
int i=12345; First,all byte, short, and char values are
promoted to int,
double result; Then, if one operand is a long
result=s+i; If one operand is a float,
[Link](result); If any of the operands are double,
} the result is double.
}
E:\slides\Java - 2021\Unit - I>java TypePromotion
12468.0
9/7/2021 1:56:52 PM CSE 208 – Java Programming 9
Data Conversions
¥ Casting is the most powerful, and dangerous, technique for conversion
¥ Both widening and narrowing conversions can be accomplished by
explicitly casting a value
¥ To cast, the type is put in parentheses in front of the value being converted
¥ For example, if total and count are integers, but we want a floating
point result when dividing them, we can cast total:
result = (float) total / count;
9/7/2021 1:56:52 PM CSE 208 – Java Programming 10
Arrays
9/7/2021 1:56:52 PM CSE 208 – Java Programming 11
Arrays
Java supports arrays
An array is a collection of elements where each element is the
same type.
Element type can be primitive or Object
Each element is a single value
The length of the array is set when it is created.
It cannot change.
12
Arrays
¥ An array is an ordered list of values
The entire array Each value has a numeric index
has a single name
0 1 2 3 4 5 6 7 8 9
scores 79 87 94 82 67 98 87 81 74 91
An array of size N is indexed from zero to N-1
This array holds 10 values that are indexed from 0 to 9
9/7/2021 1:56:52 PM CSE 208 – Java Programming 13
Arrays
¥ A particular value in an array is referenced
using the array name followed by the index in
brackets
¥ For example, the expression
scores[2]
refers to the value 94 (which is the 3rd value
in the array)
9/7/2021 1:56:52 PM CSE 208 – Java Programming 14
Creating Arrays
Creating an array is a 2 step process
It must be declared (declaration does not specify size)
int grades[5];
declaration syntax: type[] arrayName;
note the location of the []
It must be created (ie. memory must be allocated for the array)
int[] grades; // declaration
grades = new int[5]; // Create array.
// specify size
// assign new array to
// array variable
Creating Arrays
When an array is created, all of its elements are automatically
initialized
0 for integral types
0.0 for floating point types
false for boolean types grades
null for object types
array indices 0 0
int[] grades = new int[5];
1 0
2 0
3 0
Note: maximum array index is length -1 4 0
Initializing and Using Arrays
Because array elements are initialized to 0, the array should
be initialized with usable values before the array is used.
This can be done with a loop
Arrays have a length attribute which can be used for bounds checking
Elements are accessed using an index and []
int[] sequence = new int[5];
for (int i=0; i< [Link]; i++)
{
sequence[i] = i * 25;
}
array length: ensures loop
Array element being accessed. In this won't go past end of the array
case, it is being assigned a value.
Using initializer lists
Another way of initializing lists is by using initializer lists.
The array is automatically created
The array size is computed from the number of items in the list.
type[] arrayName = {initializer_list};
int[] grades = {100, 96, 78, 86, 93};
String[] colours = { "Red", "Orange",
"Yellow", "Green",
"Blue", "Indigo",
"Violet"};
Initializer Lists
Note that when an initializer list is used:
the new operator is not used
no size value is specified
The size of the array is determined by the number of
items in the initializer list
An initializer list can only be used in the declaration of
an array
9/7/2021 1:56:53 PM CSE 208 – Java Programming 19
Array Bounds Checking
Whenever and array is accessed, the index is checked to
ensure that it within the bounds of the array.
Attempts to access an array element outside the bounds of
the array will cause an ArrayIndexOutOfBounds exception to
be thrown.
int[] sequence = new int[5];
sequence[0] = 50; // ok
sequence[1] = 60; // ok
sequence[-1] = 100; // Exception
sequence[5] = 30; // Exception
The main() method
You may recall that the main method takes an array of String
objects as a parameter.
This array of Strings holds the command line parameters which were
passed to the java program when it was started
public class HelloWorld
{
public static void main(String[] args)
{
[Link]("Hello World");
}
}
Array holding command line parameters
Bounds Checking
Each array object has a public constant called
length that stores the size of the array
It is referenced using the array name (just like
any other object):
[Link]
Note that length holds the number of elements,
not the largest index
9/7/2021 1:56:53 PM CSE 208 – Java Programming 22
Array Declarations Revisited
The brackets of the array type can be associated with
the element type or with the name of the array
Therefore the following declarations are equivalent:
float[] prices;
float prices[];
The first format is generally more readable
9/7/2021 1:56:53 PM CSE 208 – Java Programming 23
Arrays as Parameters
An entire array can be passed to a method as a parameter
Like any other object, the reference to the array is passed,
making the formal and actual parameters aliases of each
other
Changing an array element in the method changes the original
An array element can be passed to a method as well, and will
follow the parameter passing rules of that element's type
9/7/2021 1:56:53 PM CSE 208 – Java Programming 24
Arrays of Objects
The elements of an array can be object
references
The following declaration reserves space to
store 25 references to String objects
String[] words = new String[25];
9/7/2021 1:56:53 PM CSE 208 – Java Programming 25
Two-Dimensional Arrays
¥ A one-dimensional array stores a simple list of values
¥ A two-dimensional array can be thought of as a table of values,
with rows and columns
¥ A two-dimensional array element is referenced using two index
values
¥ To be precise, a two-dimensional array in Java is an array of
arrays
9/7/2021 1:56:53 PM CSE 208 – Java Programming 26
Two-Dimensional Arrays
¥ int number[][]=new int[3][4]
¥ int number[][]={{0,0,0},{1,1,1}}
9/7/2021 1:56:53 PM CSE 208 – Java Programming 27
9/7/2021 1:56:53 PM CSE 208 – Java Programming 28
Operators
Operator Type Category Precedence
postfix expr++, expr--
Unary
prefix ++expr, --expr, +expr, -expr, ~ , !
multiplicative * / %
Arithmetic
additive + -
Shift shift << >> >>>
comparison < > <= >= instanceof
Relational
equality == !=
bitwise AND &
Bitwise bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
Logical
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
9/7/2021 1:56:53 PM CSE 208 – Java Programming 29
REVIEW
QUESTIONS
9/7/2021 1:56:53 PM CSE 208 – Java Programming 30
Question 1
Strings are a primitive data type in Java.
A. TRUE
B. FALSE
9/7/2021 1:56:53 PM CSE 208 – Java Programming 31
Question 2
What is output by the following Java code?
int x = 3;
double a = x / 2 + 3.5;
[Link](a);
A. a
B. 5
C. 4.5
D. 4
E. 5.0
9/7/2021 1:56:53 PM CSE 208 – Java Programming 32
Question 3
int[] list = {5, 1, 7, 3};
[Link]( list[2] );
[Link]( list[4] );
What is output by the code to the right?
A. Output will vary from one run of program to next
B. 00
C. 363
D. 7 then a runtime error
E. No output due to syntax error
9/7/2021 1:56:53 PM CSE 208 – Java Programming 33
Data Conversion
Widening
Narrowing
Arrays
Creation
Single Dimension
Two Dimension
Operators
9/7/2021 1:56:53 PM CSE 208 – Java Programming 34
Method Overloading
Constructor Overloading
9/7/2021 1:56:54 PM CSE 208 – Java Programming 35
A Closer Look
at
Methods and Classes
[Link]
SAP / ICT / SOC
SASTRA
Overloading Methods
Overloading Constructors
Using Objects as Parameters
A Closer Look at Argument
Passing
Returning Objects
9/8/2021 6:36:58 PM CSE 208 – Java Programming 2
Review Question - 1
class Array
{
public static void main(String args[])
{
int a[]={};
[Link](a[0]);
}
} F:\java>java Array
Exception in thread "main"
[Link]: 0
at [Link]([Link])
9/8/2021 6:36:59 PM CSE 208 – Java Programming 3
Review Question - 2
class Array
{
public static void main(String args[])
{
int a[]={0};
[Link](a[0]);
a[1]=123;
[Link](a[0]);
F:\java>java Array
}
0
} Exception in thread "main"
[Link]: 1
at [Link]([Link])
9/8/2021 6:36:59 PM CSE 208 – Java Programming 4
Review Question - 3
class Array
{
public static void main(String args[])
{
[Link](‘a’); F:\java>java Array
a
[Link](‘a’+0); 97
[Link](“a”+0); a0
}
}
9/8/2021 6:36:59 PM CSE 208 – Java Programming 5
Overloading Methods
9/8/2021 6:36:59 PM CSE 208 – Java Programming 6
Overloading Methods
In Java,
it is possible to define two or more methods
within the same class that share the same name
as long as their parameter declarations are different.
The methods are said to be overloaded
The process is referred to as method overloading.
Method overloading is one of the ways that Java supports
polymorphism.
9/8/2021 6:36:59 PM CSE 208 – Java Programming 7
Overloading Methods
When an overloaded method is invoked
Determine which version of the overloaded method to actually
call
Java uses the type and/or number of arguments as its guide
Overloaded methods must differ in the type and/or number of
their parameters.
Java encounters a call to an overloaded method
it simply executes the version of the method whose
parameters match the arguments used in the call.
9/8/2021 6:36:59 PM CSE 208 – Java Programming 8
Overloading Methods
class Shape
{
void computeArea(int l)
{
int area= l * l;
[Link]("Square Area:--->"+area);
}
void computeArea(int l,int b)
{
int area= l * b;
[Link]("Rectangle Area:--->"+area);
}
9/8/2021 6:36:59 PM CSE 208 – Java Programming 9
Overloading Methods
void computeArea(double radius)
{
double area=3.14* radius* radius;
[Link]("Circle Area:--->"+area);
}
public static void main(String args[])
{
Shape s=new Shape();
[Link](2);
[Link](3,3); E:\slides\Java - 2021\Unit - I>java Shape
[Link](5); Square Area:--->4
} Rectangle Area:--->9
} Square Area:--->25
9/8/2021 6:36:59 PM CSE 208 – Java Programming 10
Overloading Methods
public static void main(String args[])
{
Shape s=new Shape();
[Link](2);
[Link](3,3);
[Link](5.0);
}
} E:\slides\Java - 2021\Unit - I>java Shape
Square Area:--->4
Rectangle Area:--->9
Circle Area:--->78.5
9/8/2021 6:36:59 PM CSE 208 – Java Programming 11
Overloading Methods
class Shape Java’s automatic type
{ conversions can play a role in
overload resolution
void computeArea(int l,int b)
{
int area= l * b;
[Link]("Rectangle Area:--->"+area);
}
void computeArea(double radius)
{
double area=3.14* radius* radius;
[Link]("Circle Area:--->"+area);
}
9/8/2021 6:36:59 PM CSE 208 – Java Programming 12
Overloading Methods
public static void main(String args[])
{
Shape s=new Shape();
[Link](2);
[Link](3,3);
[Link](5.0);
}
}
E:\slides\Java - 2021\Unit - I>java Shape
Circle Area:--->12.56
Rectangle Area:--->9
Circle Area:--->78.5
9/8/2021 6:36:59 PM CSE 208 – Java Programming 13
Overloading Methods
public static void main(String args[])
{
Shape s=new Shape();
[Link]('a');
}
}
E:\slides\Java - 2021\Unit - I>java Shape
Circle Area:--->29544.26
9/8/2021 6:36:59 PM CSE 208 – Java Programming 14
Overloading Methods
public static void main(String args[])
{
Shape s=new Shape();
[Link](”a”);
}
}
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: incompatible types: String cannot
be converted to double
[Link]("a");
9/8/2021 6:36:59 PM CSE 208 – Java Programming 15
Overloading Methods
class Shape
{
void computeArea(int l)
{
int area= l * l;
[Link]("Square Area:--->"+area);
}
void computeArea(int l,int b)
{
int area= l * b;
[Link]("Rectangle Area:--->"+area);
}
9/8/2021 6:36:59 PM CSE 208 – Java Programming 16
Overloading Methods
public static void main(String args[])
{
Shape s=new Shape();
[Link](12.34);
}
}
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: incompatible types: possible lossy
conversion from double to int
[Link](12.34);
^
9/8/2021 6:36:59 PM CSE 208 – Java Programming 17
Overloading Constructors
9/8/2021 6:36:59 PM CSE 208 – Java Programming 18
Constructor Overloading
class Shape
{
Shape(int l)
{
int area= l * l;
[Link]("Square Area:--->"+area);
}
Shape(int l,int b)
{
int area= l * b;
[Link]("Rectangle Area:--->"+area);
}
9/8/2021 6:36:59 PM CSE 208 – Java Programming 19
Constructor Overloading
Shape(double radius)
{
double area=3.14* radius* radius;
[Link]("Circle Area:--->"+area);
}
public static void main(String args[])
{
[Link]("Constructor Overloading");
Shape s1=new Shape(2);
Shape s2=new Shape(3,3); E:\slides\Java - 2021\Unit - I>java Shape
Shape s3=new Shape(5.0); Constructor Overloading
} Square Area:--->4
} Rectangle Area:--->9
Circle Area:--->78.5
9/8/2021 6:36:59 PM CSE 208 – Java Programming 20
Objects as Parameters
9/8/2021 6:37:00 PM CSE 208 – Java Programming 21
Objects as Parameters
class Circle
{
double radius;
Circle(double radius)
{
[Link]=radius;
}
boolean compare(Circle c)
{
if([Link] == radius)
return true;
else
return false;
}
9/8/2021 6:37:00 PM CSE 208 – Java Programming 22
Objects as Parameters
public static void main(String args[])
{
Circle c1 = new Circle(10);
Circle c2 = new Circle(10);
Circle c3 = new Circle(15);
[Link]("Both objects are Equal--->" + [Link](c2));
[Link]("Both objects are Equal--->" + [Link](c3));
}
}
E:\slides\Java - 2021\Unit - I>java Circle
Both objects are Equal--->true
Both objects are Equal--->false
9/8/2021 6:37:00 PM CSE 208 – Java Programming 23
A Closer Look at Argument Passing
9/8/2021 6:37:00 PM CSE 208 – Java Programming 24
Argument Passing
There are two ways to pass an argument to a Method.
call-by-value.
call-by-reference.
9/8/2021 6:37:00 PM CSE 208 – Java Programming 25
call-by-value
This approach copies the value of an argument into the
formal parameter of the method.
Changes made to the parameter of the method have no
effect on the argument.
When you pass a primitive type to a method, it is
passed by value.
Example
9/8/2021 6:37:00 PM CSE 208 – Java Programming 26
call-by-value
E:\slides\Java - 2021\Unit - I>java ArrayElementToMethod
Contents of the Array is
1
2
3
4
5
Inside Method 5
Contents of the Array After method invocation is
1
2
3
4
5
9/8/2021 6:37:00 PM CSE 208 – Java Programming 27
call-by-reference
In this approach, a reference to an argument (not the value
of the argument) is passed to the parameter.
Inside the method ,
this reference is used to access the actual argument
specified in the call.
Changes made to the parameter will affect the argument
used to call the method.
objects are passed by call-by-reference
Example
9/8/2021 6:37:00 PM CSE 208 – Java Programming 28
call-by-reference
E:\slides\Java - 2021\Unit - I>java ArrayToMethod
Contents of the Array is
1
2
3
4
5
Contents of the Array After method invocation is
5
10
15
20
25
9/8/2021 6:37:00 PM CSE 208 – Java Programming 29
We have discussed:
Overloading
Methods
Constructors
Objects as Parameters
Argument Passing
call-by-value
call-by-reference
Returning Objects
9/8/2021 6:37:00 PM CSE 208 – Java Programming 30
Static
Command line
Arguments
9/8/2021 6:37:00 PM CSE 208 – Java Programming 31
A Closer Look
at
Methods and Classes - II
[Link]
SAP / ICT / SOC
SASTRA
Understanding static
Introducing Final
Using Command-Line Arguments
9/11/2021 12:31:22 PM CSE 208 – Java Programming 2
Methods - Returning Objects
9/11/2021 12:31:23 PM CSE 208 – Java Programming 3
Returning Objects
class student
{
int a;
protected void finalize()
{
[Link]("hello");
}
student get()
{
student ob=new student();
ob.a=20;
return ob;
}
9/11/2021 12:31:23 PM CSE 208 – Java Programming 4
Returning Objects
public static void main(String args[])
{
student s1=new student();
student s2;
s2=[Link]();
[Link](s1.a);
[Link](s2.a);
}
}
E:\slides\Java - 2021\Unit - I>java student
0
20
9/11/2021 12:31:23 PM CSE 208 – Java Programming 5
Understanding static
9/11/2021 12:31:23 PM CSE 208 – Java Programming 6
static - Keyword
Need to define a class member that will be used
independently of any object of that class.
Normally
a class member must be accessed only in conjunction with
an object of its class.
However
it is possible to create a member that can be used by itself,
without reference to a specific instance.
To create such a member
precede its declaration with the keyword static.
9/11/2021 12:31:23 PM CSE 208 – Java Programming 7
static - Keyword
When a member is declared static,
it can be accessed before any objects of its class are
created,
without reference to any object.
Declare both methods and variables to be static.
The most common example of a static member is main( ).
main( ) is declared as static because it must be called
before any objects exist.
9/11/2021 12:31:23 PM CSE 208 – Java Programming 8
static – Method- Example 1
class Circle E:\slides\Java - 2021\Unit - I>java Circle
{ Circle Area:---->78.5
static void area()
{
double radius=5.0; Static method
double result;
result=3.14*radius*radius;
[Link]("Circle Area:---->"+result);
}
public static void main(String args[])
{
area(); Static method Invocation
}
}
9/11/2021 12:31:23 PM CSE 208 – Java Programming 9
static – Method- Example 2
class Circle
class Circle
{
{
static void area()
void area()
{
{
double radius=5.0;
double radius=5.0;
double result;
double result;
result=3.14*radius*radius;
result=3.14*radius*radius;
[Link](result);
[Link](result);
}
}
}
}
class circledemo
class circledemo
{
{
public static void main(String args[])
public static void main(String args[])
{
{
[Link]();
Circle c1=new Circle();
}
[Link]();
}
}
}
9/11/2021 12:31:23 PM CSE 208 – Java Programming 10
static – Method - Example 2
E:\slides\Java - 2020\Unit - I>javac [Link]
E:\slides\Java - 2020\Unit - I>dir *.class
Volume in drive E is New Volume
Volume Serial Number is 8897-C289
Directory of E:\slides\Java - 2020\Unit - I
08/28/2020 10:36 PM 406 [Link]
08/28/2020 10:36 PM 308 [Link]
2 File(s) 714 bytes
0 Dir(s) 24,698,941,440 bytes free
9/11/2021 12:31:23 PM CSE 208 – Java Programming 11
static – Keyword- Example 2
E:\slides\Java - 2021\Unit - I>java circledemo
78.5
E:\slides\Java - 2020\Unit - I>java Circle
Error: Main method not found in class Circle, please define the main
method as: public static void main(String[] args)
or a JavaFX application class must extend [Link]
9/11/2021 12:31:23 PM CSE 208 – Java Programming 12
static – variable – Example 1
class Circle
{
static double radius; E:\slides\Java - 2021\Unit - I>java Circle
0.0
static void area()
{
double result;
result=3.14*radius*radius;
[Link](result);
}
public static void main(String args[])
{
area();
}
}
9/11/2021 12:31:23 PM CSE 208 – Java Programming 13
static – variable – Example 2
class Circle public static void main(String args[])
{ {
static double radius; [Link](radius);
area();
static }
{ }
radius=5.0;
}
E:\slides\Java - 2021\Unit - I>java Circle
static void area() 5.0
{ 78.5
double result;
result=3.14*radius*radius;
[Link](result);
}
9/11/2021 12:31:23 PM CSE 208 – Java Programming 14
static – variable – Example 3
class Circle public static void main(String args[])
{ {
static double radius; [Link](radius);
area();
static }
{ static
radius=5.0; {
} radius=10.0;
}
static void area() }
{
double result;
result=3.14*radius*radius; E:\slides\Java - 2021\Unit - I>java Circle
[Link](result); 10.0
} 314.0
9/11/2021 12:31:23 PM CSE 208 – Java Programming 15
static – variable – Example 4
class Circle
{
static double radius; Limitation /Constraint
}
Class CircleDemo
{
public static void main(String args[])
{
[Link]([Link]);
}
} E:\slides\Java - 2021\Unit - I>java CircleDemo
0.0
9/11/2021 12:31:23 PM CSE 208 – Java Programming 16
Introducing Final
9/11/2021 12:31:23 PM CSE 208 – Java Programming 17
Normal Parameter
class Circle
{
static void get(int x)
{
x=15;
[Link](x);
}
public static void main(String args[])
{
get(5);
} E:\slides\Java - 2020\Unit - I>java Circle
} 15
9/11/2021 12:31:23 PM CSE 208 – Java Programming 18
Final Parameter
class Circle public static void main(String args[])
{ {
get(5);
static void get(final int x) }
{ }
x=15;
[Link](x);
}
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: final parameter x may not be
assigned
x=15;
^
1 error
9/11/2021 12:31:23 PM CSE 208 – Java Programming 19
Using Command-Line Arguments
9/11/2021 12:31:23 PM CSE 208 – Java Programming 20
Command-Line Arguments
Need
want to pass information into a program when you run it.
Accomplished
by passing command-line arguments to main( ).
A command-line argument
is the information that directly follows the program’s name
on the command line when it is executed.
9/11/2021 12:31:23 PM CSE 208 – Java Programming 21
Command-Line Arguments
To access the command-line arguments inside a Java
program
they are stored as strings
in a String array passed to the args parameter of main( ).
The first command-line argument is stored at args[0], the
second at args[1], and so on.
9/11/2021 12:31:23 PM CSE 208 – Java Programming 22
Command-Line Arguments – Example 1
class Cmd
{
public static void main(String args[])
{
for(int i=0;i<[Link];i++)
{
[Link](args[i]);
}
}
E:\slides\Java - 2020\Unit - I>java Cmd 1 2.3 a mani
}
1
2.3
a
mani
9/11/2021 12:31:23 PM CSE 208 – Java Programming 23
Command-Line Arguments – Example 2
class Cmd
{
public static void main(String args[])
{
[Link](args[0]+args[1]);
}
}
E:\slides\Java - 2020\Unit - I>java Cmd sastra university
sastrauniversity
E:\slides\Java - 2020\Unit - I>java Cmd sastra 123 456
sastra123
E:\slides\Java - 2020\Unit - I>java Cmd 1 2 3 4 5 6 7
12
9/11/2021 12:31:23 PM CSE 208 – Java Programming 24
Command-Line Arguments – Example 3
class cmd
{
public static void main(String args[])
{
String st="";
for(int i=0;i<[Link];i++)
{
st=st+args[i];
}
[Link](st);
}
} E:\slides\Java - 2020\Unit - I>java cmd 1 2 sas 3 tra
12sas3tra
9/11/2021 12:31:23 PM CSE 208 – Java Programming 25
Command-Line Arguments – Example 4
class Circle
{
public static void main(String args[])
{
int radius=[Link](args[0]);
double area=3.14*radius*radius;
[Link]("Circle Area:--->"+area);
}
}
E:\slides\Java - 2020\Unit - I>java Circle 5
Circle Area:--->78.5
9/11/2021 12:31:23 PM CSE 208 – Java Programming 26
Command-Line Arguments – Example 4
E:\slides\Java - 2020\Unit - I>java Circle 12.34
Exception in thread "main" [Link]: For input
string: “12.34"
at [Link](Unknown Source)
at [Link](Unknown Source)
at [Link](Unknown Source)
at [Link]([Link])
E:\slides\Java - 2020\Unit - I>java Circle 'a'
Exception in thread "main" [Link]: For input
string: “’a'"
at [Link](Unknown Source)
at [Link](Unknown Source)
at [Link](Unknown Source)
at [Link]([Link])
9/11/2021 12:31:23 PM CSE 208 – Java Programming 27
We have discussed:
Static
Method
Variable
Final Parameter
Command Line argument
9/11/2021 12:31:24 PM CSE 208 – Java Programming 28
Inheritance
9/11/2021 12:31:24 PM CSE 208 – Java Programming 29
[Link]
SAP / ICT / SOC
SASTRA
Inheritance Basics
Inheritance Types
Method Overriding
Using Super
9/14/2021 2:00:52 PM CSE 208 – Java Programming 2
Inheritance Basics
Using inheritance, you can create a general class that defines
traits common to a set of related items.
This class can then be inherited by other
more specific classes
each adding those things that are unique to it.
In Java,
A class that is inherited is called a superclass.
The class that does the inheriting is called a subclass.
A subclass is a specialized version of a superclass.
It inherits all of the members defined by the superclass and
adds its own, unique elements.
9/14/2021 2:00:52 PM CSE 208 – Java Programming 3
Inheritance Basics
¥ To inherit a class - Use extends keyword
¥ General Form:
class subclass-name extends superclass-name
{
// body of class Class circle extends shape
} {
}
class Shape{ }
Super class
Sub class
class circle{}
9/14/2021 2:00:52 PM CSE 208 – Java Programming 4
Single Inheritance
class Circle extends Shape
{
class Shape void computeArea()
{ {
double radius; double area=3.14* radius* radius;
[Link]("Circle Area:--->"+area);
Shape() }
{ public static void main(String args[])
radius=5.0; {
} Circle c1=new Circle();
} [Link]();
}
} E:\slides\Java - 2021\Unit - I>java Circle
Circle Area:--->78.5
9/14/2021 2:00:52 PM CSE 208 – Java Programming 5
Private Access Specifier
class Circle extends Shape
{
class Shape void computeArea()
{ {
private double radius; double area=3.14* radius* radius;
[Link]("Circle Area:--->"+area);
Shape() }
{ public static void main(String args[])
radius=5.0; {
} Circle c1=new Circle();
} [Link]();
}
}
9/14/2021 2:00:52 PM CSE 208 – Java Programming 6
Private Access Specifier
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: radius has private access in Shape
double area=3.14* radius* radius;
^
[Link]: error: radius has private access in Shape
double area=3.14* radius* radius;
^
2 errors
9/14/2021 2:00:52 PM CSE 208 – Java Programming 7
Hierarchical Inheritance
class Shape
{ class Shape{ }
double d1,d2;
Shape()
{
d1=2;d2=3; class square{} class rectangle{}
}
}
class Square extends Shape
{
void computeArea()
{
double area=d1*d1;
[Link]("Square Area:--->"+area);
}
}
9/14/2021 2:00:52 PM CSE 208 – Java Programming 8
Hierarchical Inheritance
class Rectangle extends Shape
{
void computeArea()
{
double area=d1*d2;
[Link]("Rectangle Area:--->"+area);
}
}
class shapedemo
{
public static void main(String args[])
{
Square s1=new Square(); E:\slides\Java - 2021\Unit - I>java shapedemo
[Link](); Square Area:--->4.0
Rectangle r1=new Rectangle(); Rectangle Area:--->6.0
[Link]();
}
}
9/14/2021 2:00:52 PM CSE 208 – Java Programming 9
Multilevel Inheritance
class shape
{ class Shape{ }
private double radius;
Shape()
{
radius=5.0; class Shape1{}
}
}
class shape1 extends shape
{ class Circle{}
void computeArea()
{
}
}
9/14/2021 2:00:52 PM CSE 208 – Java Programming 10
Multilevel Inheritance
class Circle extends Shape1
{
void computeArea()
{
double area=3.14* radius* radius;
[Link]("Circle Area:--->"+area);
}
public static void main(String args[])
{
Circle c1=new Circle();
[Link](); E:\slides\Java - 2021\Unit - I>java Circle
} Circle Area:--->78.5
}
9/14/2021 2:00:52 PM CSE 208 – Java Programming 11
When Constructors Are Executed
class One class Three extends Two
{ {
One() Three()
{ {
[Link]("Inside Class One); [Link]("Inside Class
} Three);
} }
class Two extends One }
{
Two() class Constructordemo
{ {
[Link]("Inside Class Two); public static void main(String args[])
} {
} Three T=new Three();
}
}
9/14/2021 2:00:52 PM CSE 208 – Java Programming 12
When Constructors Are Executed
E:\slides\Java - 2021\Unit - I>dir *.class
Volume in drive E is New Volume
Volume Serial Number is 8897-C289
Directory of E:\slides\Java - 2020\Unit - I
09/01/2020 12:26 PM 309 [Link]
09/01/2020 12:26 PM 367 [Link]
09/01/2020 12:26 PM 358 [Link]
09/01/2020 12:26 PM 354 [Link]
4 File(s) 1,388 bytes
0 Dir(s) 24,688,230,400 bytes free
E:\slides\Java - 2021\Unit - I>java Constructordemo
Inside Class One
Inside Class Two
Inside Class Three
9/14/2021 2:00:52 PM CSE 208 – Java Programming 13
9/14/2021 2:00:52 PM CSE 208 – Java Programming 14
Method Overriding
In a class hierarchy
when a method in a subclass has the same name and
type signature as a method in its superclass,
The method in the subclass is said to override the method
in the superclass.
When an overridden method is called from within its subclass,
it will always refer to the version of that method defined by the
subclass.
The version of the method defined by the superclass will be
hidden.
9/14/2021 2:00:52 PM CSE 208 – Java Programming 15
Method Overriding1
class Superclass class Subclass extends Superclass
{ {
int a; int b;
void show() void display()
{ {
a=555; b=666;
[Link]("Super:--->"+a); [Link]("Subclass:--->"+b);
} }
} }
class ridedemo
{
public static void main(String args[])
E:\slides\Java - 2021\Unit - I>java ridedemo
{
Super:--->555
Subclass s=new Subclass();
Subclass:--->666
[Link]();
[Link]();
}
}
9/14/2021 2:00:52 PM CSE 208 – Java Programming 16
Method Overriding 2
class Superclass class Subclass extends Superclass
{ {
int a; int b;
void show() void show()
{ {
a=555; b=666;
[Link]("Super:--->"+a); [Link]("Subclass:--->"+b);
} }
} }
class ridedemo
{
public static void main(String args[])
{
E:\slides\Java - 2021\Unit - I>java ridedemo
Subclass s=new Subclass();
Subclass:--->666
[Link]();
Subclass:--->666
[Link]();
}
}
9/14/2021 2:00:52 PM CSE 208 – Java Programming 17
Method Overriding 3
class Superclass class Subclass extends Superclass
{ {
int a;
int a; Subclass ()
Superclass () {
{ a=666;
a=555; }
} void show()
{
} [Link]("Subclass:--->"+a);
[Link]("Subclass:--->"+a);
class ridedemo }
{ }
public static void main(String args[])
{
Subclass s=new Subclass();
E:\slides\Java - 2021\Unit - I>java ridedemo
[Link]();
Subclass:--->666
}
Subclass:--->666
}
9/14/2021 2:00:53 PM CSE 208 – Java Programming 18
9/14/2021 2:00:53 PM CSE 208 – Java Programming 19
Super 1
class Superclass class Subclass extends Superclass
{ {
int a; int b;
void show() void show()
{ {
a=555; [Link]();
[Link]("Super:--->"+a); b=666;
} [Link]("Subclass:--->"+b);
} }
class ridedemo }
{
public static void main(String args[])
{
Subclass s=new Subclass(); E:\slides\Java - 2021\Unit - I>java ridedemo
[Link](); Super:--->555
Subclass:--->666
}
}
9/14/2021 2:00:53 PM CSE 208 – Java Programming 20
Super 2
class Superclass class Subclass extends Superclass
{ {
int a;
int a; Subclass ()
Superclass () {
{ a=666;
a=555; }
} void show()
{
} [Link]("Superclass:--->"+super.a);
[Link]("Subclass:--->"+a);
class ridedemo }
{ }
public static void main(String args[])
{
Subclass s=new Subclass(); E:\slides\Java - 2021\Unit - I>java ridedemo
[Link]();
Superclass:--->555
}
} Subclass:--->666
9/14/2021 2:00:53 PM CSE 208 – Java Programming 21
Super 3
Demo program
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: constructor Superclass in class
Superclass can
not be applied to given types;
{
^
required: int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
9/14/2021 2:00:53 PM CSE 208 – Java Programming 22
Super 3
E:\slides\Java - 2021\Unit - I>java ridedemo
Demo program - 1 Super:--->123
Subclass:--->456
E:\slides\Java - 2020\Unit - I>javac [Link]
[Link]: error: constructor Superclass in class Superclass can
not be applied to given types;
{
^
required: int
found: no arguments
reason: actual and formal argument lists differ in length
[Link]: error: call to super must be first statement in const
ructor
super(y);
^
2 errors
9/14/2021 2:00:53 PM CSE 208 – Java Programming 23
super - Summary
super keyword Can be used
To Call Superclass Constructors
To access Superclass instance variable
To access Superclass method
9/14/2021 2:00:53 PM CSE 208 – Java Programming 24
We have discussed:
Inheritance Basics
Inheritance Types
Method Overriding
Using Super
9/14/2021 2:00:53 PM CSE 208 – Java Programming 25
Inheritance
9/14/2021 2:00:53 PM CSE 208 – Java Programming 26
Review Question
In what order are the destructors for
the classes that make up the
hierarchy executed?
Give Your Answer in the Chat
Window
9/14/2021 2:00:53 PM CSE 208 – Java Programming 27
Inheritance - II
[Link]
SAP / ICT / SOC
SASTRA
final Keyword
Dynamic Method Dispatch
Using abstract classes
The Object class
9/15/2021 6:37:27 PM CSE 208 – Java Programming 2
Review Question - 1
Can a public class Myclass be defined in a source file named
[Link]?
public class myclass
{ [Link]
}
F:\java>javac [Link]
[Link]: error: class myclass is public, should be declared in a
file named [Link]
public class myclass
^
1 error
9/15/2021 6:37:27 PM CSE 208 – Java Programming 3
Review Question - 2
How to invoke the garbage collection mechanism from a
java program?
[Link]();
9/15/2021 6:37:27 PM CSE 208 – Java Programming 4
Review Question - 3
class demo extends String
{
public static void main(String args[])
{
[Link](“SASTRA University”);
}
}
[Link]: error: cannot inherit from final String
class demo extends String
^
1 error
9/15/2021 6:37:27 PM CSE 208 – Java Programming 5
9/15/2021 6:37:27 PM CSE 208 – Java Programming 6
final - Need
To Prevent Method Overriding
To prevent a class from being inherited
9/15/2021 6:37:27 PM CSE 208 – Java Programming 7
final - 1
final class Superclass class Subclass extends Superclass
{ {
int a; int b;
void show() void show()
{ {
a=555; b=666;
[Link]("Super:--->"+a); [Link]("Subclass:--->"+b);
} }
} }
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: cannot inherit from final Superclass
class Subclass extends Superclass
^
1 error
9/15/2021 6:37:27 PM CSE 208 – Java Programming 8
final - 1
class Superclass class Subclass extends Superclass
{ {
int a; int b;
final void show()
void show()
{
{
a=555;
b=666;
[Link]("Super:--->"+a); [Link]("Subclass:--->"+b);
} }
} }
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: show() in Subclass cannot override show() in Superclass
void show()
^
overridden method is final
1 error
9/15/2021 6:37:27 PM CSE 208 – Java Programming 9
final - Summary
final keyword Can be used
To create the equivalent of a named
constant
To Prevent Method Overriding
To prevent a class from being inherited
9/15/2021 6:37:27 PM CSE 208 – Java Programming 10
9/15/2021 6:37:27 PM CSE 208 – Java Programming 11
Dynamic Method Dispatch
Dynamic method dispatch
is the mechanism by which a call to an overridden method
is resolved at run time
rather than compile time.
Java implements run-time polymorphism using Dynamic
method dispatch.
principle: a superclass reference variable can refer to a
subclass object.
9/15/2021 6:37:27 PM CSE 208 – Java Programming 12
Dynamic Method Dispatch
When an overridden method is called through a superclass
reference
Java determines
which version of that method to execute
based upon the type of the object being referred
at the time the call occurs.
This determination is made at run time.
When different types of objects are referred to
different versions of an overridden method will be called.
9/15/2021 6:37:27 PM CSE 208 – Java Programming 13
Dynamic Method Dispatch
class Square extends Shape
class Shape {
{ void computeArea()
double d1,d2; {
double area=d1*d1;
[Link]("Square Area:--->"+area);
Shape() }
{ }
d1=2;d2=3;
} class Rectangle extends Shape
void computeArea() {
{ void computeArea()
} {
} double area=d1*d2;
[Link]("Rectangle Area:--->"+area);
}
}
9/15/2021 6:37:28 PM CSE 208 – Java Programming 14
Dynamic Method Dispatch
class shapedemo
{
public static void main(String args[])
{
int x=[Link](args[0]);
Shape s;
Square s1=new Square();
Rectangle r1=new Rectangle();
if(x==1)
{
s=s1;
[Link]();
}
else
{
s=r1;
[Link]();
} //if
} //main
}//class
9/15/2021 6:37:28 PM CSE 208 – Java Programming 15
Dynamic Method Dispatch
E:\slides\Java - 2021\Unit - I>java shapedemo 1
Square Area:--->4.0
E:\slides\Java - 2021\Unit - I>java shapedemo 2
Rectangle Area:--->6.0
E:\slides\Java - 2021\Unit - I>java shapedemo 3
Rectangle Area:--->6.0
E:\slides\Java - 2021\Unit - I>java shapedemo a
Exception in thread "main" [Link]: For input string: "a
"
at [Link](Unknown Source)
at [Link](Unknown Source)
at [Link](Unknown Source)
at [Link]([Link])
E:\slides\Java - 2021\Unit - I>
9/15/2021 6:37:28 PM CSE 208 – Java Programming 16
Dynamic Method Dispatch
class Parent
{ class Demo
void display() {
{
[Link]("Inside Super Class");
public static void main(String args[])
} {
} Parent p;
Child c=new Child();
class Child extends Parent p=c;
{
void display()
[Link]();
{ //[Link]();
[Link]("Inside Sub Class"); }
} }
void show()
{
[Link]("Subclass Method");
}
}
9/15/2021 6:37:28 PM CSE 208 – Java Programming 17
Dynamic Method Dispatch
E:\slides\Java - 2021\Unit - I>java Demo
Inside Sub Class
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: cannot find symbol
[Link]();
^
symbol: method show()
location: variable p of type Parent
1 error
9/15/2021 6:37:28 PM CSE 208 – Java Programming 18
9/15/2021 6:37:28 PM CSE 208 – Java Programming 19
Abstract Classes
Need to define a superclass that declares the structure of a
given abstraction without providing a complete implementation
of every method.
create a superclass that only defines a generalized form that
will be shared by all of its subclasses, leaving it to each
subclass to fill in the details
Ensure that a subclass does, indeed, override all necessary
methods.
Java’s solution to this problem is the abstract method.
General Form:
abstract type name(parameter-list);
9/15/2021 6:37:28 PM CSE 208 – Java Programming 20
Abstract Classes
Any class that contains one or more abstract methods must
also be declared abstract.
To declare a class abstract
use the abstract keyword in front of the class keyword at
the beginning of the class declaration.
There can be no objects of an abstract class.
An abstract class cannot be directly instantiated with the new
operator.
9/15/2021 6:37:28 PM CSE 208 – Java Programming 21
Abstract Classes
Such objects would be useless, because an abstract class
is not fully defined.
Cannot declare abstract
Constructors
Static methods.
Any subclass of an abstract class
must either implement all of the abstract methods in the
superclass, or be declared abstract itself.
9/15/2021 6:37:28 PM CSE 208 – Java Programming 22
Abstract Classes
abstract class Parent class Demo
{ {
abstract void display(); public static void main(String args[])
} {
Child1 c1=new Child1();
class Child1 extends Parent [Link]();
{ Child2 c2=new Child2();
void display() [Link]();
{ }
[Link]("SASTRA"); }
}
}
E:\slides\Java - 2021\Unit - I>javac [Link]
class Child2 extends Parent
{ E:\slides\Java - 2021\Unit - I>java Demo
void display() SASTRA
{ int a=10; 10
[Link](a);
}
}
9/15/2021 6:37:28 PM CSE 208 – Java Programming 23
Abstract Classes
abstract class Parent class Demo
{ {
abstract void display(); public static void main(String args[])
} {
class Child1 extends Parent Child1 c1=new Child1();
{ c1.display1();
void display1() }
{ }
[Link]("SASTRA");
}
} E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: Child1 is not abstract and does not override abstract
method display() in Parent
class Child1 extends Parent
^
1 error
9/15/2021 6:37:28 PM CSE 208 – Java Programming 24
Abstract Classes
abstract class Parent class Demo
{ {
abstract void display(); public static void main(String args[])
abstract void show(); {
} Child1 c1=new Child1();
class Child1 extends Parent [Link]();
{ }
void display() }
{
[Link]("SASTRA");
}
} E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: Child1 is not abstract and does not override
abstract method show() in Parent
class Child1 extends Parent
^
1 error
9/15/2021 6:37:28 PM CSE 208 – Java Programming 25
Abstract Classes
class Parent class Demo
{ {
abstract void display(); public static void main(String args[])
} {
class Child1 extends Parent Child1 c1=new Child1();
{ [Link]();
void display() }
{ }
[Link]("SASTRA");
}
}
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: Parent is not abstract and does not override abstract
method display() in Parent
class Parent
^
1 error
9/15/2021 6:37:28 PM CSE 208 – Java Programming 26
Abstract Classes
abstract class Parent class Demo
{ {
abstract void display(); public static void main(String args[])
} {
class Child1 extends Parent Parent P=new Parent();
{ Child1 c1=new Child1();
void display() [Link]();
{ }
[Link]("SASTRA"); }
}
}
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: Parent is abstract; cannot be instantiated
Parent P=new Parent();
^
1 error
9/15/2021 6:37:28 PM CSE 208 – Java Programming 27
Abstract Classes
class Parent class Demo
{ {
void display(); public static void main(String args[])
} {
class Child1 extends Parent Child1 c1=new Child1();
{ [Link]();
void display() }
{ }
[Link]("SASTRA");
}
}
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: missing method body, or declare abstract
void display();
^
1 error
9/15/2021 6:37:28 PM CSE 208 – Java Programming 28
9/15/2021 6:37:28 PM CSE 208 – Java Programming 29
The Object Class
One special class defined by Java - Object.
All other classes are subclasses of Object.
Object is a superclass of all other classes.
This means that a reference variable of type Object can refer
to an object of any other class.
Arrays are implemented as classes,
a variable of type Object can also refer to any array.
9/15/2021 6:37:28 PM CSE 208 – Java Programming 30
The Object Class
9/15/2021 6:37:28 PM CSE 208 – Java Programming 31
The Object Class
¥ The methods getClass( ), notify( ), notifyAll( ), and wait( ) are
declared as final.
¥ Override the others.
¥ The equals( ) method compares two objects.
¥ It returns true if the objects are equal, and false otherwise.
¥ The toString( ) method returns a string that contains a description
of the object on which it is called.
¥ Also, this method is automatically called when an object is
output using println().
9/15/2021 6:37:28 PM CSE 208 – Java Programming 32
The Object Class
class ObjectClass
{
public static void main(String args[])
{
ObjectClass ob = new ObjectClass();
[Link](ob);
}
} E:\slides\Java - 2021\Unit - I>javac [Link]
E:\slides\Java - 2021\Unit - I>java ObjectClass
ObjectClass@15db9742
9/15/2021 6:37:28 PM CSE 208 – Java Programming 33
The Object Class
class ObjectClass
{
public String toString()
{
return ("Object Class Description");
}
public static void main(String args[])
{
ObjectClass ob=new ObjectClass();
[Link](ob);
} E:\slides\Java - 2021\Unit - I>javac [Link]
}
E:\slides\Java - 2021\Unit - I>java ObjectClass
Object Class Description
9/15/2021 6:37:28 PM CSE 208 – Java Programming 34
The Object Class
class ObjectClass
{
public static void main(String args[])
{
ObjectClass ob= new ObjectClass();
ObjectClass ob1=new ObjectClass();
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
} E:\slides\Java - 2021\Unit - I>javac [Link]
E:\slides\Java - 2021\Unit - I>java ObjectClass
366712642
1829164700
class ObjectClass
9/15/2021 6:37:28 PM CSE 208 – Java Programming 35
We have discussed:
final keyword
Run Time Polymorphism
Use of abstract keyword
Object Class
9/15/2021 6:37:28 PM CSE 208 – Java Programming 36
Interface
9/15/2021 6:37:29 PM CSE 208 – Java Programming 37
[Link]
SAP / ICT / SOC
SASTRA
Interface Basics
Defining an Interface
Implementing Interfaces
Partial Implementations
Interfaces Can Be Extended
9/17/2021 3:18:29 PM CSE 208 – Java Programming 2
Review Question - 1
public void d2(int x){
x *= 2;
[Link](x);
}
What is output by the code to
the right when method d1 is
called? public void d1(){
int x = 3;
A. 322 [Link](x);
B. 323 d2(x);
[Link](x);
C. 363
}
D. 366
E. 399
9/17/2021 3:18:29 PM CSE 208 – Java Programming 3
Interfaces - Basics
Interfaces are syntactically similar to classes
but they lack instance variables
their methods are declared without any body.
Once it is defined,
any number of classes can implement an interface
one class can implement any number of interfaces.
9/17/2021 3:18:29 PM CSE 208 – Java Programming 4
Interfaces - Basics
To implement an interface,
a class must provide the complete set of methods required
by the interface.
Each class is free to determine the details of its own
implementation.
By providing the interface keyword,
Java allows you to fully utilize the “one interface,
multiple methods” aspect of polymorphism.
9/17/2021 3:18:29 PM CSE 208 – Java Programming 5
General form of an interface
9/17/2021 3:18:30 PM CSE 208 – Java Programming 6
Defining an Interface
When no access modifier is included
then default access results,
the interface is only available to other members of the
package in which it is declared.
When it is declared as public,
the interface can be used by code outside its package.
the interface must be the only public interface declared in
the file
the file must have the same name as the [Link]
can be any valid identifier.
9/17/2021 3:18:30 PM CSE 208 – Java Programming 7
Defining an Interface
The methods that are declared inside interface have no
bodies.
They end with a semicolon after the parameter list.
They are, essentially, abstract methods.
Each class that includes such an interface must implement all
of the methods.
JDK 8
possible to add a default implementation to an interface
method
static interface methods
JDK 9
an interface can include private methods
9/17/2021 3:18:30 PM CSE 208 – Java Programming 8
Defining an Interface
As the general form shows,
variables can be declared inside interface declarations.
They are implicitly final and static
meaning they cannot be changed by the implementing
class.
They must also be initialized.
All methods and variables are implicitly public.
interface shape
{
double radius=5.0;
void area();
}
9/17/2021 3:18:30 PM CSE 208 – Java Programming 9
Implementing Interfaces
¥ To implement an interface,
¥ include the implements clause in a class definition,
¥ then create the methods required by the interface.
9/17/2021 3:18:30 PM CSE 208 – Java Programming 10
Implementing Interfaces
¥ If a class implements more than one interface,
¥ the interfaces are separated with a comma
¥ The methods that implement an interface must be declared
public.
¥ The type signature of the implementing method must match
exactly the type signature specified in the interface definition.
¥ It is permissible for classes that implement interfaces to define
additional members of their own.
9/17/2021 3:18:30 PM CSE 208 – Java Programming 11
Example 1
public static void main(String args[])
interface Shape
{
{
Circle obj=new Circle();
double radius=5.0;
[Link]();
void area();
[Link]();
}
}
}
class Circle implements Shape
{
double result;
E:\slides\Java - 2021\Unit - I>java Circle
public void area() Circle Area:---->78.5
{
result = 3.14* radius* radius;
}
void display()
{
[Link]("Circle Area:---->"+result);
}
9/17/2021 3:18:30 PM CSE 208 – Java Programming 12
Example 2
public void area()
interface Shape {
{ result = d1* d1;
double d1=5.0; }
void area(); }
} class idemo
{
class Circle implements Shape public static void main(String args[])
{ {
double result; Circle obj=new Circle(); // creating object
public void area() [Link]();
{ [Link]("Circle Area---->"+[Link]);
result = 3.14* d1* d1;
} Square sobj=new Square(); // creating object
} [Link]();
[Link]("Square Area---->"+[Link]);
class Square implements Shape }
{ }
double result;
9/17/2021 3:18:30 PM CSE 208 – Java Programming 13
Example 2
E:\slides\Java - 2021\Unit - I>javac [Link]
E:\slides\Java - 2021\Unit - I>dir *.class
Volume in drive E is New Volume
Volume Serial Number is 14EA-A7F4
Directory of E:\slides\Java - 2021\Unit - I
04-09-2020 12:02 303 [Link]
04-09-2020 12:02 812 [Link]
04-09-2020 12:02 170 [Link]
04-09-2020 12:02 100 [Link]
04-09-2020 12:02 303 [Link]
5 File(s) 1,688 bytes
0 Dir(s) 104,534,536,192 bytes free
E:\slides\Java - 2021\Unit - I>java idemo
Circle Area---->78.5
Square Area---->25.0
9/17/2021 3:18:30 PM CSE 208 – Java Programming 14
Example 3
interface Shape void display()
{ {
double radius=5.0; [Link]("Circle Area:---->"+result);
} }
interface Shape1 public static void main(String args[])
{ {
void area(); Circle obj=new Circle(); // creating object
} [Link]();
class Circle implements Shape,Shape1 [Link]();
{ }
double result; }
public void area()
E:\slides\Java - 2021\Unit - I>javac [Link]
{
E:\slides\Java - 2021\Unit - I>java Circle
result = 3.14* radius* radius;
Circle Area:---->78.5
}
9/17/2021 3:18:30 PM CSE 208 – Java Programming 15
Example 4
interface Shape
{
double d1;
void area();
}
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: = expected
double d1;
^
1 error
9/17/2021 3:18:30 PM CSE 208 – Java Programming 16
Example 5
interface Shape class Circle implements Shape
{ {
double d1=5.0; double result;
void area(); void area()
} {
result = 3.14* d1* d1;
}
}
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: area() in Circle cannot implement area() in Shape
void area()
^
attempting to assign weaker access privileges; was public
1 error
9/17/2021 3:18:30 PM CSE 208 – Java Programming 17
Example 6
interface Shape class Circle implements Shape
{ {
double d1=5.0; double result;
void area(); public void area()
void show(); {
} result = 3.14* d1* d1;
}
}
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: Circle is not abstract and does not override abstract method
show() in Shape
class Circle implements Shape
^
9/17/2021 3:18:30 PM CSE 208 – Java Programming 18
Example 7
interface Shape class Circle implements Shape
{ {
double d1=5.0; double result;
void area(); public void area()
} {
d1=6.0;
result = 3.14* d1* d1;
}
}
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: cannot assign a value to final variable d1
d1=6.0;
^
1 error
9/17/2021 3:18:30 PM CSE 208 – Java Programming 19
Example 8
class idemo implements Shape
interface Shape {
{ public static void main(String args[])
int x=50; {
[Link]("Integer value---->"+x);
boolean flag=false; [Link]("Double value---->"+d1);
double d1=5.0; [Link]("Boolean value---->"+flag);
String s="SASTRA"; [Link]("String value---->"+s);
} }
}
E:\slides\Java - 2021\Unit - I>java idemo
Integer value---->50
Double value---->5.0
Boolean value---->false
String value---->SASTRA
9/17/2021 3:18:30 PM CSE 208 – Java Programming 20
Example 9
class Circle extends Figure implements Shape
interface Shape {
{ double result;
public void area()
void area(); {
} result = 3.14* radius* radius;
[Link]("Circle Area:---->"+result);
class Figure }
{ public static void main(String args[])
{
double radius; Circle ob=new Circle();
} [Link]();
}
}
E:\slides\Java - 2021\Unit - I>java Circle
Circle Area:---->0.0
9/17/2021 3:18:30 PM CSE 208 – Java Programming 21
Example 10
class Circle implements Shape extends Figure
interface Shape {
double result;
{ public void area()
void area(); {
} result = 3.14* radius* radius;
[Link]("Circle Area:---->"+result);
class Figure }
public static void main(String args[])
{ {
double radius; Circle ob=new Circle();
} [Link]();
}
} E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: '{' expected
class Circle implements Shape extends Figure
^
1 error
9/17/2021 3:18:30 PM CSE 208 – Java Programming 22
Interfaces Can Be Extended
¥ One interface can inherit another by use of the keyword
extends.
¥ The syntax is the same as for inheriting classes.
¥ When a class implements
¥ an interface that inherits another interface
¥ it must provide implementations for all methods required by
the interface inheritance chain.
9/17/2021 3:18:30 PM CSE 208 – Java Programming 23
Example 11
interface Shape class Circle implements Shape1
{ {
double result;
void area(); public void area()
} {
interface Shape1 extends Shape result = 3.14* radius* radius;
{ [Link]("Circle Area:---->"+result);
double radius=5; }
public static void main(String args[])
} {
Circle ob=new Circle();
[Link]();
}
}
E:\slides\Java - 2021\Unit - I>java Circle
Circle Area:---->78.5
9/17/2021 3:18:30 PM CSE 208 – Java Programming 24
We have discussed how to:
Define an Interface
Create a program - Implements Interfaces
Make use of Partial Implementations
Extended an interface
9/17/2021 3:18:30 PM CSE 208 – Java Programming 25
Interface
9/17/2021 3:18:31 PM CSE 208 – Java Programming 26
[Link]
SAP / ICT / SOC
SASTRA
Default Interface Methods
Multiple Inheritance Issues
Use static Methods in an Interface
9/18/2021 10:59:21 AM CSE 208 – Java Programming 2
Review Question - 1
Name the parent class of all the classes in java.
9/18/2021 10:59:22 AM CSE 208 – Java Programming 3
Review Question - 2
Can we have a class prefixed with both final
and abstract keywords. Justify your answer.
9/18/2021 10:59:22 AM CSE 208 – Java Programming 4
Review Question - 3
Check the following code for errors. If there is no error then,
predict the output.
class test extends Object
{
public static void main(String args[])
{
[Link](“SASTRA”);
}
}
9/18/2021 10:59:22 AM CSE 208 – Java Programming 5
Default Interface Methods
Prior to JDK 8
An interface could not define any implementation.
All previous versions of Java
the methods specified by an interface were abstract
containing no body.
JDK 8
changed this by adding a new capability to interface
called the default method.
A default method lets you define a default implementation
for an interface method.
9/18/2021 10:59:22 AM CSE 208 – Java Programming 6
Default Interface
Methods
9/18/2021 10:59:22 AM CSE 208 – Java Programming 7
Default Interface Methods
By use of a default method
it is possible for an interface method to provide a body,
rather than being abstract.
The default method was also referred to as an extension
method
A primary motivation
for the default method was to provide a means by which
interfaces could be expanded without breaking existing
code.
if a new method were added to a widely used interface
then the addition of that method would break existing code
because no implementation would be found for that new
method
9/18/2021 10:59:22 AM CSE 208 – Java Programming 8
Example - 1
class Circle implements Shape
interface Shape {
{ double result;
public void area()
double radius=5; {
void area(); result=3.14*radius*radius;
default void show() [Link]("Circle Area:---->"+result);
{ }
[Link]("To public static void main(String args[])
{
Display the result"); Circle ob=new Circle();
} [Link]();
} [Link]();
}
}
E:\slides\Java - 2021\Unit - I>javac interface_default.java
E:\slides\Java - 2021\Unit - I>java Circle
Circle Area:---->78.5
To Display the result
9/18/2021 10:59:22 AM CSE 208 – Java Programming 9
Example - 2
interface Shape
{ public void show()
double radius=5; {
void area(); [Link]("Circle Area:---->"+result);
default void show() }
{ public static void main(String args[])
System .[Link]("To Display the result"); {
} Circle ob=new Circle();
} [Link]();
class Circle implements Shape [Link]();
{ }
double result; }
public void area()
{
result=3.14*radius*radius;
} E:\slides\Java - 2021\Unit - I>java Circle
Circle Area:---->78.5
9/18/2021 10:59:22 AM CSE 208 – Java Programming 10
Multiple
Inheritance Issues
9/18/2021 10:59:22 AM CSE 208 – Java Programming 11
Multiple Inheritance Issues
Assume that two interfaces called Shape and Shape1 are
implemented by a class called Circle.
What happens if both Shape and Shape1 provide a method
called area() for which both declare a default
implementation?
Is the version by Shape or the version by Shape1 used by
Circle.?
9/18/2021 10:59:22 AM CSE 208 – Java Programming 12
Multiple Inheritance Issues
Consider a situation in which Shape1 extends Shape.
Which version of the default method is used?
What if Circle class provides its own implementation of the
method?
To handle these and other similar types of situations
Java defines a set of rules that resolves such conflicts.
9/18/2021 10:59:22 AM CSE 208 – Java Programming 13
Multiple Inheritance Issues - 1
interface Shape class Circle implements Shape,Shape1
{ {
default void area() public void area()
{ {
[Link]("Inside shape "); double radius=5.0;
} double result=3.14*radius*radius;
} [Link]("Circle Area:---->"+result);
}
interface Shape1 public static void main(String args[])
{ {
default void area() Circle ob=new Circle();
{ [Link]();
[Link]("Inside shape 1"); }
} }
}
E:\slides\Java - 2021\Unit - I>java Circle
Circle Area:---->78.5
9/18/2021 10:59:22 AM CSE 208 – Java Programming 14
Multiple Inheritance Issues - 2
interface Shape class Circle implements Shape,Shape1
{ {
default void area() public static void main(String args[])
{ {
[Link]("Inside shape "); Circle ob=new Circle();
} [Link]();
} }
interface Shape1 }
{
default void area()
{
[Link]("Inside shape 1");
}
} E:\slides\Java - 2021\Unit - I>javac interface_default2.java
interface_default2.java:15: error: class Circle inherits unrelated defaults for
area() from types Shape and Shape1
class Circle implements Shape,Shape1
^
1 error
9/18/2021 10:59:22 AM CSE 208 – Java Programming 15
Multiple Inheritance Issues - 3
interface Shape class Circle implements Shape1
{ {
default void area() double result;
{ public static void main(String args[])
[Link]("Inside shape "); {
} Circle ob=new Circle();
} [Link]();
}
interface Shape1 extends Shape }
{
default void area()
{
[Link]("Inside shape 1");
}
}
E:\slides\Java - 2021\Unit - I>javac interface_default2.java
E:\slides\Java - 2021\Unit - I>java Circle
Inside shape 1
9/18/2021 10:59:22 AM CSE 208 – Java Programming 16
Multiple Inheritance Issues - 4
interface Shape class Circle implements Shape1
{ {
default void area() double result;
{ public static void main(String args[])
[Link]("Inside shape "); {
} Circle ob=new Circle();
} [Link]();
}
interface Shape1 extends Shape }
{
default void area()
{
[Link]();
[Link]("Inside shape 1"); E:\slides\Java - 2021\Unit - I>java Circle
} Inside shape
} Inside shape 1
9/18/2021 10:59:22 AM CSE 208 – Java Programming 17
Use static Methods
in an
Interface
9/18/2021 10:59:22 AM CSE 208 – Java Programming 18
Static Methods in an Interface
JDK 8
Define one or more static methods – interface
A static method defined by an interface can be called
independently of any object.
No implementation of the interface is necessary
No instance of the interface is required, in order to call a
static method.
9/18/2021 10:59:22 AM CSE 208 – Java Programming 19
Static Methods in an Interface
JDK 8
A static method is called by
specifying the interface name
followed by a period
followed by the method name.
General Form:
[Link]
¥ static interface methods are not inherited by either an
implementing class or a subinterface.
9/18/2021 10:59:23 AM CSE 208 – Java Programming 20
Example - 1
interface Shape
{
static void show()
{
System .[Link]("Static Method in Interface");
}
}
class Circle
{
public static void main(String args[])
{
[Link](); E:\slides\Java - 2021\Unit - I>javac interface_static.java
}
} E:\slides\Java - 2021\Unit - I>java Circle
Static Method in Interface
9/18/2021 10:59:23 AM CSE 208 – Java Programming 21
Example - 2
interface Shape
{
static void show()
{
[Link]("Static Method in Interface");
}
}
class Circle implements Shape
{
public static void main(String args[])
{
Circle ob=new Circle();
[Link](); E:\slides\Java - 2021\Unit - I>javac interface_static.java
} interface_static.java:13: error: cannot find symbol
} [Link]();
^
symbol: method show()
location: variable ob of type Circle
1 error
9/18/2021 10:59:23 AM CSE 208 – Java Programming 22
We have discussed:
Default Interface Methods
Multiple Inheritance Issues
Use static Methods in an Interface
9/18/2021 10:59:23 AM CSE 208 – Java Programming 23
Packages
9/18/2021 10:59:23 AM CSE 208 – Java Programming 24
9/18/2021 10:59:23 AM CSE 208 – Java Programming 25
[Link]
SAP / ICT / SOC
SASTRA
Predefined packages
Need for a Package
Create a Package
Use the Package
9/21/2021 4:36:44 PM CSE 208 – Java Programming 2
Review Question - 1
class demo implements shape
interface shape {
{ public void show()
{
int show(); [Link]("SASTRA University");
}
} public static void main(String args[])
{
demo d=new demo();
[Link]();
}}
F:\java>javac [Link]
[Link]: error: demo is not abstract and does not override abstract method show() in
shape
class demo implements shape
^
[Link]: error: show() in demo cannot implement show() in shape
public void show()
^
return type void is not compatible with int
2 errors
9/21/2021 4:36:44 PM CSE 208 – Java Programming 3
Review Question - 2
interface shape class demo implements shape
{ {
public void show()
default void show()
{
{ [Link]("SASTRA");
[Link]("ICT Dept"); }
public static void main(String args[])
}
{
void show(); demo d=new demo();
} [Link]();
}
}
F:\java>javac [Link]
[Link]: error: method show() is already defined in interface shape
void show();
^
1 error
9/21/2021 4:36:44 PM CSE 208 – Java Programming 4
Review Question - 3
interface shape class demo implements shape
{ {
public static void main(String args[])
default void show()
{
{ [Link]();
[Link]("ICT Dept"); }
}
}
static void show();
{ F:\java>javac [Link]
[Link]("SASTRA"); [Link]: error: method show()
is already defined in interface shape
} default void show()
} ^
1 error
9/21/2021 4:36:44 PM CSE 208 – Java Programming 5
Types
9/21/2021 4:36:44 PM CSE 208 – Java Programming 6
PreDefined Packages
9/21/2021 4:36:44 PM CSE 208 – Java Programming 7
Need
9/21/2021 4:36:44 PM CSE 208 – Java Programming 8
Package - Basics
Packages are containers for classes.
They are used to keep the class name space
compartmentalized.
For example, a package allows you to create a class named
Circle, which you can store in your own package without
concern that it will collide with some other class named Circle
stored elsewhere.
Packages are stored in a hierarchical manner
9/21/2021 4:36:45 PM CSE 208 – Java Programming 9
Package - Basics
The package is both a naming and a visibility control
mechanism.
Define classes inside a package that are not accessible by
code outside that package.
They are explicitly imported into new class definitions.
9/21/2021 4:36:45 PM CSE 208 – Java Programming 10
Package - Definition
To create a package
simply include a package command as the first statement
in a Java source file.
Any classes declared within that file will belong to the
specified package.
The package statement defines a name space in which
classes are stored.
If you omit the package statement
the class names are put into the default package
which has no name.
9/21/2021 4:36:45 PM CSE 208 – Java Programming 11
Package
General Form of the package statement:
package pkg;
pkg is the name of the package.
For example,
the following statement creates a package called Shapes.
package shapes;
Java uses file system directories to store packages
¥ the .class files for any classes you declare to be part of
shapes must be stored in a directory called shapes.
9/21/2021 4:36:45 PM CSE 208 – Java Programming 12
Package
General form - multileveled package statement:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of
your Java development system
Example:
package a.b.c;
needs to be stored in a\b\c in a Windows environment
case is significant, and the directory name must match the
package name exactly.
9/21/2021 4:36:45 PM CSE 208 – Java Programming 13
Finding Packages and CLASSPATH
How does the Java run-time system know where to look for
packages that you create?
First, by default,
the Java run-time system uses the current working directory as its
starting point.
if your package is in a subdirectory of the current directory, it will be
found
Second,
you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
Third,
you can use the -classpath option with java and javac to specify the
path to your classes
9/21/2021 4:36:45 PM CSE 208 – Java Programming 14
Importing Packages
¥ Java includes the import statement to bring certain classes, or
entire packages, into visibility.
¥ Once imported
¥ a class can be referred to directly, using only its name
¥ In a Java source file,
¥ import statements occur immediately following the
package statement (if it exists) and before any class
definitions.
¥ general form of the import statement:
¥ import pkg1 [.pkg2].(classname | *);
9/21/2021 4:36:45 PM CSE 208 – Java Programming 15
Importing Packages
import [Link];
import [Link].*;
basic language functions are stored in a package called
[Link].
implicitly imported by the compiler for all programs
import [Link].*;
class MyDate extends Date {}
class MyDate extends [Link] { }
9/21/2021 4:36:45 PM CSE 208 – Java Programming 16
Example - 1
**********
sastra
**********
9/21/2021 4:36:45 PM CSE 208 – Java Programming 17
Example - 1
[Link]
package pkg;
public class design
{
public void star()
{
for(int i=0;i<10;i++)
{
[Link]("*");
}
}
}
9/21/2021 4:36:45 PM CSE 208 – Java Programming 18
Example - 1
E:\slides\Java - 2021\Unit - I>
E:\slides\Java - 2021\Unit - I>md pkg
E:\slides\Java - 2021\Unit - I>cd pkg
E:\slides\Java - 2021\Unit - I\pkg>dir
Volume in drive E is New Volume
Volume Serial Number is 8897-C289
Directory of E:\slides\Java - 2021\Unit - I\pkg
09/08/2020 03:57 PM <DIR> .
09/08/2020 03:57 PM <DIR> ..
03/28/2018 04:49 PM 91 [Link]
1 File(s) 91 bytes
2 Dir(s) 24,617,558,016 bytes free
9/21/2021 4:36:45 PM CSE 208 – Java Programming 19
Example - 1
E:\slides\Java - 2021\Unit - I\pkg>javac [Link]
E:\slides\Java - 2021\Unit - I\pkg>dir
Volume in drive E is New Volume
Volume Serial Number is 8897-C289
Directory of E:\slides\Java - 2020\Unit - I\pkg
09/08/2020 04:05 PM <DIR> .
09/08/2020 04:05 PM <DIR> ..
09/08/2020 04:05 PM 384 [Link]
03/28/2018 04:49 PM 91 [Link]
2 File(s) 475 bytes
2 Dir(s) 24,617,558,016 bytes free
9/21/2021 4:36:45 PM CSE 208 – Java Programming 20
Example - 1
[Link]
import pkg.*;
class packdemo
{
public static void main(String args[])
{
design d=new design();
[Link]();
[Link]("\n sastra");
[Link]();
} E:\slides\Java - 2021\Unit - I>javac [Link]
} E:\slides\Java - 2021\Unit - I>java packdemo
**********
sastra
**********
9/21/2021 4:36:45 PM CSE 208 – Java Programming 21
Example - 2
package pkg; import pkg.*;
public class design class packdemo
{ {
void star() public static void main(String args[])
{ {
for(int i=0;i<10;i++) design d=new design();
{ [Link]();
[Link]("*"); [Link]("\n sastra");
} [Link]();
} }
} }
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: star() is not public in design; cannot be accessed from outside package
[Link]();
^
[Link]: error: star() is not public in design; cannot be accessed from outside package
[Link]();
^
2 errors
9/21/2021 4:36:45 PM CSE 208 – Java Programming 22
We have discussed how to:
Define a package
Import a package
9/21/2021 4:36:45 PM CSE 208 – Java Programming 23
Package
9/21/2021 4:36:46 PM CSE 208 – Java Programming 24
[Link]
SAP / ICT / SOC
SASTRA
Access Specifiers
9/22/2021 6:21:12 PM CSE 208 – Java Programming 2
Example - 3
package pkg; public class design1
{
public class design void hash()
{ {
void star() for(int i=0;i<10;i++)
{ {
for(int i=0;i<10;i++) [Link]("#");
{ }
[Link]("*"); }
} }
}
}
9/22/2021 6:21:12 PM CSE 208 – Java Programming 3
Example - 3
E:\slides\Java - 2021\Unit - I\pkg>javac [Link]
[Link]: error: class design1 is public, should be declared in a file
named [Link]
public class design1
^
1 error
9/22/2021 6:21:12 PM CSE 208 – Java Programming 4
Solution
[Link] [Link]
package pkg; package pkg;
public class design public class design1
{ {
void star() void hash()
{ {
for(int i=0;i<10;i++) for(int i=0;i<10;i++)
{ {
[Link]("*"); [Link]("#");
} }
} }
} }
9/22/2021 6:21:12 PM CSE 208 – Java Programming 5
Example - 4
[Link]
import pkg.*;
class packdemo
{
public static void main(String args[])
{
design d=new design();
design1 d1=new design1();
[Link]();
[Link]("\n sastra");
[Link]();
} E:\slides\Java - 2021\Unit - I>java packdemo
} **********
sastra
##########
9/22/2021 6:21:12 PM CSE 208 – Java Programming 6
Example - 4
package pkg; package pkg1;
public class design public class design
{ {
public void star() public void star()
{ {
for(int i=0;i<10;i++) for(int i=0;i<10;i++)
{ {
[Link]("*"); [Link]("*");
} }
} }
} }
9/22/2021 6:21:12 PM CSE 208 – Java Programming 7
Example - 4
import pkg.*;
import pkg1.*;
class packdemo
{
public static void main(String args[])
{
design d=new design();
[Link]();
[Link]("\n sastra");
[Link]();
}
}
9/22/2021 6:21:12 PM CSE 208 – Java Programming 8
Example - 4
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: cannot access design
design d=new design();
^
bad class file: .\pkg1\[Link] lass file contains wrong class: [Link]
Please remove or make sure it appears in the correct subdirectory of the classpath.
1 error
9/22/2021 6:21:12 PM CSE 208 – Java Programming 9
Example - 4
import pkg.*; E:\slides\Java - 2021\Unit - I>javac [Link]
import pkg1.*; E:\slides\Java - 2021\Unit - I>java packdemo
**********
sastra
class packdemo **********
{
public static void main(String args[])
{
[Link] d=new [Link]();
[Link]();
[Link]("\n sastra");
[Link]();
}
}
9/22/2021 6:21:12 PM CSE 208 – Java Programming 10
Example - 4
import pkg.*; E:\slides\Java - 2021\Unit - I>javac [Link]
import pkg1.*; E:\slides\Java - 2021\Unit - I>java packdemo
**********
sastra
class packdemo **********
{
public static void main(String args[])
{
[Link] d=new [Link]();
[Link] d1=new [Link]();
[Link]();
[Link]("\n sastra");
[Link]();
}
}
9/22/2021 6:21:12 PM CSE 208 – Java Programming 11
9/22/2021 6:21:13 PM CSE 208 – Java Programming 12
Access Specifiers
Default
Private
Protected
Public
9/22/2021 6:21:13 PM CSE 208 – Java Programming 13
[Link] Example
public class protection
{ public static void main(String args[])
int n=1; {
private int a=2; protection p=new protection();
protected int b=3; [Link]();
public int c=4; }
}
void protectionshow() E:\slides\Java - 2021\Unit - I>java protection
{ Output from protection class
[Link]("Output from 1
2
protection class");
3
[Link](n); 4
[Link](a);
[Link](b);
[Link](c);
}
9/22/2021 6:21:13 PM CSE 208 – Java Programming 14
Access Specifiers
E:\slides\Java - 2021\Unit - I>java demo123
Output from protection class
1
2
3
4 Program 1
Output from derived class
1
3
4
Output from samepackage class
1
3
4
9/22/2021 6:21:13 PM CSE 208 – Java Programming 15
Program output
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: a has private access in protection
[Link](a);
^
[Link]: error: a has private access in protection
[Link](p.a);
^
2 errors
9/22/2021 6:21:13 PM CSE 208 – Java Programming 16
Access Specifiers
E:\slides\Java - 2021\Unit - I>java demo
Output from derived class in other package
3
4 Program 2
Output from other class in other package
4
9/22/2021 6:21:13 PM CSE 208 – Java Programming 17
Program Output
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: n is not public in protection; cannot be accessed from
outside package
[Link](n);
^
[Link]: error: a has private access in protection
[Link](a);
^
2 errors
E:\slides\Java - 2021\Unit - I>javac [Link]
[Link]: error: b has protected access in protection
[Link](p.b);
^
1 error
9/22/2021 6:21:13 PM CSE 208 – Java Programming 18
Access Specifiers - Summary
9/22/2021 6:21:13 PM CSE 208 – Java Programming 19
We have discussed how to:
Define a package
Import a package
Use access specifiers
9/22/2021 6:21:13 PM CSE 208 – Java Programming 20
Exception Handling
9/22/2021 6:21:13 PM CSE 208 – Java Programming 21
E
X
C
E H
P A
T N
I D
O L
N I
[Link]
SAP / ICT / SOC N
G
Acknowledgement
• Liang, Introduction to Java Programming, Sixth
Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
• Program images from - Schildt
2
9/24/2021 2:06:59 PM
Introduction
Errors and Error handling
Types of Exceptions
General Form
Using try and catch
finally
9/24/2021 2:06:59 PM 3
Introduction
Users have high expectations for the code we
produce.
Users will use our programs in unexpected
ways.
Due to design errors or coding errors, our
programs may fail in unexpected ways during
execution
9/24/2021 2:06:59 PM 4
Introduction
It is our responsibility to produce quality
code that does not fail unexpectedly.
Consequently,
we must design error handling into our
programs.
9/24/2021 2:06:59 PM 5
9/24/2021 2:06:59 PM 6
Errors and Error Handling
An Error is any unexpected result obtained from a program
during execution.
Unhandled errors may manifest themselves as incorrect
results or behavior, or as abnormal program termination.
Errors should be handled by the programmer, to prevent
them from reaching the user.
9/24/2021 2:06:59 PM 7
Errors and Error Handling
Some typical causes of errors:
Memory errors (i.e. memory incorrectly allocated,
memory leaks, “null pointer”)
File system errors (i.e. disk is full, disk has been
removed)
Network errors (i.e. network is down, URL does not
exist)
Calculation errors (i.e. divide by 0)
9/24/2021 2:06:59 PM 8
Errors and Error Handling
You learned that there are three categories of errors: syntax errors,
runtime errors, and logic errors.
Syntax errors
Arise because the rules of the language have not been followed.
They are detected by the compiler.
Runtime errors
Occur while the program is running if the environment detects an
operation that is impossible to carry out.
Logic errors
occur when a program doesn't perform the way it was intended to.
9/24/2021 2:06:59 PM 9
Runtime Errors
1 import [Link];
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner([Link]);
6 [Link]("Enter an integer: ");
7 int number = [Link]();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the [Link](
10
programis terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.
9/24/2021 2:06:59 PM 10
Exception
Handling
9/24/2021 2:06:59 PM 11
What is an Exception?
An Exception is an abnormal condition that arises in a code
sequence at run time.
In other words, an exception is a runtime error.
In computer languages
that do not support exception handling,
errors must be checked and handled manually
typically through the use of error codes, and so on.
9/24/2021 2:06:59 PM 12
Exception-Handling Fundamentals
A Java exception is an object that describes an
exceptional (that is, error) condition that has occurred in a
piece of code.
When an exceptional condition arises,
an object representing that exception is created and
thrown in the method that caused the error.
That method may choose to handle the exception itself, or
pass it on.
Either way, at some point, the exception is caught and
processed.
9/24/2021 2:06:59 PM 13
General Form
try {
// block of code to monitor for errors Keywords
try
} catch
catch (ExceptionType1 exOb) { throw
// exception handler for ExceptionType1 throws
} finally
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block
ends }
9/24/2021 2:06:59 PM 14
Uncaught Exception
class Exc0
{
public static void main(String args[])
{
int d = 0; Exco.j
int a = 42 / d;
[Link](d);
ava
}
}
[Link]: / by zero
at [Link]([Link])
9/24/2021 2:06:59 PM 15
Catch Runtime Errors
1 import [Link].*;
2
3 public class HandleExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner([Link]);
6 boolean continueInput = true;
7
8 do {
9 try {
10 [Link]("Enter an integer: ");
11 int number = [Link]();
12 If an exception occurs on this line,
13 the rest of lines in the try block are // Display the result
14 skipped and the control is [Link](
15 transferred to the catch block. "The number entered is " + number);
16
17 continueInput = false;
18 }
19 catch (InputMismatchException ex) {
20 [Link]("Try again. (" +
21 "Incorrect input: an integer is required)");
22 [Link](); // discard input
23 }
24 } while (continueInput);
25 }
}
9/24/2021 2:06:59 PM 16
9/24/2021 2:06:59 PM 17
Exception Classes
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
LinkageError Several more classes
VirtualMachineError
Error
AWTError
Several more classes
9/24/2021 2:06:59 PM 18
System Errors
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
System errors are thrown by JVM Several more classes
LinkageError
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely VirtualMachineError
occur. If one does, there is little Error
you can do beyond notifying the AWTError
user and trying to terminate the
program gracefully. Several more classes
9/24/2021 2:06:59 PM 19
Exceptions
Exception describes errors ClassNotFoundException
caused by your program
and external IOException
circumstances. These ArithmeticException
errors can be caught and Exception AWTException
handled by your program. NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
LinkageError Several more classes
VirtualMachineError
Error
AWTError
Several more classes
9/24/2021 2:06:59 PM 20
Runtime Exceptions
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
LinkageError Several more classes
VirtualMachineError RuntimeException is caused by
Error programming errors, such as bad
casting, accessing an out-of-bounds
AWTError
array, and numeric errors.
Several more classes
9/24/2021 2:06:59 PM 21
Checked Exceptions
vs
Unchecked Exceptions
9/24/2021 2:06:59 PM 22
Checked Exceptions vs. Unchecked
Exceptions
Runtime Exception, Error and their subclasses are known as
unchecked exceptions.
All other exceptions are known as checked exceptions,
meaning that the compiler forces the programmer to check and
deal with the exceptions.
9/24/2021 2:06:59 PM 23
Checked or Unchecked Exceptions
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
LinkageError Several more classes
VirtualMachineError
Error Unchecked
exception.
AWTError
Several more classes
9/24/2021 2:06:59 PM 24
The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
9/24/2021 2:06:59 PM 25
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
9/24/2021 2:06:59 PM 26
Trace a Program Execution
The final block is
try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
9/24/2021 2:06:59 PM 27
Trace a Program Execution
Next statement in the
try { method is executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
9/24/2021 2:06:59 PM 28
Trace a Program Execution
try { Suppose an exception
statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
9/24/2021 2:06:59 PM 29
Trace a Program Execution
try { The exception is
statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
9/24/2021 2:06:59 PM 30
Trace a Program Execution
try { The final block is
statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
9/24/2021 2:06:59 PM 31
Trace a Program Execution
try { The next statement in
statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
9/24/2021 2:06:59 PM 32
Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type
statement3; Exception2.
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
9/24/2021 2:06:59 PM 33
Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
9/24/2021 2:06:59 PM 34
Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
9/24/2021 2:06:59 PM 35
We have discussed :
Need for Exception
handling mechanism
Types of Errors
Types of Exceptions
General Form
Using try and catch
finally
9/24/2021 2:06:59 PM
Exception Handling
9/24/2021 2:06:59 PM 37
9/24/2021 2:06:59 PM 38
E
X
C
E H
P A
T N
I D
O L
N I
[Link] N
SAP / ICT / SOC G
Acknowledgement
• Liang, Introduction to Java Programming, Sixth
Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
• Program images from - Schildt
2
Checked Exception - Example
Multiple Catch Clauses
Nested try statements
Throw
Throws
Checked Exception - Example
4
Checked Exception - Example
import [Link].*; [Link]
class filedemo
{
public static void main(String args[])
{
FileInputStream f=new FileInputStream("[Link]");
int size=[Link]();
[Link](size);
}
}
5
Checked Exception - Example
E:\slides\Java - 2020\Unit - I>javac [Link]
[Link]: error: unreported exception FileNotFoundException;
must be caught or declared to be thrown
FileInputStream f=new FileInputStream("[Link]");
^
[Link]: error: unreported exception IOException; must be
caught or declared to be thrown
int size=[Link]();
^
2 errors
6
Checked Exception - Example
import [Link].*; [Link]
class filedemo
{
public static void main(String args[]) throws Exception
{
FileInputStream f=new FileInputStream("[Link]");
int size=[Link]();
[Link](size);
}
}
E:\slides\Java - 2020\Unit - I>javac [Link]
E:\slides\Java - 2020\Unit - I>java filedemo
211
7
Using try and catch
8
Checked Exception - Example
import [Link].*; [Link]
class filedemo
{
public static void main(String args[])
{
try
{
FileInputStream f=new FileInputStream("[Link]");
int size=[Link]();
[Link](size);
} E:\slides\Java - 2020\Unit - I>javac [Link]
catch(Exception e)
{ E:\slides\Java - 2020\Unit - I>java filedemo
[Link](e); 254
}
}
}
9
Multiple catch Clauses
10
Multiple catch Clauses
11
12
Limitation
13
Error
14
We have discussed :
Checked Exception - Example
Multiple Catch Clauses
Generic Catch
9/25/2021 9:38:53 AM
Exception Handling
9/25/2021 9:38:53 AM 16
17
E
X
C
E H
P A
T N
I D
O L
N I
[Link] N
SAP / ICT / SOC G
Acknowledgement
• Liang, Introduction to Java Programming, Sixth
Edition, (c) 2007 Pearson Education, Inc. All
rights reserved. 0-13-222158-6
• Program images from - Schildt
2
Nested try statements
Throw
Throws
Creating your own Exception subclasses
Review Question - 1
What is the O/P of the Following Program ?
class d33 {
static
{
[Link]("sastra");
}
public static void main(String args[]) throws Exception
{
try
{ F:\java>javac [Link]
return;
}
F:\java>java d33
catch(Exception e)
{ sastra
[Link]("sastra123");
}
}
}
4
Review Question - 2
What is the O/P of the Following Program ?
class d33 {
public static void main(String args[]) throws Exception
{
try
{
return; F:\java>javac [Link]
}
[Link]: error: illegal start of
catch(Exception e)
{ expression
[Link]("sastra123"); static
} ^
static
1 error
{
[Link]("sastra");
}
}
}
5
Review Question - 3
What is the O/P of the Following Program ?
class d33 {
public static void main(String args[]) throws Exception
{
static F:\java>javac [Link]
{ [Link]: error: illegal start of
expression
[Link]("sastra");
static
} ^
} 1 error
}
6
Nested try Statements
7
Nested try Statements
8
9
Catch or Declare
Checked Exceptions
Java forces you to deal with checked exceptions. If a method declares a
checked exception (i.e., an exception other than Error or
RuntimeException), you must invoke it in a try-catch block or declare to
throw the exception in the calling method. For example, suppose that
method p1 invokes method p2 and p2 may throw a checked exception (e.g.,
IOException), you have to write the code as shown in (a) or (b).
void p1() { void p1() throws IOException {
try {
p2(); p2();
}
catch (IOException ex) { }
...
}
}
(a) (b)
10
11
Declaring Exceptions
Every method must state the types of checked
exceptions it might throw.
This is known as declaring exceptions.
public void myMethod() throws IOException
public void myMethod() throws IOException, OtherException
12
Throwing Exceptions
When the program detects an error,
the program can create an instance of an appropriate
exception type and throw it.
This is known as throwing an exception.
Here is an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
13
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
14
Recently
Added
Exception Feature
15
multi-catch feature
16
Creating Your
Own
Exception Subclasses
17
User Defined Exception
Define a subclass of Exception
The Exception class does not define any
methods of its own.
It inherit those methods provided by
Throwable.
18
Constructors
Exception( )
Exception(String msg)
19
Example
20
We have discussed :
Nested try statements
Throw
Throws
Creating your own Exception
subclasses
9/28/2021 1:05:09 PM
9/28/2021 1:05:09 PM 22
23
R
E
V
I
S
O
N
[Link]
SAP / ICT / SOC
CIA – I - Syllabus
• Introduction:
• History and Evolution of Java - Overview of
Java - Data types, Variables and Arrays -
Operators - Control Statements - Introducing
Classes - A closer look at Methods and
Classes - Inheritance. Packages and
Interfaces.
2
Review Question - 1
What is the output of the following program?
class array1 extends Object
{
public static void main(String args[])
{
int a[][]={{1,2,3},{4,5,6}};
[Link]([Link]);
}
}
A. 2
B. 3
C. 6
D. Compile Time Error
3
Review Question - 2
Predict is the output of the following program?
class demo1
{
public static void main(String args[])
{
double f1[ ],f2[ ];
f1=new double[10];
f2=f1;
[Link](f2[0]);
} A. ArrayIndexOutOfBoundsException
} B. 0.0
C. No Error No Output
D. Compile Time Error
4
Review Question - 3
What is the output of the following program?
class demo2
{
static public void main(String args[])
{
boolean $=false;
[Link]($);
}
}
A. true
B. false
C. CompileTimeError
D. RunTimeError
5
Review Question - 4
Analyze the program segment that follow and determine the output?
class demo
{
public static void main (String args[])
{
short a;
for(a=0;a<=70000;a++)
[Link](a);
} A. 0 ….70000 will be displayed in single line
} B. Compiler Error
C. Infinite Loop
D. 0 ….70000 will be displayed but each number in
separate line.
6
Review Question - 5
Analyze the program segment that follow and determine the output?
import [Link].*;
package p1;
class d35
{
public static void main(String args[])
{
[Link](“SASTRA University”);
}
} A. SASTRA University
B. Compiler Error
C. Runtime Error
D. None of the above
7
Review Question - 6
What is the output of the following program?
class d39
{
public static void main(String args[])
{
int x= -14 % 3;
[Link](x);
}
} A. 2
B. -2
C. 4
D. Compiler Error
8
Review Question - 7
What will happen when you try to compile and execute the following code?
interface x
{
void show();
} A. Show
B. Compile Time Error
class y implements x C. Run Time Error
{ D. Garbage value will be displayed
void show()
{
[Link](“show”);
}
}
9
Review Question - 8
Predict the output of the following program.
class loop
{
public static void main(String args[])
{
int i=2;
for(;i<8;i+=2)
{
[Link](i+"");
}
[Link](i);
}
} 10
Review Question - 9
What will happen when you try to compile and execute the
following code?
class loop
{
public static void main(String args[])
{
while (true)
{
[Link](“SASTRA”);
}
}
} 11
Review Question - 10
Analyze the following program and determine the output.
class empty
{
public static void main(String args[])
{
[Link]("sastra");
return;
[Link]("university");
}
}
12
Nested and Inner
Classes
9/29/2021 4:13:14 PM 13
14
15