Problem Solving Using Java
Problem Solving Using Java
Important: No Re-exam
[Link]
JAVA - IDE
JAVA - Eclipse
Step 1) Installing Eclipse Open your browser and type [Link]
Reference: [Link]
Step 16) Click on “Run” button.
Processing
Actions needed to obtain the required output
Output
List of Output Required
Problem Analysis Chart (PAC)
• According to Sprankle and Hubbard, (2012), the initial step for
a programs need to do when get a problem is to analyze and
understand the requirements.
• To easily analyze the problem, a Problem Analysis Chart (PAC)
was introduced. This chart have four section:
• The given data
• The required result
• The processing involved
• A list of solution alternative
PAC - Table
Problem Analysis Chart (PAC)
1. A program is required to find average of five
numbers.
Given Data Required Result
Number_1 Average of 5 numbers
Number_2
Number_3
Number_4
Number_5
Process Required Solution Alternative
Total = Number 1+ Number 2+ 1. Define the numbers as constants.
Number 3+ Number 4+ 2. Define the numbers as input
Number 5 values
Average = Total / 5
Problem Analysis Chart (PAC)
• Calculate the area of a circle for any given radius
Input Output
Length (l) Volume (V)
breadth (b)
width(w)
Input:
Enter strings = Hello Patrick Jane
Output:
Total 6
a2
e2
i1
o1
Display Total
Input String
Display each vowels count
• Sequence structure
• Selection structure
• Repetition structure
Three Basic Language Structures
Flowcharts for three constructs
Pseudocode for three constructs
Examples
Create PAC, Pseudocode, Flowchart to check whether a number is odd or even.
PAC
Input num1
Is
Yes num1 No
Mod
2==0?
STOP
Examples
Create PAC, Pseudocode, Flowchart to print the numbers 0 to “n” value.
PAC
Given Data Required Result
n Sum of the n numbers
1. Coding.
2. Compiling.
Programming phase takes 5 3. Debugging.
stages: 4. Run or Testing.
5. Documentation and
maintenance.
CODING
NO SYNTAX
ERROR
EXECUTE OR
RUN
DOCUMENTATION OR
MAINTENANCE
Basics
Procedure Oriented Programming
• Programming model which is derived from structured
programming, based upon the concept of calling procedure.
Main Program
Function 1 Function 2
Object A
Data
Functions
Object B Object C
Data Data
Functions Functions
Object Oriented Programming (OOPs) Paradigm
• The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the
code can access this data except that function.
Access Modifier
Access Modifier
Object Oriented Programming (OOPs) Paradigm
• The return type: The data type of the value returned by the
method or void if does not return a value.
• Method Name: the rules for field names apply to method names
as well, but the convention is a little different.
• Parameter list: Comma separated list of the input parameters are
defined, preceded with their data type, within the enclosed
parenthesis. If there are no parameters, you must use empty
parentheses ().
• Exception list: The exceptions you expect by the method can
throw; you can specify these exception(s).
• Method body: it is enclosed between braces. The code you need
to be executed to perform your intended operations.
OOPs Concepts
Object
An object is a real-world element in an object–oriented environment
that may have a physical or a conceptual existence.
Each object has −
• Identity that distinguishes it from other objects in the system.
• State that determines the characteristic properties of an object
as well as the values of the properties that the object holds.
• Behavior that represents externally visible activities performed
by an object in terms of changes in its state.
Objects can be modelled according to the needs of the application.
An object may have a physical existence, like a customer, a car, etc.; or
an intangible conceptual existence, like a project, a process, etc.
Class
A class represents a collection of objects having same characteristic
properties that exhibit common behavior.
It gives the blueprint or description of the objects that can be created
from it.
Creation of an object as a member of a class is called instantiation.
Thus, object is an instance of a class.
The constituents of a class are −
• A set of attributes for the objects that are to be instantiated from
the class. Generally, different objects of a class have some
difference in the values of the attributes. Attributes are often
referred as class data.
• A set of operations that portray the behavior of the objects of the
class. Operations are also referred as functions or methods.
Class
Let us consider a simple class, Circle, that represents the
geometrical figure circle in a two–dimensional space.
The attributes of this class can be identified as follows −
• x–coord, to denote x–coordinate of the center
• y–coord, to denote y–coordinate of the center
• a, to denote the radius of the circle
Some of its operations can be defined as follows −
• findArea(), method to calculate area
• findCircumference(), method to calculate circumference
• scale(), method to increase or decrease the radius
Class
During instantiation, values are assigned for at least some
of the attributes.
If we create an object my_circle, we can assign values like
x-coord : 2, y-coord : 3, and a : 4 to depict its state.
Now, if the operation scale() is performed on my_circle
with a scaling factor of 2, the value of the variable a will
become 8.
This operation brings a change in the state of my_circle,
i.e., the object has exhibited certain behavior.
Class & Objects
Class
Objects
Class & Objects
Class Objects
Class & Objects
Inheritance
Inheritance is an important pillar of OOP(Object Oriented Programming).
It is the mechanism in java by which one class is allow to inherit the
features(fields and methods) of another class.
• Let us discuss some of frequent used important terminologies:
• Super Class: The class whose features are inherited is known as
superclass(or a base class or a parent class).
• Sub Class: The class that inherits the other class is known as subclass(or
a derived class, extended class, or child class). The subclass can add its
own fields and methods in addition to the superclass fields and
methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when
we want to create a new class and there is already a class that includes
some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of
the existing class.
Inheritance
Types of Inheritance
• Single Inheritance − A subclass derives from a single super-class.
• Multiple Inheritance − A subclass derives from more than one
super-classes.
• Multilevel Inheritance − A subclass derives from a super-class
which in turn is derived from another class and so on.
• Hierarchical Inheritance − A class has a number of subclasses
each of which may have subsequent subclasses, continuing for a
number of levels, so as to form a tree structure.
• Hybrid Inheritance − A combination of multiple and multilevel
inheritance so as to form a lattice structure.
Inheritance
Inheritance
Polymorphism
• Polymorphism is originally a Greek word that means the ability to
take multiple forms.
• In object-oriented paradigm, polymorphism implies using
operations in different ways, depending upon the instance they
are operating upon.
• Polymorphism allows objects with different internal structures to
have a common external interface.
• Polymorphism is particularly effective while implementing
inheritance.
Note: Polymorphism in Java are mainly of 2 types:
• Overloading
• Overriding
Abstraction
• Data Abstraction is the property by virtue of which only the
essential details are displayed to the user.
• The trivial or the non-essentials units are not displayed to the user.
Ex: A car is viewed as a car rather than its individual components.
• Data Abstraction may also be defined as the process of identifying
only the required characteristics of an object ignoring the irrelevant
details.
• The properties and behaviors of an object differentiate it from
other objects of similar type and also help in classifying/grouping
the objects.
Abstraction
Abstraction
Encapsulation
It is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. Another
way to think about encapsulation is, it is a protective shield that prevents
the data from being accessed by the code outside this shield.
• Technically in encapsulation, the variables or data of a class is hidden
from any other class and can be accessed only through any member
function of own class in which they are declared.
• As in encapsulation, the data in a class is hidden from other classes, so it
is also known as data-hiding.
• Encapsulation can be achieved by Declaring all the variables in the class as
private and writing public methods in the class to set and get the values
of variables.
Encapsulation
Encapsulation
History of Java
James Gosling and Patrick Naughton initiated the Java
language project in June 1991.
The idea was to develop a language which was
platform-independent and which could create
embedded software for consumer electronic devices,
It took 18 months to develop and had an initial name
as Oak, Renamed to Java in 1995, due to copyright
issues.
Java originally developed by James Gosling at Sun
Microsystems and released in 1995
The principles for creating Java programming were "Simple, Robust, Portable,
Platform-independent, Secured, High Performance, Multithreaded,
Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java
Versions of java
• 1995 version 1.0:
– The Java development kit was released for free by the sun
– 8-Packages 212-Classes
– Microsoft and other companies licensed Java
• 1997 version 1.1:
– 23 -Packages 504-Classes
– Improvement include better event handling inner classes ,
improved JVM.
– Microsoft developed its own 1.1 compatible Java Virtual
Machine for Internet Explorer
– Many browsers in use are still compatible only with 1.1
Versions of java…
1999 version 1.2:
-It is also called as the Java 2 platform
-59 Packages -1520 Classes
-Code & tools distributed as the SDK
-A Java foundation class based on swings for
improved graphics and user interfaces
-Collection API included list sets and hash map
Versions of java…
. 2000 VERSION 1.3:
- 76 Packages - 1842 Classes
- Java Sound (API for Digital & MIDI Sound)
•2002 VERSION 1.4:
- 135 Packages - 2991 Classes
- Improved XML support etc..,
•2004 VERSION 5.0 (1.5):
- 165 Packages - over 3000 Classes
- Faster startup metadata formatted Output
- Generic to operate on objects of various types
Versions of java…
2006 Java SE 6:
– Scripting language support
2011 Java SE 7:
– JVM Support for dynamic language
– String in switch
– Allowing underscores in numeric literals
2014 Java SE 8:
– for Each() method in Iterable interface.
- default and static methods in Interfaces.
- Functional Interfaces and Lambda Expressions.
Versions of java…
Java SE 25
Features of Java
Features of Java
Simple
Java is very easy to learn, and its syntax is simple, clean and easy
to understand. According to Sun Microsystem, Java language is a
simple programming language because:
• Java syntax is based on C++ (so easier for programmers to
learn it after C++).
• Java has removed many complicated and rarely-used
features, for example, explicit pointers, operator overloading,
etc.
• There is no need to remove unreferenced objects because
there is an Automatic Garbage Collection in Java.
Features of Java
Object-oriented
Java is an object-oriented programming language. Everything in
Java is an object. Object-oriented means we organize our
software as a combination of different types of objects that
incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that
simplifies software development and maintenance by providing
some rules.
Basic concepts of OOPs are:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
Features of Java
Platform Independent
Java is platform independent because it is different from other
languages like C, C++, etc. which are compiled into platform specific
machines while Java is a write once, run anywhere language. A
platform is the hardware or software environment in which a program
runs.
The Java platform differs from most other platforms in the sense that
it is a software-based platform that runs on top of other hardware-
based platforms. It has two components:
[Link] Environment
[Link](Application Programming Interface)
Features of Java
Platform Independent
Class Loader
Execution Engine
As the name suggests, it is a component responsible for Loading Class
files. Loading, Linking, and initializing a class file are the major
functions of the Loader. The loader does it work in runtime.
Loading: Basically, the loader reads the .class file and then generates
the binary code and saves it in a method area. Bootstrap Classloader,
Extension Classloader, and Application Classloader are the various
ClassLoaders responsible for loading various classes.
Class Loader
Linking: Three major functions like Verification, Preparation, and
Resolve. It starts with .class file verification. If verification fails, it gives
a run-time verification exception. Later, Memory is allocated to the
variables with default values. Then, finally, the symbolic memory
references are replaced with direct references from the memory area.
One of the most relatable errors is the “OutOfMemoryError” exception, which means the
JVM cannot allocate an object in the Heap area, or memory allocation cannot be done for
the same object.
Stack
This is where a separate runtime stack is created for every new thread. Also known as a
Run-Time Stack, every time a method is called upon, all the details are stored in the
corresponding runtime stand, and after the completion of the method, these details are
removed from the stack.
PC Registers
For every single thread, a separate PC (Program Counter) register is created, which
stores the address of the current execution instruction, which, later, will be updated
with the next instruction. This memory area is quite small and is of fixed size.
It is one of its own kind of memory area, which is invoked by a thread, and then the
thread is at a whole new level where structure and security restrictions implied by Java
Virtual Machine are no longer in exercise. Compared to other runtime memory areas,
the memory occupied by the native method stacks has no fixed size, with no limitations
in increment or decrement.
Java Native Interface
2. JIT Compiler
• One of the most important components of the Java Runtime Environment
which enhances the Java Application performance at run time.
• No other component has more impact on performance than the JIT
Compiler.
• This is a default compiler and is activated when any Java method is called.
Features of Java
3. Garbage Collector
• As the name suggests, it does have something to do with garbage;
Garbage Collector simply searches for every possible object available in
the JVM heap space, checks if it is in use, and then delete the unused ones.
• So, it simply marks the pieces of memory which are in use or not. Then it
goes on sweeping, where it simply removes the object marked.
• The best use case is that no manual memory allocation system is needed as
the Garbage Collector does the job of automatically removing unused
memory space.
• As this is an automatic task, no programmer has control over scheduling
any time slot for specific cleaning tasks and requires more CPU power as it
searches for object references.
Byte Code
• In java when you compile a program, the java compiler(javac)
converts/rewrite your program in another form/language which we call
as bytecode.
• The .class file that is generated after compilation is nothing but just the
bytecode instructions of your program.
• The word bytecode and .class are used interchangeably, so if someone
says bytecode, it simply means the .class file of program.
JDK, JRE, JVM
Java Programming Structure
My First Program
Write a code to print the words Hello World.
Data Types in JAVA
Primitive Data Types
BYTE
• Byte stores from -128 and 127.
SHORT
short myNum = 5000;
[Link](myNum);
INT
• int stores from -2147483648 to 2147483647.
LONG
• long stores from -9223372036854775808 to
9223372036854775808.
DOUBLE
• Double can store fractional numbers from 1.7e−308 to 1.7e+038.
float f1 = 35e3f;
double d1 = 12E4d;
[Link](f1);
[Link](d1);
The precision of a floating point value indicates how many digits the
value can have after the decimal point. The precision of float is only six or
seven decimal digits, while double variables have a precision of about 15
digits. Therefore it is safer to use double for most calculations.
Boolean
Character
• The char data type is used to store a single character.
Variable-
Data-type
name
int count;
Variable Initialization
To initialize a variable, you must assign it a valid value.
if (i > 0) { if (i > 0)
[Link]("i is positive"); Equivalent [Link]("i is positive");
}
(a) (b)
Example
Write a program that prompts the user to enter an integer. If the
number is a multiple of 5, print HiFive. If the number is divisible
by 2, print HiEven.
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
if-else Example
if (radius >= 0) {
area = radius * radius * 3.14159;
(a) (b)
Multi-Way if-else Statements
Trace if-else statement
Suppose score is 70.0 The condition is false
BMI Interpretation
|| or logical disjunction
true false !(age > 18) is false, because (age > 18) is true.
false false false (age <= 18) && (weight < 140) is false, because both
true false false (age > 18) && (weight > 140) is false, because (weight
true true true (age > 18) && (weight >= 140) is true, because both
false true true (age > 34) || (weight <= 140) is true, because (age > 34)
true
true false (age > 14) || (weight >= 150) is false, because
true
true true
Truth Table for Operator ^
p1 p2 p1 ^ p2 Example (assume age = 24, weight = 140)
false false false (age > 34) ^ (weight > 140) is true, because (age > 34) is false
false true true (age > 34) ^ (weight >= 140) is true, because (age > 34) is false
true false true (age > 14) ^ (weight > 140) is true, because (age > 14) is
TestBooleanOperators
" divisible by 2 or 3, but not both? " + Run
Run
((number % 2 == 0) ^ (number % 3 == 0)));
Companion
Website
The & and | Operators
Statements break;
case 3: compute taxes for head of
household;
break;
default: [Link]("Errors: invalid
status");
[Link](1);
}
switch Statement Flow Chart
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression) {
byte, short, or int type and
must always be enclosed in case value1: statement(s)1;
parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression.
The resulting statements in the case valueN: statement(s)N;
case statement are executed when break;
the value in the case statement default: statement(s)-for-default;
matches the value of the switch-
}
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
switch Statement Rules
The keyword break is optional,
switch (switch-expression) {
but it should be used at the end
of each case in order to terminate case value1: statement(s)1;
the remainder of the switch break;
statement. If the break statement
is not present, the next case case value2: statement(s)2;
statement will be executed.
break;
…
case valueN: statement(s)N;
The default case, which is break;
optional, can be used to perform default: statement(s)-for-default;
actions when none of the
specified cases matches the
}
switch-expression.
When the value in a case statement matches the value
of the switch-expression, the statements starting from
this case are executed until either a break statement or
the end of the switch statement is reached.
animation
Trace switch statement
Suppose day is 2:
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
animation
Trace switch statement
Match case 2
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
animation
Trace switch statement
Fall through case 3
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
animation
Trace switch statement
Fall through case 4
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
animation
Trace switch statement
Fall through case 5
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
animation
Trace switch statement
Encounter break
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
animation
Trace switch statement
Exit the statement
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: [Link]("Weekday"); break;
case 0:
case 6: [Link]("Weekend");
}
Sample
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 6:
[Link]("Today is Saturday");
break;
case 7:
[Link]("Today is Sunday");
break;
default:
[Link]("Looking forward to the Weekend");
}
}
}
Problem: Chinese Zodiac
Write a program that prompts the user to enter a year and
displays the animal for the year.
ChineseZodiac
Run
ChineseZodiac Run
Conditional Expressions
if (x > 0)
y=1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(boolean-expression) ? expression1 : expression2
Ternary operator
Binary operator
Unary operator
Conditional Operator
if (num % 2 == 0)
[Link](num + “is even”);
else
[Link](num + “is odd”);
[Link](
(num % 2 == 0)? num + “is even” :
num + “is odd”);
Conditional Operator, cont.
boolean-expression ? exp1 : exp2
Operator Precedence
• ()
• var++, var--
• +, - (Unary plus and minus), ++var,--var
• (type) Casting
• ! (Not)
• *, /, % (Multiplication, division, and remainder)
• +, - (Binary addition and subtraction)
• <, <=, >, >= (Relational operators)
• ==, !=; (Equality)
• ^ (Exclusive OR)
• && (Conditional AND) Short-circuit AND
• || (Conditional OR) Short-circuit OR
• =, +=, -=, *=, /=, %= (Assignment operator)
Operator Precedence and Associativity
The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the expression
in the inner parentheses is executed first.) When
evaluating an expression without parentheses, the
operators are applied according to the precedence rule
and the associativity rule.
3 + 4 * 4 > 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 > 5 * 7 – 1
(2) multiplication
3 + 16 > 5 * 7 – 1
(3) multiplication
3 + 16 > 35 – 1
(4) addition
19 > 35 – 1
(5) subtraction
19 > 34
(6) greater than
false
Debugging
Logic errors are called bugs. The process of finding and
correcting errors is called debugging. A common approach
to debugging is to use a combination of methods to
narrow down to the part of the program where the bug is
located. You can hand-trace the program (i.e., catch errors
by reading the program), or you can insert print
statements in order to show the values of the variables or
the execution flow of the program. This approach might
work for a short, simple program. But for a large, complex
program, the most effective approach for debugging is to
use a debugger utility.
Debugger
Debugger is a program that facilitates debugging.
You can use a debugger to
RepeatAdditionQuiz Run
Problem: Guessing Numbers
Write a program that randomly generates an integer
between 0 and 100, inclusive. The program prompts the
user to enter a number continuously until the number
matches the randomly generated number. For each user
input, the program tells the user whether the input is too
low or too high, so the user can choose the next input
intelligently. Here is a sample run:
GuessNumberOneTime
Run
GuessNumberOneTime Run
GuessNumber
Run
GuessNumber Run
Problem: An Advanced Math Learning Tool
SubtractionQuizLoop
Run
SubtractionQuizLoop Run
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to signify the
end of the loop. Such a value is known as a sentinel value.
SentinelValue
Run
SentinelValue Run
Caution
Don’t use floating-point values for equality checking in a
loop control. Since floating-point values are
approximations for some values, using them could result
in imprecise counter values and inaccurate results.
Consider the following code for computing 1 + 0.9 + 0.8
+ ... + 0.1:
double item = 1; double sum = 0;
while (item != 0) { // No guarantee item will be 0
sum += item;
item -= 0.1;
}
[Link](sum);
do-while Loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
for Loops
for (initial-action; loop- int i;
continuation-condition; action- for (i = 0; i < 100; i++) {
after-each-iteration) {
[Link](
// loop body;
Statement(s); "Welcome to Java!");
} }
animation
A for loop in (a) in the following figure can generally be converted into the
following while loop in (b) except in certain special cases (see Review Question
3.19 for one of them):
for (initial-action; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
Recommendations
Use the one that is most intuitive and comfortable for
you. In general, a for loop may be used if the number of
repetitions is known, as, for example, when you need to
print a message 100 times. A while loop may be used if
the number of repetitions is not known, as in the case of
reading the numbers until the input is 0. A do-while loop
can be used to replace a while loop if the loop body has to
be executed before testing the continuation condition.
Nested Loops
Problem: Write a program that uses nested for
loops to print a multiplication table.
MultiplicationTable
Run
MultiplicationTable Run
Minimizing Numerical Errors
Numeric errors involving floating-point
numbers are inevitable. This section discusses
how to minimize such errors through an
example.
TestSum Run
Problem:
Finding the Greatest Common Divisor
Problem: Write a program that prompts the user to enter two
positive integers and finds their greatest common divisor.
Solution: Suppose you enter two integers 4 and 2, their greatest
common divisor is 2. Suppose you enter two integers 16 and 24,
their greatest common divisor is 8. So, how do you find the
greatest common divisor? Let the two input integers be n1 and n2.
You know number 1 is a common divisor, but it may not be the
greatest commons divisor. So you can check whether k (for k = 2,
3, 4, and so on) is a common divisor for n1 and n2, until k is
greater than n1 or n2.
Problem: Predicting the Future Tuition
Problem: Suppose that the tuition for a university is $10,000 this year
and tuition increases 7% every year. In how many years will the
tuition be doubled?
FutureTuition
Run
FutureTuition Run
Problem: Predicating the Future Tuition
double tuition = 10000; int year = 0 // Year 0
tuition = tuition * 1.07; year++; // Year 1
tuition = tuition * 1.07; year++; // Year 2
tuition = tuition * 1.07; year++; // Year 3
...
Case Study: Converting Decimals to
Hexadecimals
Hexadecimals are often used in computer systems programming (see
Appendix F for an introduction to number systems). How do you
convert a decimal number to a hexadecimal number? To convert a
decimal number d to a hexadecimal number is to find the hexadecimal
digits hn, hn-1, hn-2, ... , h2, h1, and h0 such that
d = hn 16 n + hn − 1 16 n −1 + hn − 2 16 n − 2 + ... + h 2 16 2 + h1 161 + h 0 16 0
Dec2Hex Run
Companion Website
can be approximated as 4 *
-1 1
x numberOfHits / numberOfTrials
MonteCarloSimulation
Run
MonteCarloSimulation Run
-1
Using break and continue
Examples for using the break and continue
keywords:
[Link]
TestBreak
Run
TestBreak Run
[Link]
TestContinue
Run
TestContinue Run
break
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;
GuessNumberUsingBreak
Run
GuessNumberUsingBreak Run
Problem: Checking Palindrome
A string is a palindrome if it reads the same forward and backward.
The words “mom,” “dad,” and “noon,” for instance, are all
palindromes.
The problem is to write a program that prompts the user to enter a
string and reports whether the string is a palindrome. One solution is
to check whether the first character in the string is the same as the last
character. If so, check whether the second character is the same as the
second-to-last character. This process continues until a mismatch is
found or all the characters in the string are checked, except for the
middle character if the string has an odd number of characters.
low high
String s a b c d e f g n h g f e d c b a
Palindrome
Run
Palindrome Run
Problem: Displaying Prime Numbers
Problem: Write a program that displays the first 50 prime numbers in
five lines, each of which contains 10 numbers. An integer greater than
1 is prime if its only positive divisor is 1 or itself. For example, 2, 3,
5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.
Solution: The problem can be broken into the following tasks:
•For number = 2, 3, 4, 5, 6, ..., test whether the number is prime.
•Determine whether a given number is prime.
•Count the prime numbers.
•Print each prime number, and print 10 numbers per line.
PrimeNumber
Run
PrimeNumber Run
Single-Dimensional Arrays
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;
Example:
myList = new double[10];
[Link]
For example,
[Link] returns 10
Default Values
When an array is created, its elements are
assigned the default value of
arrayRefVar[index];
Using Indexed Variables
After an array is created, an indexed variable can
be used in the same way as a regular variable.
For example, the following code adds the value
in myList[0] and myList[1] to myList[2].
}
}
animation
Trace Program with Arrays
i becomes 1
} 2 0
4 0
}
}
animation
Trace Program with Arrays
i (=1) is less than 5
} 4 0
}
animation
Trace Program with Arrays
After this line is executed, value[1] is 1
}
}
animation
Trace Program with Arrays
After i++, i becomes 2
values[i] = i + values[i-1]; 1 1
2 0
} 3 0
}
}
animation
Trace Program with Arrays
i (= 2) is less than 5
public class Test {
public static void main(String[]
args) {
int[] values = new int[5]; After the first iteration
} 2 0
3 0
values[0] = values[1] + 4 0
values[4];
}
}
animation
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)
}
}
animation
Trace Program with Arrays
After this, i becomes 3.
}
}
animation
Trace Program with Arrays
i (=3) is still less than 5.
}
}
animation
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)
}
}
animation
Trace Program with Arrays
After this, i becomes 4
}
}
animation
Trace Program with Arrays
i (=4) is still less than 5
}
}
animation
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)
}
}
animation
Trace Program with Arrays
After i++, i becomes 5
1 1
values[0] = values[1] + values[4];
2 3
}
3 6
} 4 10
animation
1 1
values[0] = values[1] + values[4]; 2 3
} 3 6
10
} 4
animation
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)
double total = 0;
for (int i = 0; i < [Link]; i++) {
total += myList[i];
}
Finding the largest element
You still have to use an index variable if you wish to traverse the array in a
different order or change the elements in the array.
Analyze Numbers
Read numbers from users, compute their average, and
find out how many numbers are above the average.
Problem: Deck of Cards
The problem is to write a program that picks four cards
randomly from a deck of 52 cards. All the cards can be
represented using an array named deck, filled with initial
values 0 to 51, as follows:
LottoNumbers
Run
[2] false [2] false [2] false [2] true [2] true
[3] false [3] false [3] false [3] false [3] false
. . . . .
. . . . .
. . . . .
list2 = list1;
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[[Link]];
Example:
[Link](sourceArray, 0,
targetArray, 0, [Link]);
Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < [Link]; i++) {
[Link](array[i] + " ");
}
}
Anonymous array
Anonymous Array
The statement
printArray(new int[]{3, 1, 2, 6, 4, 2});
creates an array using the following syntax:
new dataType[]{literal0, literal1, ..., literalk};
There is no explicit reference variable for the array.
Such array is called an anonymous array.
Pass By Value
Java uses pass by value to pass arguments to a method. There
are important differences between passing a value of variables
of primitive data types and passing arrays.
TestPassArray
Run
TestPassArray Run
Example, cont.
Stack Heap Stack
Space required for the
Space required for the swapFirstTwoInArray
swap method method
n2: 2 int[] array reference
n1: 1
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 0
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 0 and j = 5
public static int[] reverse(int[] list) {
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 0
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (= 0) is less than 6
public static int[] reverse(int[] list) {
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 0
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 0 and j = 5
public static int[] reverse(int[] list) { Assign list[0] to result[5]
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 1 and j = 4
public static int[] reverse(int[] list) { Assign list[1] to result[4]
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 2 and
public static int[] reverse(int[] list) { j becomes 3
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=2) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 2 and j = 3
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 3 and
public static int[] reverse(int[] list) { j becomes 2
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=3) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 3 and j = 2
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 4 and
public static int[] reverse(int[] list) { j becomes 1
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=4) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 4 and j = 1
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 5 and
public static int[] reverse(int[] list) { j becomes 0
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=5) is still less than 6
public static int[] reverse(int[] list) {
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i = 5 and j = 0
public static int[] reverse(int[] list) { Assign list[i] to result[j]
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
After this, i becomes 6 and
public static int[] reverse(int[] list) { j becomes -1
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=6) < 6 is false. So exit
public static int[] reverse(int[] list) { the loop.
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
animation
Trace the reverse Method, cont.
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
Return result
public static int[] reverse(int[] list) {
int[] result = new int[[Link]];
return result;
}
list 1 2 3 4 5 6
list2
result 6 5 4 3 2 1
Problem: Counting Occurrence of Each
Letter
• Generate 100 lowercase letters randomly and assign to an array of
characters.
• Count the occurrence of each letter in the array.
CountLettersInArray
Run
CountLettersInArray Run
Variable-Length Arguments
You can pass a variable number of arguments of the same
type to a method.
VarArgsDemo
Run
VarArgsDemo Run
Searching Arrays
Searching is the process of looking for a specific element in
an array; for example, discovering whether a certain score is
included in a list of scores. Searching is a common task in
computer programming. There are many algorithms and
data structures devoted to searching. In this section, two
commonly used approaches are discussed, linear search
and binary search.
public class LinearSearch {
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < [Link]; i++)
if (key == list[i]) [0] [1] [2] …
return i; list
return -1;
} key Compare key with list[i] for i = 0, 1, …
}
Linear Search
The linear search approach compares the key
element, key, sequentially with each element in the
array list. The method continues to do so until the
key matches an element in the list or the list is
exhausted without a match being found. If a match is
made, the linear search returns the index of the
element in the array that matches the key. If no
match is found, the search returns -1.
animation
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
3 6 4 1 9 7 3 2 8
animation
Linear Search Animation
[Link]
[Link]
From Idea to Solution
/** The method for finding a key in the list */
public static int linearSearch(int[] list, int key) {
for (int i = 0; i < [Link]; i++)
if (key == list[i])
return i;
return -1;
}
Binary Search
Key List
8 1 2 3 4 6 7 8 9
8 1 2 3 4 6 7 8 9
8 1 2 3 4 6 7 8 9
animation
Binary Search Animation
[Link]
[Link]
Binary Search, cont.
Binary Search, cont.
key is 54 low mid high
key > 50 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
list 2 4 7 10 11 45 50 59 60 66 69 70 79
low mid high
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
key < 66 list 59 60 66 69 70 79
[7] [8]
key < 59 list 59 60
low high
-insertion point - 1.
return -1 - low;
}
The [Link] Method
Since binary search is frequently used in programming, Java provides several
overloaded binarySearch methods for searching a key in an array of int, double,
char, short, long, and float in the [Link] class. For example, the following
code searches the keys in an array of numbers and an array of characters.
int[] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79};
[Link]("Index is " +
[Link](list, 11));
Return is 4
char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'};
[Link]("Index is " +
[Link](chars, 't')); Return is –4 (insertion point is
3, so return is -3-1)
For the binarySearch method to work, the array must be pre-sorted in increasing
order.
Sorting Arrays
Sorting, like searching, is also a common task in computer
programming. Many different algorithms have been
developed for sorting. This section introduces a simple,
intuitive sorting algorithms: selection sort.
Selection Sort
Selection sort finds the smallest number in the list and places it first. It then
finds the smallest number remaining and places it second, and so on until the list
contains only a single number.
animation
Selection Sort Animation
[Link]
[Link]
From Idea to Solution
for (int i = 0; i < [Link]; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i+1..listSize-1]
}
...
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i+1; j < [Link]; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
for (int i = 0; i < listSize; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i; j < [Link]; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
for (int i = 0; i < listSize; i++) {
select the smallest element in list[i..listSize-1];
swap the smallest with list[i], if necessary;
// list[i] is in its correct position.
// The next iteration apply on list[i..listSize-1]
}
Expand
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
Wrap it in a Method
/** The method for sorting the numbers */
public static void selectionSort(double[] list) {
for (int i = 0; i < [Link]; i++) {
// Find the minimum in the list[i..[Link]-1]
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < [Link]; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
java Calculator 2 + 3
java Calculator 2 - 3
Calculator
// Alternative syntax
dataType refVar[][] = new dataType[10][10];
380
Declaring Variables of Two-dimensional Arrays
and Creating Two-dimensional Arrays
double[][] x;
381
Two-dimensional Array Illustration
[Link]? 5 [Link]? 4
matrix[0].length? 5 array[0].length? 3
382
Declaring, Creating, and Initializing Using Shorthand
Notations
int[][] array = {
int[][] array = new int[4][3];
{1, 2, 3}, array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, Same as array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};
383
Lengths of Two-dimensional Arrays
384
Lengths of Two-dimensional Arrays,
cont.
int[][] array = { [Link]
{1, 2, 3}, array[0].length
{4, 5, 6}, array[1].length
{7, 8, 9}, array[2].length
{10, 11, 12} array[3].length
};
array[4].length ArrayIndexOutOfBoundsException
385
Ragged Arrays
Each row in a two-dimensional array is itself an array. So,
the rows can have different lengths. Such an array is
known as a ragged array. For example,
int[][] matrix = {
{1, 2, 3, 4, 5},
[Link] is 5
{2, 3, 4, 5}, matrix[0].length is 5
{3, 4, 5}, matrix[1].length is 4
matrix[2].length is 3
{4, 5}, matrix[3].length is 2
{5} matrix[4].length is 1
};
386
Ragged Arrays, cont.
387
Processing Two-Dimensional Arrays
See the examples in the text.
1. (Initializing arrays with input values)
2. (Printing arrays)
3. (Summing all elements)
4. (Summing all elements by column)
5. (Which row has the largest sum)
6. (Finding the smallest index of the largest element)
7. (Random shuffling)
388
Initializing arrays with input values
[Link] input = new Scanner([Link]);
[Link]("Enter " + [Link] + " rows and " +
matrix[0].length + " columns: ");
for (int row = 0; row < [Link]; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = [Link]();
}
}
389
Initializing arrays with random values
390
Printing arrays
for (int row = 0; row < [Link]; row++) {
for (int column = 0; column < matrix[row].length; column++) {
[Link](matrix[row][column] + " ");
}
[Link]();
}
391
Summing all elements
int total = 0;
for (int row = 0; row < [Link]; row++) {
for (int column = 0; column < matrix[row].length; column++) {
total += matrix[row][column];
}
}
392
Summing elements by column
for (int column = 0; column < matrix[0].length; column++) {
int total = 0;
for (int row = 0; row < [Link]; row++)
total += matrix[row][column];
[Link]("Sum for column " + column + " is "
+ total);
}
393
Random shuffling
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int i1 = (int)([Link]() * [Link]);
int j1 = (int)([Link]() * matrix[i].length);
// Swap matrix[i][j] with matrix[i1][j1]
int temp = matrix[i][j];
matrix[i][j] = matrix[i1][j1];
matrix[i1][j1] = temp;
}
}
394
Problem: Grading Multiple-Choice Test
395
Problem: Finding Two Points Nearest to Each Other
396
What is Sudoku?
5 3 7 [Link]
6 1 9 5
9 8 6
/animation/web/[Link]
8 6 3
4 8 3 1
7 2 6
6
4 1 9 5
8 7 9
397
Every row contains the numbers 1 to 9
5 3 7 5 3 4 6 7 8 9 1 2
6 1 9 5 6 7 2 1 9 5 3 4 8
9 8 6 1 9 8 3 4 2 5 6 7
8 6 3 8 5 9 7 6 1 4 2 3
4 8 3 1 4 2 6 8 5 3 7 9 1
7 2 6 7 1 3 9 2 4 8 5 6
6 9 6 1 5 3 7 2 8 4
4 1 9 5 2 8 7 4 1 9 6 3 5
8 7 9 3 4 5 2 8 6 1 7 9
398
Every column contains the numbers 1 to 9
5 3 7 5 3 4 6 7 8 9 1 2
6 1 9 5 6 7 2 1 9 5 3 4 8
9 8 6 1 9 8 3 4 2 5 6 7
8 6 3 8 5 9 7 6 1 4 2 3
4 8 3 1 4 2 6 8 5 3 7 9 1
7 2 6 7 1 3 9 2 4 8 5 6
6 9 6 1 5 3 7 2 8 4
4 1 9 5 2 8 7 4 1 9 6 3 5
8 7 9 3 4 5 2 8 6 1 7 9
399
Every 3×3 box contains the numbers 1 to 9
5 3 7 5 3 4 6 7 8 9 1 2
6 1 9 5 6 7 2 1 9 5 3 4 8
9 8 6 1 9 8 3 4 2 5 6 7
8 6 3 8 5 9 7 6 1 4 2 3
4 8 3 1 4 2 6 8 5 3 7 9 1
7 2 6 7 1 3 9 2 4 8 5 6
6 9 6 1 5 3 7 2 8 4
4 1 9 5 2 8 7 4 1 9 6 3 5
8 7 9 3 4 5 2 8 6 1 7 9
400
Checking Whether a Solution Is Correct
5 3 7 5 3 4 6 7 8 9 1 2
6 1 9 5 6 7 2 1 9 5 3 4 8
9 8 6 1 9 8 3 4 2 5 6 7
8 6 3 8 5 9 7 6 1 4 2 3
4 8 3 1 4 2 6 8 5 3 7 9 1
7 2 6 7 1 3 9 2 4 8 5 6
6 9 6 1 5 3 7 2 8 4
4 1 9 5 2 8 7 4 1 9 6 3 5
8 7 9 3 4 5 2 8 6 1 7 9
PassTwoDimensionalArray
Run
PassTwoDimensionalArray Run
401
Multidimensional Arrays
Occasionally, you will need to represent n-dimensional
data structures. In Java, you can create n-dimensional
arrays for any integer n.
402
Multidimensional Arrays
double[][][] scores = {
{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},
{{4.5, 21.5}, {9.0, 22.5}, {15, 34.5}, {12, 20.5}, {14, 9.5}},
{{6.5, 30.5}, {9.4, 10.5}, {11, 33.5}, {11, 23.5}, {10, 2.5}},
{{6.5, 23.5}, {9.4, 32.5}, {13, 34.5}, {11, 20.5}, {16, 7.5}},
{{8.5, 26.5}, {9.4, 52.5}, {13, 36.5}, {13, 24.5}, {16, 2.5}},
{{9.5, 20.5}, {9.4, 42.5}, {13, 31.5}, {12, 20.5}, {16, 6.5}}
};
scores[ i ] [ j ] [ k ]
403
Problem: Calculating Total Scores
Objective: write a program that calculates the total score for
students in a class. Suppose the scores are stored in a three-
dimensional array named scores. The first index in scores refers
to a student, the second refers to an exam, and the third refers
to the part of the exam. Suppose there are 7 students, 5 exams,
and each exam has two parts--the multiple-choice part and the
programming part. So, scores[i][j][0] represents the score on the
multiple-choice part for the i’s student on the j’s exam. Your
program displays the total score for each student.
404
Problem: Weather Information
Suppose a meteorology station records the temperature
and humidity at each hour of every day and stores the data
for the past ten days in a text file named [Link]. Each
line of the file consists of four numbers that indicate the
day, hour, temperature, and humidity. Your task is to write a
program that calculates the average daily temperature and
humidity for the 10 days.
(a) (b)
405
Problem: Guessing Birthday
Listing 4.3, [Link], gives a program that
guesses a birthday. The program can be simplified by
storing the numbers in five sets in a three-dimensional
array, and it prompts the user for the answers using a
loop.
406
Problem:
Wrapper Classes
• The [Link] package contains a wrapper class
that corresponds to each primitive type:
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
void Void 408
Wrapper Classes
• The following declaration creates an Integer
object which is a reference to an object with the
integer value 40
Integer age = new Integer(40);
• An object of a wrapper class is used in situations
where a primitive value will not suffice
• For example, some objects serve as containers of
other objects
• Primitive values could not be stored in such
containers, but wrapper objects could be
409
Wrapper Classes
• Wrapper classes may contain static methods that help
manage the associated type
• For example, the Integer class contains a method to convert
digits stored in a String to an int value:
num = [Link](str);
• Wrapper classes often contain useful constants
• For example, the Integer class contains MIN_VALUE and
MAX_VALUE for the smallest and largest int values
410
Autoboxing
• Autoboxing is the automatic conversion of a primitive
value to a corresponding wrapper object:
Integer obj;
int num = 42;
obj = num;
• The assignment creates the appropriate Integer
object wrapping a value of 42
• The reverse conversion (called unboxing) also occurs
automatically as needed
411
Methods
414
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method
return result;
}
415
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method
416
Pass by Value
417
Exercise: Converting Hexadecimals to
Decimals
418
Solution
419
420
Overloading Methods
Overloading methods enables you to define the methods with
the same name as long as their signatures are different.
421
422
Objects and Classes
423
OO Programming Concepts
425
Classes
Classes are constructs that define objects of the
same type. A Java class uses variables to define
data fields and methods to define behaviors.
Additionally, a class provides a special type of
methods, known as constructors, which are
invoked to construct objects from the class.
426
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field
428
Example: Defining Classes and
Creating Objects
429
430
431
432
Example: Defining Classes and Creating Objects
TV
channel: int The current channel (1 to 120) of this TV.
volumeLevel: int The current volume level (1 to 7) of this TV.
on: boolean Indicates whether this TV is on/off.
433
434
435
436
Constructors
Constructors are a special kind of methods that are invoked to
construct objects.
Circle() {
}
Circle(double newRadius) {
radius = newRadius;
}
437
Constructors, cont.
A constructor with no parameters is referred to as a no-
arg constructor.
▪ Constructors must have the same name as the class
itself.
▪ Constructors do not have a return type—not even
void.
▪ Constructors are invoked using the new operator
when an object is created. Constructors play the role
of initializing objects.
438
Creating Objects Using Constructors
new ClassName();
Example:
new Circle();
new Circle(5.0);
439
Default Constructor
A class may be defined without constructors. In
this case, a no-arg constructor with an empty
body is implicitly defined in the class.
This constructor, called a default constructor, is
provided automatically only if no constructors
are explicitly defined in the class.
440
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n; }
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a; }
void display(){[Link](id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
441
}
Destructor
The destructor is the opposite of the constructor.
The constructor is used to initialize objects while the destructor is
used to delete or destroy the object that releases the resource
occupied by the object.
Remember that there is no concept of destructor in Java. In place
of the destructor, Java provides the garbage collector that works
the same as the destructor.
The garbage collector is a program (thread) that runs on the JVM
It is difficult for the programmer to forcefully execute the garbage
collector to destroy the object. Alternatively, the Java Object class
provides the finalize() method that works the same as the
destructor.
442
Garbage Collection
TIP: If you know that an object is no longer needed, you can
explicitly assign null to a reference variable for the object. The
JVM will automatically collect the space if the object is not
referenced by any variable.
443
public class DestructorExample
{
public static void main(String[] args)
{
DestructorExample de = new DestructorExample ();
[Link]();
de = null;
[Link]();
[Link]("Inside the main() method");
}
protected void finalize()
{
[Link]("Object is destroyed GC");
}
}
444
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.
ClassName objectRefVar;
Example:
Circle myCircle;
445
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
446
Accessing Object’s Members
❑Referencing the object’s data:
[Link]
e.g., [Link]
447
Caution
Recall that you use
[Link](arguments) (e.g., [Link](3, 2.5))
448
Reference Data Fields
The data fields can be of reference types. For example, the
following Student class contains a data field name of the String
type.
public class Student {
String name;
// name has default value null
int age;
// age has default value 0
boolean isScienceMajor;
// isScienceMajor has default value false
char gender;
// c has default value '\u0000'
}
449
The null Value
If a data field of a reference type does not
reference any object, the data field holds a
special literal value, null.
450
Default Value for a Data Field
The default value of a data field is null for a reference
type, 0 for a numeric type, false for a boolean type, and
'\u0000' for a char type. However, Java assigns no default
value to a local variable inside a method.
451
Example
Java assigns no default value to a local variable inside a
method.
radius = 1
453
Copying Variables of Primitive
Data Types and Object Types
Primitive type assignment i = j
Before: After:
i 1 i 2
j 2 j 2
Object type assignment c1 = c2
Before: After:
c1 c1
c2 c2
454
The Date Class
Java provides a system-independent encapsulation of date and
time in the [Link] class. You can use the Date class to
create an instance for the current date and time and use its
toString method to return the date and time as a string.
[Link]
The + sign indicates
public modifer +Date() Constructs a Date object for the current time.
+Date(elapseTime: long) Constructs a Date object for a given time in
milliseconds elapsed since January 1, 1970, GMT.
+toString(): String Returns a string representing the date and time.
+getTime(): long Returns the number of milliseconds since January 1,
1970, GMT.
+setTime(elapseTime: long): void Sets a new elapse time in the object.
455
The Date Class Example
For example, the following code
456
Input
import [Link];
public class DateDemo {
Output
on May 04 09:51:52 CDT 2009
457
// Program to demonstrate methods of Date class
import [Link].*;
public class Main
{
public static void main(String[] args)
{
// Creating date
Date d1 = new Date(2000, 11, 21);
Date d2 = new Date(); // Current date
Date d3 = new Date(2010, 1, 3);
boolean a = [Link](d1);
[Link]("Date d3 comes after " + "date d2: " + a);
boolean b = [Link](d2);
[Link]("Date d3 comes before "+ "date d2: " + b);
int c = [Link](d2);
[Link](c);
[Link]("Miliseconds from Jan 1 "+ "1970 to date d1 is " +
[Link]());
[Link]("Before setting "+d2);
[Link](204587433443L);
[Link]("After setting "+d2);
}
}
458
The Random Class
You have used [Link]() to obtain a random double
value between 0.0 and 1.0 (excluding 1.0). A more useful
random number generator is provided in the
[Link] class.
[Link]
+Random() Constructs a Random object with the current time as its seed.
+Random(seed: long) Constructs a Random object with a specified seed.
+nextInt(): int Returns a random int value.
+nextInt(n: int): int Returns a random int value between 0 and n (exclusive).
+nextLong(): long Returns a random long value.
+nextDouble(): double Returns a random double value between 0.0 and 1.0 (exclusive).
+nextFloat(): float Returns a random float value between 0.0F and 1.0F (exclusive).
+nextBoolean(): boolean Returns a random boolean value.
459
The Random Class Example
If two Random objects have the same seed, they will generate
identical sequences of numbers. For example, the following code
creates two Random objects with the same seed 3.
From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961
460
import [Link];
public class JavaRandomExample1 {
public static void main(String[] args) {
//create random object
Random random= new Random();
//returns unlimited stream of pseudorandom long values
[Link]("Longs value : "+[Link]());
// Returns the next pseudorandom boolean value
boolean val = [Link]();
[Link]("Random boolean value : "+val);
byte[] bytes = new byte[10];
//generates random bytes and put them in an array
[Link](bytes);
[Link]("Random bytes = ( ");
for(int i = 0; i< [Link]; i++)
{
[Link]("%d ", bytes[i]);
}
[Link](")");
}
} 461
The Point2D Class
Java API has a conveninent Point2D class in the
[Link] package for representing a point in a two-
dimensional plane.
462
463
Instance Variables, and Methods
Instance variables belong to a specific instance.
464
Static Member
▪ To create a static member (block, variable, method,
nested class), you need to precede its declaration with
the keyword static.
▪ When a member of the class is declared as static, it
can be accessed before the objects of its class are
created, and without any object reference.
▪ static keyword is a non-access modifier and can be
used for the following:
➢ Static Block
➢ Static Variable
➢ Static Method
➢ Static Classes
465
Static Block
// Java program to demonstrate the use of static blocks
import [Link].*;
public class BlockExample{ Output
// static variable Static block initialized
static int j = 10; Inside main method
static int n; Value of j:10
// static block Value of n : 80
static {
[Link]("Static block initialized.");
n = j * 8;
}
public static void main(String[] args)
{
[Link]("Inside main method");
[Link]("Value of j : "+j);
[Link]("Value of n : "+n);
}
}
466
Static Variables
// Java program demonstrate execution of static blocks and variables
import [Link].*;
public class VariableExample Output
{ from n
// static variable
Inside the static block
static int j = n();
// static block Value of j: 20
static { Inside main method
[Link]("Inside the static block");
}
// static method
static int n() {
[Link]("from n ");
return 20;
}
// static method(main !!)
public static void main(String[] args)
{
[Link]("Value of j : "+j);
[Link]("Inside main method");
}
}
467
Static Methods
void getStudentInfo()
{
[Link]("name : " +
// static keyword with methods and variables
[Link]);
// Student class [Link]("rollNo : " +
class Student { [Link]);
String name; // accessing static variable
int rollNo; [Link]("cllgName : " +
// static variable cllgName);
}
static String cllgName;
}
// static counter to set unique roll no // Driver class
static int counter = 0; public class StaticDemo {
public Student(String name) public static void main(String[] args)
{ {
[Link] = name; // calling static method
// without instantiating Student class
[Link] = setRollNo();
[Link]("XYZ");
}
// getting unique rollNo Student s1 = new Student("Alice");
// through static variable(counter) Student s2 = new Student("Bob");
static int setRollNo()
{ [Link]();
[Link]();
counter++;
}
return counter; }
}
// static method
static void setCllg(String name) { cllgName = name; }
// instance method
468
Static Class
// A java program to demonstrate use of static keyword with Classes
import [Link].*;
public class SMEC {
private static String str = “Welcome SMEC-VIT";
// Static class
static class MyNestedClass {
// non-static method
public void disp(){
[Link](str);
}
}
public static void main(String args[])
{
[Link] obj = new [Link]();
[Link]();
}
}
469
Visibility Modifiers
470
Visibility Modifiers and
Accessor/Mutator Methods
By default, the class, variable, or method can be
accessed by any class in the same package.
❑ public
The class, data, or method is visible to any class in any
package.
❑ private
The data or methods can be accessed only by the declaring
class.
The get and set methods are used to read and modify private
properties.
471
The private modifier restricts access to within a class, the default
modifier restricts access to within a package, and the public
modifier enables unrestricted access.
472
The default modifier on a class restricts access to within a package,
and the public modifier enables unrestricted access.
473
NOTE
474
Why Data Fields Should Be
private?
To protect data.
475
Example of
Data Field Encapsulation
Circle
The - sign indicates
private modifier -radius: double The radius of this circle (default: 1.0).
-numberOfObjects: int The number of circle objects created.
476
Passing Objects to Methods
477
Passing Objects to Methods, cont.
478
Array of Objects
Circle[] circleArray = new Circle[10];
480
Array of Objects, cont.
public class TotalArea {
/** Main method */
public static void main(String[] args) {
// Declare circleArray
CircleWithPrivateDataFields[] circleArray;
// Create circleArray
circleArray = createCircleArray();
// Print circleArray and total areas of the circles
printCircleArray(circleArray);
}
/** Create an array of Circle objects */
public static CircleWithPrivateDataFields[] createCircleArray() {
CircleWithPrivateDataFields[] circleArray =
new CircleWithPrivateDataFields[5];
A class with all private data fields and without mutators is not
necessarily immutable. For example, the following class
Student has all private data fields and no mutators, but it is
mutable.
483
Example public class BirthDate {
private int year;
public class Student {
private int month;
private int id;
private BirthDate birthDate; private int day;
484
What Class is Immutable?
485
Scope of Variables
❑The scope of instance and static variables is the
entire class. They can be declared anywhere inside
a class.
❑The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must be
initialized explicitly before it can be used.
486
The this Keyword
❑The this keyword is the name of a reference that refers
to an object itself. One common use of the this keyword
is reference a class’s hidden data fields.
❑Another common use of the this keyword to enable a
constructor to invoke another constructor of the same
class.
487
Reference the Hidden Data Fields
public class F { Suppose that f1 and f2 are two objects of F.
private int i = 5; F f1 = new F(); F f2 = new F();
private static double k = 0;
Invoking [Link](10) is to execute
void setI(int i) { this.i = 10, where this refers f1
this.i = i;
} Invoking [Link](45) is to execute
this.i = 45, where this refers f2
static void setK(double k) {
F.k = k;
}
}
488
Calling Overloaded Constructor
public class Circle {
private double radius;
A super class
B <<class>>
B sub class
A interface
B <<class>>
B sub class
Various Forms of Inheritance
Single Inheritance Hierarchical Inheritance
A A X X
B B A B C A B C
B B
C C
C C
Forms of Inheritance
• Mulitiple Inheritance can be implemented by
implementing multiple interfaces not by extending
multiple classes
Example : A C D
OK
class Z extends A ,B class Z extends A extends B
{ {
WRONG OR WRONG
} }
Defining a Subclass
Syntax :
class <subclass name> extends <superclass name>
{
variable declarations;
method declarations;
Access Location
Non-subclasses in Yes No No
other packages
Inheritance Basics
1. Whenever a sub class object is created ,super class
constructor is called first.
2. If super class constructor does not have any constructor
of its own OR has an unparametrized constructor then it
is automatically called by Java Run Time by using call
super()
3. If a super class has a parameterized constructor then it is
the responsibility of the sub class constructor to call the
super class constructor by call
super(<parameters required by super class>)
4. Call to super class constructor must be the first
statement in sub class constructor
USE OF super KEYWORD
• Can be used to call super class constrctor
super();
super(<parameter-list>);
• Can refer to super class instance
variables/Methods
super.<super class instance variable/Method>
class A File Name is [Link]
{ A()
{
[Link]("This is class A");
} /*
} E:\Java>java inherit1
class B extends A This is class A
{ This is class B
B()
{ E:\Java>
[Link]("This is class B"); */
}
}
class inherit1
{
public static void main(String args[])
{
B b1 = new B();
}
}
class A
{
private A()
{
[Link]("This is class A");
}
}
class B extends A
{
B()
{
[Link]("This is class B");
}
} /*
class inherit2 E:\Java>javac [Link]
{ [Link]: A() has private access
public static void main(String args[]) in A
{ {
B b1 = new B(); ^
} 1 error
}
When super class has a Unparametrized constructor
class A
{
A()
{
[Link]("This is constructor of class A");
}
} // End of class A
class B extends A
{
B()
{
super();
[Link]("This is constructor of class B");
}
} // End of class B
Cont…..
class inhtest
{
public static void main(String args[])
{
B b1 = new B();
}
}
OUTPUT
This is constructor of class A
This is constructor of class B
502
class A
{
private int a;
A( int a)
{
this.a =a;
[Link]("This is
constructor of class A");
}}
class B extends A
{ B b1 = new B(8,10,8.6);
private int b;
private double c;
B(int a,int b,double c)
{
OUTPUT
super(a); This is constructor of class A
this.b=b; This is constructor of class B
this.c=c;
[Link]("This is
constructor of class B");
}}
Example:
The Car class is the parent class and the ElectricCar class is the child class. The Car
class has three properties: make, model, and year. It also has two methods: drive()
and brake(). The ElectricCar class inherits all of the properties and methods of the
Car class. It also has an additional property called batteryCapacity. The ElectricCar
class also overrides the drive() and brake() methods to account for the fact that it is
an electric car.
504
class Car {
public String make;
public String model;
public int year;
505
class ElectricCar extends Car {
public int batteryCapacity;
@Override
public void drive() {
[Link]("The electric car is driving.");
[Link]("The car is using its battery to power the wheels.");
}
@Override
public void brake() {
[Link]("The electric car is braking.");
[Link]("The car is using its regenerative braking system to recharge
the battery.");
}
} 506
public class Main {
public static void main(String[] args) {
Car car = new Car("Tesla", "Model S", 2023);
[Link]();
[Link]();
507
DYNAMIC METHOD DISPATCH
• Dynamic method dispatch is a mechanism
by which a call to an overridden method is
resolved at runtime.
• This is how java implements runtime
polymorphism.
Upcasting in Java
• When Parent class reference variable
refers to Child class object, it is known
as Upcasting.
class Game
{
public void type()
{
[Link]("Indoor & outdoor");
}
}
Class Cricket extends Game
{
public void type()
{
[Link]("outdoor game");
}
Points to Remember
➢ An abstract class must be declared with an abstract keyword.
➢ It can have abstract and non-abstract methods.
➢ It cannot be instantiated.
➢ It can have constructors and static methods also.
➢ It can have final methods which will force the subclass not to
change the body of the method.
abstract class Bank class TestBank
{ {
abstract int getRateOfInterest(); public static void main(String args[])
{
}
Bank b;
class SBI extends Bank b=new SBI();
{
int getRateOfInterest() [Link]("Rate of Interest is: "+b.
{ getRateOfInterest()+" %");
return 7;
b=new PNB();
} [Link]("Rate of Interest is: "+b.
} getRateOfInterest()+" %");
class PNB extends Bank }
{ }
int getRateOfInterest()
{
return 8;
}
}
public abstract class Animal
{
abstract void makeSound();
}
public class Cow extends Animal public class Dog extends Animal
{ {
public void makeSound() public void makeSound()
{ {
[Link]("Moo-Moo"); [Link](“Wuf-Wuf");
} }
} }
• Focuses on:
▪ defining polymorphism and its benefits
▪ using inheritance to create polymorphic references
▪ using interfaces to create polymorphic references
▪ using polymorphism to implement sorting and searching
algorithms
▪ additional GUI components
Polymorphism
• The term polymorphism literally means "having
many forms"
Holiday
Holiday day;
day = new Christmas();
Christmas
References and Inheritance
• Assigning a child object to a parent reference is
considered to be a widening conversion, and can
be performed by simple assignment
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
public abstract class Animal
{
abstract void makeSound();
public void move() Define a new method
{ which is not
[Link](“walk”); abstract and is
} inherited by all
} children.
public class Cow extends Animal public class Dog extends Animal
{ {
public void makeSound() public void makeSound()
{ {
[Link]("Moo-Moo"); [Link](“Wuf-Wuf");
} }
} }
public class Cow extends Animal public class Dog extends Animal
{ {
public void makeSound() public void makeSound()
{ {
[Link]("Moo-Moo"); [Link](“Wuf-Wuf");
} }
} }
StaffMember
Volunteer Employee
Executive Hourly
Employee Class Hierarchy
INTERFACES
Interfacesin Java
● In the Java programming language, an interface is a reference
type, similar to a class, that can contain only constants, method
signatures, and nested types.
● Interface interfacename
{
Method Declarations..
…………………..
}
Example :
Interface Bicycle
{
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
● Once it is defined, any number of classes can implement an
interface. Also, one class can implement any number of
interfaces.
● To implement an interface, a class must create the complete
set of methods defined by the interface.
● By providing the interface keyword, Java allows you to fully
utilize the “one interface, multiple methods” aspect of
polymorphism.
● Interfaces are designed to support dynamic method resolution
at run-time.
Defining an Interface
● An interface is defined much like a class. This is the general
form of an interface:
● Variables can be declared inside of interface
declarations.
● They are implicitly final and static, meaning they cannot
be changed by the implementing class.
● They must also be initialized with a constant value. All
methods and variables are implicitly public if the interface,
itself, is declared as public.
● Example declares a simple interface which contains one
method called callback( ) that takes a single integer
parameter.
interface Callback
{
void callback(int param);
}
● To implement an interface, include the implements clause in
a class definition, and then create the methods defined by the
interface. The general form of a class that includes the
implements clause looks like this:
accessclassclassname[extendssuperclass]
[implements interface [,interface...]] {
/ / class-body }
● The methods that implement an interface must be declared
public.
● Type signature of the implementing method must match exactly
the type signature specified in the interface definition.
● class that implements the Callback interface
classClient implementsCallback
{
/ / Implement Callback'sinterface
publicvoid callback(int p)
{
[Link]("callback called with " + p);}
}
● classes that implement interfaces can define additional members
of their own.
classClient implementsCallback {
/ / Implement Callback'sinterface
publicvoid callback(int p) {
[Link]("callback called with " + p);
}
● Applying Interfaces
/ / Define an integer stack interface.
interface IntStack {
void push(int item); / / store an item
int pop(); / / retrieve an item
}
/ / An implementation of IntStack that uses fixed storage.
class FixedStack implements IntStack {
private int stck[];
private int tos;
/ / allocate and initialize stack
FixedStack(int size) {
stck = new int[size];
tos = -1; }
/ / Push an item onto the stack
public void push(int item) {
if(tos==[Link]-1) / / use length member
[Link]("Stack is full.");
else
stck[++tos] = item;
}
/ / Pop an item from the stack
public int pop() {
if(tos < 0) {
[Link]("Stack underflow.");
return 0; }
else
return stck[tos--]; } }
class IFTest {
public static void main(String args[]) {
FixedStack mystack1 = new FixedStack(5);
FixedStack mystack2 = new FixedStack(8);
/ / push some numbers onto the stack
for(int i= 0; i< 5; i+ +) [Link](i);
for(int i= 0; i< 8; i+ +) [Link](i);
/ / pop those numbers off the stack
[Link]("Stack in mystack1:");
for(int i= 0; i< 5; i+ +)
[Link]([Link]());
[Link]("Stack in mystack2:");
for(int i= 0; i< 8; i+ +)
[Link]([Link]());
} }
Nested Interfaces
● An interface can be declared a member of a class or another
interface. Such an interface is called a member interface or a nested
interface.
● Anested interface can bedeclaredaspublic,private, or protected.
● This differs from a top-level interface, which must either be
declared as public or use the default access level, as previously
described.
● When a nested interface is used outside of its enclosing scope, it
must be qualified by the name of the class or interface of which
it is a member.
Interfaces Can Be Extended:
● One interface can inherit another by use of the keyword extends.
The syntax is the same asfor inheriting [Link] aclass
implements an interface that inherits another interface, it must
provide implementations for all methods defined within the
interface inheritance chain.
/ / One interface an extend another.
interfaceA{
void meth1();
void meth2(); }
/ / Bnow includes meth1() and meth2() -- it adds meth3().
interface BextendsA{
void meth3(); }
Exception handling
• Errors arise unexpectedly and can result in disrupting the normal flow of
execution. This is something that every programmer faces at one point
or the other while coding.
• Java, being the most prominent object-oriented language, provides a
powerful mechanism to handle these errors/exceptions.
What happens if exceptions are not handled?
• When an exception occurs, and if you don’t handle it, the program will
terminate abruptly (the piece of code after the line causing the
exception will not get executed).
Introduction to Exception Handling
An exception is a problem that arises during the execution of a program. It can
occur for various reasons say-
• A user has entered an invalid data
• File not found
• A network connection has been lost in the middle of communications
• The JVM has run out of a memory
Exception Handling mechanism follows a flow which is depicted in the below
figure. But if an exception is not handled, it may lead to a system failure. That
is why handling an exception is very important.
Exceptions Hierarchy
All exception and error types are subclasses of class Throwable, which is the base
class of hierarchy. One branch is headed by Error which occurs at run-time and other
by Exception that can happen either at compile time or run-time.
• Basically, an Error is used by the Java run-time system (JVM) to indicate
errors that are associated with the run-time environment
(JRE). StackOverflowError is an example of such an error.
• Whereas Exception is used for exceptional conditions that user programs
should catch. NullPointerException is an example of such an exception.
Different types of exceptions
Checked Exception
It is an exception that occurs at compile time, also called compile time exceptions. If some
code within a method throws a checked exception, then the method must either handle
the exception or it must specify the exception using throws keyword.
Unchecked Exception
It is an exception that occurs at the time of execution. These are also called Runtime
Exceptions. In C++, all exceptions are unchecked, so it is not forced by the compiler to
either handle or specify the exception. It is up to the programmers to specify or catch the
exceptions.
Basic Example of Exception
class Exception{
public static void main(String args[]){
try{
//code that may raise exception
}
catch(Exception e){
// rest of the program
}
}
}
Types of Exceptions
[Link]-in Exceptions
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a
certain situation. In such cases, a user can also create exceptions
which are called ‘User-Defined Exceptions’.
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
catch block
A catch block is where you handle the exceptions. This block must follow the try block
and a single try block can have several catch blocks associated with it. You can catch
different exceptions in different catch blocks. When an exception occurs in a try block,
the corresponding catch block that handles that particular exception executes.
A finally block contains all the crucial statements that must be executed whether an exception occurs
or not. The statements present in this block will always execute, regardless an exception occurs in the
try block or not such as closing a connection, stream etc.
class SampleFinallyBlock{
public static void main(String args[]){
try{
int data=55/5;
[Link](data);
}
catch(NullPointerException e)
{[Link](e);}
finally {[Link]("finally block is executed");}
[Link]("remaining code");
}
}
final vs finally vs finalize
Example:
//Java throw example
void a()
{
throw new ArithmeticException("Incorrect");
}
//Java throws example
void a()throws ArithmeticException
{
//method code
}
//Java throw and throws example
void a()throws ArithmeticException
{
throw new ArithmeticException("Incorrect");
}
Example:
“public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18
years old.");
}
else {
[Link]("Access granted - You are old enough!");
}
}
a/b/c/[Link]
• Can include:
• the current "working directory" from which you ran javac
/ java
• other folders
• JAR archives
• URLs
• ...
Example:
package [Link];
public class Ghost extends Sprite {
...
}
Example:
package [Link];
import [Link].*;
public class PacManGui {
...
Ghost blinky = new Ghost();
}
Example:
package [Link];
import [Link];
public class PacManGui {
Ghost blinky = new Ghost();
}
Example:
import static [Link].*;
...
double angle = sin(PI / 2) + ln(E * E);
Example:
[Link] console =
new [Link]([Link]);