[Go to site: main page, start]

0% found this document useful (0 votes)
11 views584 pages

Problem Solving Using Java

The document outlines the course BACSE102: Problem Solving using Java, led by Dr. R. Bharanidaran, detailing course objectives, outcomes, and assessment rubrics. It includes instructions for installing the Java IDE Eclipse, problem-solving techniques, and the use of Problem Analysis Charts (PAC) and pseudocode for programming tasks. Additionally, it covers fundamental programming concepts such as procedural and object-oriented programming, including inheritance and class structures.

Uploaded by

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

Problem Solving Using Java

The document outlines the course BACSE102: Problem Solving using Java, led by Dr. R. Bharanidaran, detailing course objectives, outcomes, and assessment rubrics. It includes instructions for installing the Java IDE Eclipse, problem-solving techniques, and the use of Problem Analysis Charts (PAC) and pseudocode for programming tasks. Additionally, it covers fundamental programming concepts such as procedural and object-oriented programming, including inheritance and class structures.

Uploaded by

SHORYA Jain
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BACSE102

Problem Solving using Java


• Dr. [Link]
• Professor
• Department of Design and Automation
• School of Mechanical Engineering
Course Objective
Course Outcomes
Rubrics
Note: Preliminary plan for the Course
Sl. No Exams Marks Weightage Module
1 PAT 1 10 10 Java Basics, Loops
2 PAT 2 10 10 Module 12
3 PAT 3 10 10 Module 1 - 3
4 Mid-Term 50 20 Module 1 - 5
5 PAT 4 20 10 Module 1- 6
6 FAT 50 40 Module 1 - 7
Note
• Do not miss any class, practice problem, assessments
and challenging tasks.

• Be ethical and professional throughout the course

• Unethical practices are punishable

Important: No Re-exam

Exams will be conducted through

[Link]
JAVA - IDE
JAVA - Eclipse
Step 1) Installing Eclipse Open your browser and type [Link]

Step 2) Click on “Download” button.


JAVA - Eclipse
Step 3) Click on “Download 64 bit” button

Step 4) Click on “Download” button


JAVA - Eclipse
Step 4) Install Eclipse.
[Link] on “downloads” in Windows file explorer.
[Link] on “[Link]” file.

Step 5) Click on Run button


JAVA - Eclipse
Step 6) Click on “Eclipse IDE for Java Developers”
JAVA - Eclipse
Step 7) Click on “INSTALL” button
JAVA - Eclipse
Step 8) Click on “LAUNCH” button.
JAVA - Eclipse
Step 9) Click on “Launch” button.
JAVA - Eclipse
Step 10) Click on “Create a new Java project” link.
JAVA - Eclipse
Step 11) Create a new Java
Project:
[Link] project name.
[Link] on “Finish button”.
JAVA - Eclipse
Step 12) Create Java Package.
[Link] “src”.
[Link] on “New”.
[Link] on “Package”.
JAVA - Eclipse
Step 13) Writing package name.
[Link] name of the package
[Link] on Finish button.
JAVA - Eclipse
Step 14) Creating Java Class
[Link] on package you have created.
[Link] on “New”.
[Link] on “Class”.
JAVA - Eclipse
Step 15) Defining Java Class.
[Link] class name
[Link] on “public static void main
(String[] args)” checkbox.
[Link] on “Finish” button.
JAVA - Eclipse
[Link] file will be created as shown below:
JAVA - Eclipse

Reference: [Link]
Step 16) Click on “Run” button.

Output will be displayed as shown below.


Problem Solving Techniques
Problem Solving: Definition
• It is a process of identifying the problem,
developing an algorithm or approach, then
converting algorithm into computer code or
program

• Programming is a problem-solving activity.

• Program - Instruction for the computer to solve


something for you.
Problem?
Problem to Solution
Input
List of Data provided

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

Given Data Required Result


Radius r Area of the Circle

Process Required Solution Alternative


Area = pi * r^2 1. R as constant
2. R can be a User input
Problem Analysis Chart (PAC)
2. A program is required to find the volume of a
cuboid. Please construct the PAC for this problem.

Input Output
Length (l) Volume (V)
breadth (b)
width(w)

Process Required Solution Alternative


V = l*b*w 1. l, b, w as constant
2. User input
Problem Analysis Chart (PAC)
3. Write a Problem Analysis Chart (PAC) to convert the distance
in miles to kilometers where 1.609 kilometers per mile.

Given Data Required Result


Distance (d) in miles Distance (D) Kilometer
Fac = 1.609

Process Required Solution Alternative


D = d*Fac 1. d can be a constant
2. d can be a user input
Problem Analysis Chart (PAC)
4. Write a Problem Analysis Chart (PAC) to find an area of a
rectangle where area = height * length.

Given Data Required Result

Process Required Solution Alternative


Pseudocode
• It is a simpler version of a programming code in plain English
which uses short phrases to write code for a program before
it is implemented in a specific programming language.
• It does not have a specific syntax like any of the programming
languages and thus cannot be executed on a computer.
• Many time algorithms are presented using pseudocode since
they can be read and understood by programmers who are
familiar with different programming languages
Pseudocode
• Pseudocode allows you to include several control structures
such as While, If-then-else, Repeat-until, for and case, which is
present in many high-level languages.
Keywords : INPUT, COMPUTE,PRINT, INCREMENT, DECREMENT,
IF/ELSE, WHILE, TRUE/FALSE
Advantages of Pseudocode
❑ Reduced complexity
❑ Increased flexibility
❑ Ease of understanding
Pseudocode
• The programming process is a complicated one.
• You must first understand the program specifications.
• Then you need to organize your thoughts and create
the program.
• You must break the main tasks that must be
accomplished into smaller ones in order to be able
to eventually write fully developed code.
• Writing Pseudocode will save you time later during
the construction & testing phase of a program's
development.
Example
Write a pseudocode to display the sum of two numbers
entered by user.
input num1
input num2
COMPUTE Result = num1 + num2
PRINT Result
Example: Count and display the vowels in the strings.

Sample Test Case:

Input:
Enter strings = Hello Patrick Jane

Output:
Total 6
a2
e2
i1
o1

Dr.R. Bharanidaran, SMEC, VIT


PAC Chart
Given Data Required Result

Display Total
Input String
Display each vowels count

Process Required Solution Alternatives

Create a string with vowel


Run loop to count vowel in string Can use list data type
Count the vowel individually

Dr.R. Bharanidaran, SMEC, VIT


Pseudocode
Get input <- string
Convert string lower case
Vow = ‘aeiou’
Count = 0
Loop var in string
Check var in Vow
then count = count+1
Display Count
Loop var2 in Vow
Count multiples of var2 in string != o
Then display var2 and its count

Dr.R. Bharanidaran, SMEC, VIT


Three Basic Language Structures

• 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

Given Data Required Result


n1 Display Odd or Even

Process Required Solution Alternative


If n1% 2 == 0 [% modulus]
even number
Else
odd Number
Pseudocode
PRINT "Enter the Number"
INPUT number
IF number MOD 2 == 0 THEN
PRINT "Number is Even"
ELSE
PRINT "Number is Odd"
Flow Chart
START

Input num1

Is
Yes num1 No
Mod
2==0?

Print “Even” Print “Odd”

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

Process Required Solution Alternative


n value
I = 0 [Start]
While (i<=n)
Print I
i = i+1
End While
Pseudocode
PRINT "Enter the Number"
INPUT n
i= 0
WHILE (I <= n)
PRINT i
i= i+1
END WHILE
Programming Or Implementation Phase

Transcribing the logical flow of solution steps in flowchart


or algorithm to program code and run the program code
on a computer using a programming language.

1. Coding.
2. Compiling.
Programming phase takes 5 3. Debugging.
stages: 4. Run or Testing.
5. Documentation and
maintenance.
CODING

COMPILE THE MAKE


PROGRAM CORRECTION

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.

• Procedures, also known as routines, subroutines or functions,


simply consist of a series of computational steps to be carried
out.

• During a program’s execution, any given procedure might be


called at any point, including by other procedures or itself.

• Languages used in Procedural Programming:


• FORTRAN, ALGOL, COBOL,
• BASIC, Pascal and C.
Procedure Oriented Programming

Main Program

Function 1 Function 2

Function 3 Function 4 Function 5


Object Oriented Programming (OOPs) Paradigm

• Object-Oriented Programming System (OOPs) is a programming


concept that works on the principles of abstraction,
encapsulation, inheritance, and polymorphism.

• It allows users to create objects they want and create methods to


handle those objects.

• The basic concept of OOPs is to create objects, re-use them


throughout the program, and manipulate these objects to get
results.

• OOP meaning “Object Oriented Programming” is a popularly


known and widely used concept in modern programming
languages like Java.
OOPs

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.

• Let us do discuss pre-requisites by polishing concepts of


methods declaration and passing.

• Starting off with the method declaration, it consists of six


components:
Object Oriented Programming (OOPs) Paradigm
• Access Modifier: Defines access type of the method i.e. from
where it can be accessed in your application. In Java, there 4 type
of the access specifiers.
• public: accessible in all class in your application.
• protected: accessible within the package in which it is defined
and in the situation subclass (es) (including subclasses
declared outside the package)
• private: accessible only within the class in which it is defined.
• default (declared/defined without using any
modifier): accessible within same class and package within
which its class is defined.
Object Oriented Programming (OOPs) Paradigm

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

Java code can be executed on multiple platforms, for example, Windows,


Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere (WORA).
Features of Java
Secured
Java is best known for its security. With Java, we can develop
virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
Features of Java
• Classloader: Classloader in Java is a part of the Java Runtime Environment
(JRE) which is used to load Java classes into the Java Virtual Machine
dynamically. It adds security by separating the package for the classes of
the local file system from those that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can
violate access rights to objects.
• Security Manager: It determines what resources a class can access such
as reading and writing to the local disk.
Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS,
Cryptography, etc.
Features of Java
Robust
The English mining of Robust is strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on
the Java Virtual Machine to get rid of objects which are not
being used by a Java application anymore.
• There are exception handling and the type checking
mechanism in Java. All these points make Java robust.
Features of Java
Architecture-neutral
Java is architecture neutral because there are no implementation
dependent features, for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages
because Java bytecode is "close" to native code. It is still a little bit slower
than a compiled language (e.g., C++). Java is an interpreted language that
is why it is slower than compiled languages, e.g., C, C++, etc.
Features of Java
Distributed
Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating distributed
applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write
Java programs that deal with many tasks at once by defining multiple
threads. The main advantage of multi-threading is that it doesn't occupy
memory for each thread. It shares a common memory area. Threads are
important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It
means classes are loaded on demand. It also supports functions from its
native languages, i.e., C and C++.
JAVA Programming Model
Java Virtual Machine
• Java Virtual Machine is a Virtual Machine that allows a computer
system to run/execute Java Programs.
• JVM is an engine, which works as a runtime environment for Java code.
JVM converts the java code into machine language. When you run a
compiled .class file, it goes to JVM, and then JVM returns the output.
• Java Virtual Machine is a part of JRE, which stands for “Java Runtime
Environment”.
• Basic tasks for a Java Virtual Machine consist of Loading the code, then
verifying the code, and executing the code.
• Also, provide the runtime environment for code execution. JVM
consists of various components like Classloader, List of space assigned
by JVM like Stack, an Execution Engine, and a few native libraries.
The architecture of Java Virtual Machine

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.

Initializing: This is the final part of ClassLoader. Original values are


assigned to all the static variables, followed by the execution of Static
Block. This part executes from the top to the bottom of a class.
Heap
Details of an object and instance variables are all stored here. It is a shared memory area,
which means the data stored here is not thread-safe.

Exception in thread “main” [Link]: Java heap space

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.

Native Method Stack

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

JNI simply interacts with the below-mentioned Native Method Libraries,


which are of C, C++ implementation, and provide the same to the
execution engine. Direct Access to assembly code is allowed by JNI. For a
JVM, Java and Native are the two types of codes. The JNI smoothly
establishes a well-defined link between these two.

Native Method Libraries


Collection of Native Libraries, as required by the Execution Engine.
Execution Engine
Well, now we have a java program into bytecode, which is being assigned to
the above-explained data areas via a class loader, and now the bytecode will
be executed by the execution engine.
Execution Engine simply reads the bytecode in units, like a machine reading
code lines one by one.
The bytecode is a human-readable format, which is why the machine cannot
read it as it is and needs to be converted to a machine-readable format,
where the below components are utilized for the interpretation purpose.
The Execution Engine has three major components, which are Interpreter, JIT
Compiler, and a Garbage Collector.
The execution engine executes the .class file and reads the byte-code line by line. It
contains:
•A virtual processor.
•An interpreter that translates the bytecode line by line and executes.
•Just-In-Time (JIT) compiler: It compiles the bytecode and changes it into native code.
Features of Java
1. Interpreter
• Simply executes the bytecode in a sequential method.
• A command-line query makes a call with a compiled file as an argument.
• The interpreter is quite quick in interpreting and executing commands one
by one, which happens faster than the JIT compiler to compile the code.
java class name
• A main() class is must in a compiled .class file.

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

Data – Type Size Description

Byte (8 bit) 1 byte Stores whole numbers from -128 to 127

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

short 2 bytes Stores whole numbers from -32,768 to 32,767

long 8 bytes Stores whole numbers from -9,223.372,036.854,775.808 to


9,223.372,036,854,775,808

char 2 bytes Stores a single character/letter

boolean 1 byte Stores true or false values

float 4 bytes Stores fractional numbers from 3.4e−038 to 3.4e+038. Sufficient


for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers from 1.7e−308 to 1.7e+038. Sufficient


for storing 15 decimal digits
Integer

BYTE
• Byte stores from -128 and 127.

• Can be used instead of int or other integer types to save memory.

byte myNum = 100;


[Link](myNum);

SHORT
short myNum = 5000;
[Link](myNum);
INT
• int stores from -2147483648 to 2147483647.

• preferred data type when we create variables with a numeric value.

int myNum = 100000;


[Link](myNum);

LONG
• long stores from -9223372036854775808 to
9223372036854775808.

• Used when int is not large enough to store the value.

• you should end the value with an "L":

long myNum = 15000000000L;


[Link](myNum);
Floating Point Types
FLOAT
• float can store fractional numbers from 3.4e−038 to 3.4e+038.

• should end the value with an "f":


float myNum = 5.75f;
[Link](myNum);

DOUBLE
• Double can store fractional numbers from 1.7e−308 to 1.7e+038.

• you should end the value with a "d":


double myNum = 19.99d;
[Link](myNum);
Scientific Numbers
A floating point number can also be a scientific number with an "e"
to indicate the power of 10:

float f1 = 35e3f;
double d1 = 12E4d;
[Link](f1);
[Link](d1);

Use float or double?

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

• declared with the boolean keyword

• can only take the values true or false:

boolean isJavaFun = true;


boolean isFishTasty = false;
[Link](isJavaFun);
[Link](isFishTasty);
String
• The String data type is used to store a sequence of characters (text).

• String values must be surrounded by double quotes:

String greeting = "Hello World";


[Link](greeting);

Character
• The char data type is used to store a single character.

• A char value must be surrounded by single quotes, like 'A' or 'c':

char myGrade = 'B';


[Link](myGrade);
Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to
objects.
The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java. Non-primitive
types are created by the programmer and is not defined by Java (except
for String).
• Non-primitive types can be used to call methods to perform certain
operations, while primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types
starts with an uppercase letter.
• The size of a primitive type depends on the data type, while non-
primitive types have all the same size.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.
VARIABLES
What is a variable ?
• A variable which holds value, during the life of a Java program.
• Every variable is assigned a data type which designates the type and
quantity of value it can hold.
• Variable is a memory location name of the data.
• In order to use a variable in a program you to need to perform 2 steps
• Variable Declaration
• Variable Initialization
• Variable is a name of memory location. There are three types of
variables in java: local, instance and static.
VARIABLES
• A variable is a name given to a memory location. It is the basic
unit of storage in a program.
• The value stored in a variable can be changed during
program execution.
• A variable is only a name given to a memory location, all
the operations done on the variable effects that memory
location.
• In Java, all the variables must be declared before use.
Variable Declaration
To declare a variable, you must specify the data type & give the variable a
unique name.

Variable-
Data-type
name

int count;
Variable Initialization
To initialize a variable, you must assign it a valid value.

You can combine variable declaration and initialization.


int count=100;
TYPES OF VARIABLES
Types of Variables
1) Local Variable
• Local Variables are a variable that are declared inside the body of a method.
• Valid only within that method
• A local variable cannot be defined with "static" keyword.
2) Instance Variable
• A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.
• It is called an instance variable because its value is instance-specific and is not
shared among instances.
3) Static variable
• A variable that is declared as static is called a static variable. It cannot be local.
• You can create a single copy of the static variable and share it among all the
instances of the class.
• Memory allocation for static variables happens only once when the class is
loaded in the memory.
Consider this code snippet
NAMING CONVENTION OF VARIABLES
The general rules for naming variables are:
• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter
• Names should start with a lowercase letter and it cannot contain
whitespace
• Names can also begin with $ and _
• Names are case sensitive ("myVar" and "myvar" are different
variables)
• Reserved words (like Java keywords, such as int or boolean) cannot
be used as names
Non-static variable V/S Static variable
Non-static variable Static variable

1. Memory is allocated multiple time 1. Memory is allocated for these


whenever a new object is created. variable only once in the program.
2. Non-static variable also known as 2. Memory is allocated at the time
instance variable while because of loading of class so that these
memory is allocated whenever are also known as class variable.
instance is created. 3. Static variable are common for
3. Non-static variable are specific to every object that means there
an object memory location can be sharable
4. Non-static variable can access by every object reference or same
with object reference. class.
4. Static variable can access with
class reference.
Java Variable Example: Add Two Numbers
Java Variable Example: Widening
RULES FOR WIDENING PRIMITVE CONVERSION

• The result of adding Java chars, shorts or bytes is an int.


• If either operand is of type double, the other is converted to
double.
• Otherwise, if either operand is of type float, the other is
converted to float.
• Otherwise, if either operand is of type long, the other is
converted to long.
• Otherwise, both operands are converted to type int
Consider this code snippet

public class Test Can you predict the output?


{
public static void main(String[] args) YOLO
{
[Link]("Y" + "O");
[Link]('L' + 'O'); YO155
}
}
Now, try to predict the output

public class Test


{
public static void main(String[] args) YO7679
{
[Link]("Y" + "O");
YOLO
[Link]('L');
[Link]('O');
}
}
NARROWING OR EXPLICIT TYPE-CASTING

If we want to assign a value of larger data type to a smaller data


type we perform explicit type casting or narrowing.

• This is useful for incompatible data types where automatic


conversion cannot be done.

• Here, target-type specifies the desired type to convert the specified


value to.
Guess the output
public class Test
{
public static void main(String[] argv)
{
char ch = 'c'; Error
int num = 88;
ch = num;
}
}
Now, try to predict the output
class Simple
{
public static void main(String[] args)
{
10.5
float f=10.5f; 10
//int a=f;//Compile time error
int a=(int)f;
[Link](f);
[Link](a);
}
}
Java Variable Example: Narrowing (Typecasting)
Java Variable Example: Overflow
Java Variable Example: Adding Lower Type
Java Naming Convention
Identifiers Type Naming Rules Examples

Class It should start with the uppercase letter. public


It should be a noun such as Color, Button, class Employee
System, Thread, etc. {
Use appropriate words, instead of acronyms. //code snippet
}

Interface It should start with the uppercase letter. interface Printable


It should be an adjective such as Runnable, {
Remote, ActionListener. //code snippet
Use appropriate words, instead of acronyms. }
Identifiers Type Naming Rules Examples

Method It should start with lowercase letter. class Employee


It should be a verb such as main(), print(), {
println(). // method
If the name contains multiple words, start it with void draw()
a lowercase letter followed by an uppercase {
letter such as actionPerformed(). //code snippet
}
}
Variable It should start with a lowercase letter such as id, class Employee
name. It should not start with the special {
characters like & (ampersand), $ (dollar), _ // variable
(underscore). If the name contains multiple int id;
words, start it with the lowercase letter followed //code snippet
by an uppercase letter such as firstName, }
lastName. Avoid using one-character variables
such as x, y, z.
Identifiers Type Naming Rules Examples

Package It should be a lowercase letter such as //package


java, lang. If the name contains multiple package [Link];
words, it should be separated by dots (.) class Employee
such as [Link], [Link]. {
//code snippet
}

Constant It should be in uppercase letters such as class Employee


RED, YELLOW. {
If the name contains multiple words, it //constant
should be separated by an underscore(_) static final int MIN_AGE =
such as MAX_PRIORITY. 18;
It may contain digits but not as the first //code snippet
letter. }
Operators in Java
Java AND Operator Example: Logical && and Bitwise &
Java OR Operator Example: Logical || and Bitwise |
Java Ternary Operator Example
Java Ternary Operator Example
Java Assignment Operator Example
Java Assignment Operator Example: Adding short
Example
Conditional Control Statements in Java
Conditional control statements in java
Relational Operators
Java Mathematics Name Example Result
Operator Symbol (radius is 5)

< < less than radius < 0 false


<= ≤ less than or equal to radius <= 0 false
> > greater than radius > 0 true
>= ≥ greater than or equal to radius >= 0 true
== = equal to radius == 0 false
!= ≠ not equal to radius != 0 true
One-way if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { [Link]("The area"
statement(s);
} + " for the circle of radius "
+ radius + " is " + area);
}
Note
if i > 0 { if (i > 0) {
[Link]("i is positive"); [Link]("i is positive");
} }
(a) Wrong (b) Correct

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;

[Link]("The area for the “


+ “circle of radius " + radius +
" is " + area);
}
else {
[Link]("Negative input");
}
Multiple Alternative if Statements

if (score >= 90.0) if (score >= 90.0)


[Link]("A"); [Link]("A");
else else if (score >= 80.0)
if (score >= 80.0) Equivalent [Link]("B");
[Link]("B"); else if (score >= 70.0)
else [Link]("C");
if (score >= 70.0) else if (score >= 60.0)
[Link]("C"); [Link]("D");
else else
if (score >= 60.0) [Link]("F");
[Link]("D"); This is better
else
[Link]("F");

(a) (b)
Multi-Way if-else Statements
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


[Link]("A");
else if (score >= 80.0)
[Link]("B");
else if (score >= 70.0)
[Link]("C");
else if (score >= 60.0)
[Link]("D");
else
[Link]("F");
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


[Link]("A");
else if (score >= 80.0)
[Link]("B");
else if (score >= 70.0)
[Link]("C");
else if (score >= 60.0)
[Link]("D");
else
[Link]("F");
Trace if-else statement
Suppose score is 70.0 The condition is true

if (score >= 90.0)


[Link]("A");
else if (score >= 80.0)
[Link]("B");
else if (score >= 70.0)
[Link]("C");
else if (score >= 60.0)
[Link]("D");
else
[Link]("F");
Trace if-else statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


[Link]("A");
else if (score >= 80.0)
[Link]("B");
else if (score >= 70.0)
[Link]("C");
else if (score >= 60.0)
[Link]("D");
else
[Link]("F");
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


[Link]("A");
else if (score >= 80.0)
[Link]("B");
else if (score >= 70.0)
[Link]("C");
else if (score >= 60.0)
[Link]("D");
else
[Link]("F");
Note
The else clause matches the most recent if clause in the
same block.
Note, cont.
Nothing is printed from the preceding statement. To
force the else clause to match the first if clause, you
must add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
[Link]("A");
}
else
[Link]("B");
This statement prints B.
Common Errors
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0);
Wrong
{
area = radius*radius*PI;
[Link](
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is not a compilation error
or a runtime error, it is a logic error.
This error often occurs when you use the next-line block style.
TIP
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)
CAUTION
Equivalent if (even)
if (even == true)
[Link]( [Link](
"It is even."); "It is even.");
(a) (b)
Problem: An Improved Math Learning Tool
This example creates a program to teach a
first grade child how to learn subtractions.
The program randomly generates two single-
digit integers number1 and number2 with
number1 >= number2 and displays a question
such as “What is 9 – 2?” to the student. After
the student types the answer, the program
displays whether the answer is correct.
Problem: Body Mass Index
Body Mass Index (BMI) is a measure of health on weight. It can
be calculated by taking your weight in kilograms and dividing by
the square of your height in meters. The interpretation of BMI for
people 16 years or older is as follows:

BMI Interpretation

BMI < 18.5 Underweight


18.5 <= BMI < 25.0 Normal
25.0 <= BMI < 30.0 Overweight
30.0 <= BMI Obese
Problem: Computing Taxes
The US federal personal income tax is calculated based on the
filing status and taxable income. There are four filing statuses:
single filers, married filing jointly, married filing separately, and
head of household. The tax rates for 2009 are shown below.
Problem: Computing Taxes, cont.
if (status == 0) {
// Compute tax for single filers
}
else if (status == 1) {
// Compute tax for married file jointly
// or qualifying widow(er)
}
else if (status == 2) {
// Compute tax for married file separately
}
else if (status == 3) {
// Compute tax for head of household
}
else {
// Display wrong status
}
Logical Operators
Operator Name Description

! not logical negation

&& and logical conjunction

|| or logical disjunction

^ exclusive or logical exclusion


Truth Table for Operator !

p !p Example (assume age = 24, weight = 140)

true false !(age > 18) is false, because (age > 18) is true.

false true !(weight == 150) is true, because (weight == 150) is false.


Truth Table for Operator &&
p1 p2 p1 && p2 Example (assume age = 24, weight = 140)

false false false (age <= 18) && (weight < 140) is false, because both

conditions are both false.

false true false

true false false (age > 18) && (weight > 140) is false, because (weight

> 140) is false.

true true true (age > 18) && (weight >= 140) is true, because both

(age > 18) and (weight >= 140) are true.


Truth Table for Operator ||
p1 p2 p1 || p2 Example (assume age = 24, weihgt = 140)

false false false

false true true (age > 34) || (weight <= 140) is true, because (age > 34)

is false, but (weight <= 140) is true.

true
true false (age > 14) || (weight >= 150) is false, because

(age > 14) is true.

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

and (weight > 140) is false.

false true true (age > 34) ^ (weight >= 140) is true, because (age > 34) is false

but (weight >= 140) is true.

true false true (age > 14) ^ (weight > 140) is true, because (age > 14) is

true and (weight > 140) is false.

true true false


Examples
Here is a program that checks whether a number is divisible by 2
and 3, whether a number is divisible by 2 or 3, and whether a
number is divisible by 2 or 3 but not both:
Examples
[Link]("Is " + number + " divisible by 2 and 3? " +
((number % 2 == 0) && (number % 3 == 0)));

[Link]("Is " + number + " divisible by 2 or 3? " +


((number % 2 == 0) || (number % 3 == 0)));

[Link]("Is " + number + TestBooleanOperators

TestBooleanOperators
" divisible by 2 or 3, but not both? " + Run

Run
((number % 2 == 0) ^ (number % 3 == 0)));
Companion
Website
The & and | Operators

Supplement III.B, “The & and | Operators”


Companion
Website
The & and | Operators
If x is 1, what is x after this
expression?
(x > 1) & (x++ < 10)

If x is 1, what is x after this


expression?
(1 > x) && ( 1 > x++)

How about (1 == x) | (10 > x++)?


(1 == x) || (10 > x++)?
Problem: Determining Leap Year?
This program first prompts the user to enter a year as
an int value and checks if it is a leap year.
A year is a leap year if it is divisible by 4 but not by
100, or it is divisible by 400.
(year % 4 == 0 && year % 100 != 0) || ( year % 400 == 0)
Problem: Lottery
Write a program that randomly generates a lottery of a
two-digit number, prompts the user to enter a two-digit
number, and determines whether the user wins
according to the following rule:

• If the user input matches the lottery in exact order,


the award is $10,000.
• If the user input matches the lottery, the award is
$3,000.
• If one digit in the user input matches a digit in the
lottery, the award is $1,000.
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file
jointly;
break;
case 2: compute taxes for married file
switch separately;

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.

If operators with the same precedence are next to each


other, their associativity determines the order of
evaluation. All binary operators except assignment
operators are left-associative.
Operator Associativity
When two operators with the same precedence
are evaluated, the associativity of the operators
determines the order of evaluation. All binary
operators except assignment operators are left-
associative.
a – b + c – d is equivalent to ((a – b) + c) – d
Assignment operators are right-associative.
Therefore, the expression
a = b += c = 5 is equivalent to a = (b += (c = 5))
Example
Applying the operator precedence and associativity
rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is
evaluated as follows:

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

•Execute a single statement at a time.


•Trace into or stepping over a method.
•Set breakpoints.
•Display variables.
•Display call stack.
•Modify variables.
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
[Link]("Welcome to Java!");
Statement(s); count++;
} }
animation

Trace while Loop


Initialize count
int count = 0;
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


(count < 2) is true
int count = 0;
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 1 now

while (count < 2) {


[Link]("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


(count < 2) is still true since count
int count = 0; is 1

while (count < 2) {


[Link]("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


Print Welcome to Java
int count = 0;
while (count < 2) {
[Link]("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


Increase count by 1
int count = 0; count is 2 now

while (count < 2) {


[Link]("Welcome to Java!");
count++;
}
animation

Trace while Loop, cont.


(count < 2) is false since count is 2
int count = 0; now

while (count < 2) {


[Link]("Welcome to Java!");
count++;
}
animation

Trace while Loop


The loop exits. Execute the next
int count = 0; statement after the loop.

while (count < 2) {


[Link]("Welcome to Java!");
count++;
}
Problem: Repeat Addition Until Correct

Recall that Listing 3.1 [Link] gives a program


that prompts the user to enter an answer for a question
on addition of two single digits. Using a loop, you can
now rewrite the program to let the user enter a new
answer until it is correct.

IMPORTANT NOTE: If you cannot run the buttons,


see [Link]/liang/[Link].
RepeatAdditionQuiz
Run

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

The Math subtraction learning tool program generates


just one question for each run. You can use a loop to
generate questions repeatedly. This example gives a
program that generates five questions and reports the
number of the correct answers after a student answers all
five questions.

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.

Write a program that reads and calculates the sum of an


unspecified number of integers. The input 0 signifies the
end of the input.

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

Trace for Loop


Declare i
int i;
for (i = 0; i < 2; i++) {
[Link](
"Welcome to Java!");
}
animation

Trace for Loop, cont.


Execute initializer
int i; i is now 0
for (i = 0; i < 2; i++) {
[Link](
"Welcome to Java!");
}
animation

Trace for Loop, cont.


(i < 2) is true
int i; since i is 0
for (i = 0; i < 2; i++) {
[Link]( "Welcome to Java!");
}
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
[Link]("Welcome to Java!");
}
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 1
for (i = 0; i < 2; i++) {
[Link]("Welcome to Java!");
}
animation

Trace for Loop, cont.


(i < 2) is still true
int i; since i is 1
for (i = 0; i < 2; i++) {
[Link]("Welcome to Java!");
}
animation

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
[Link]("Welcome to Java!");
}
animation

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 2
for (i = 0; i < 2; i++) {
[Link]("Welcome to Java!");
}
animation

Trace for Loop, cont.


(i < 2) is false
int i; since i is 2
for (i = 0; i < 2; i++) {
[Link]("Welcome to Java!");
}
animation

Trace for Loop, cont.


Exit the loop. Execute the next
int i; statement after the loop
for (i = 0; i < 2; i++) {
[Link]("Welcome to Java!");
}
Note
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-each-
iteration in a for loop can be a list of zero or more comma-
separated statements. Therefore, the following two for
loops are correct. They are rarely used in practice,
however.
for (int i = 1; i < 100; [Link](i++));

for (int i = 0, j = 0; (i + j < 10); i++, j++) {


// Do something
}
Note
If the loop-continuation-condition in a for loop is omitted,
it is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct. Nevertheless, it is
better to use the equivalent loop in (b) to avoid confusion:

for ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }
(a) (b)
Caution
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic
Error

for (int i=0; i<10; i++);


{
[Link]("i is " + i);
}
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
while (i < 10); Logic Error
{
[Link]("i is " + i);
i++;
}
In the case of the do loop, the following semicolon is
needed to end the loop.
int i=0;
do {
[Link]("i is " + i);
i++;
} while (i<10); Correct
Which Loop to Use?
The three forms of loop statements, while, do-while, and for, are
expressively equivalent; that is, you can write a loop in any of these
three forms. For example, a while loop in (a) in the following figure
can always be converted into the following for loop in (b):
while (loop-continuation-condition) { Equivalent for ( ; loop-continuation-condition; )
// Loop body // Loop body
} }
(a) (b)

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.

Here is an example that sums a series that


starts with 0.01 and ends with 1.0. The
numbers in the series will increment by 0.01,
as follows: 0.01 + 0.02 + 0.03 and so on.
TestSum
Run

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

These hexadecimal digits can be found by successively dividing d by


16 until the quotient is 0. The remainders are h0, h1, h2, ... , hn-2, hn-1,
and hn.
Dec2Hex
Run

Dec2Hex Run
Companion Website

Problem: Monte Carlo Simulation


The Monte Carlo simulation refers to a technique that uses random
numbers and probability to solve problems. This method has a wide
range of applications in computational mathematics, physics,
chemistry, and finance. This section gives an example of using the
Monto Carlo simulation for estimating .
y circleArea / squareArea =  / 4.
1

 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;

while (number < 20) {


number++;
sum += number;
if (sum >= 100)
break;
}

[Link]("The number is " + number);


[Link]("The sum is " + sum);
}
}
continue
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;

while (number < 20) {


number++;
if (number == 10 || number == 11)
continue;
sum += number;
}

[Link]("The sum is " + sum);


}
}
Guessing Number Problem Revisited

Here is a program for guessing a number. You can rewrite


it using a break statement.

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;

• datatype arrayRefVar[]; // This style is


allowed, but not preferred
Example:
double myList[];
Creating Arrays
arrayRefVar = new datatype[arraySize];

Example:
myList = new double[10];

myList[0] references the first element in the array.


myList[9] references the last element in the array.
Declaring and Creating
in One Step
• datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];

• datatype arrayRefVar[] = new


datatype[arraySize];
double myList[] = new double[10];
The Length of an Array
Once an array is created, its size is fixed. It cannot be
changed. You can find its size using

[Link]

For example,

[Link] returns 10
Default Values
When an array is created, its elements are
assigned the default value of

0 for the numeric primitive data types,


'\u0000' for char types, and
false for boolean types.
Indexed Variables
The array elements are accessed through the index.
The array indices are 0-based, i.e., it starts from 0 to
[Link]-1. example, myList holds ten double
values and the indices are from 0 to 9.

Each element in the array is represented using the


following syntax, known as an indexed variable:

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].

myList[2] = myList[0] + myList[1];


Array Initializers

• Declaring, creating, initializing in one step:


double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand syntax must be in one


statement.
Declaring, creating, initializing Using the
Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following
statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
CAUTION
Using the shorthand notation, you have to declare, create,
and initialize the array all in one statement. Splitting it
would cause a syntax error. For example, the following is
wrong:
double[] myList;

myList = {1.9, 2.9, 3.4, 3.5};


animation
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values

public class Test {


public static void main(String[] args) { After the array is created

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) {
1 0
values[i] = i + values[i-1]; 2 0
} 3 0
values[0] = values[1] + values[4]; 4 0

}
}
animation
Trace Program with Arrays
i becomes 1

public class Test {


public static void main(String[] args) {
After the array is created
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 0
values[i] = i + values[i-1]; 1 0

} 2 0

values[0] = values[1] + values[4]; 3 0

4 0
}
}
animation
Trace Program with Arrays
i (=1) is less than 5

public class Test {


public static void main(String[] args) {
int[] values = new int[5]; After the array is created

for (int i = 1; i < 5; i++) {


0 0
values[i] = i + values[i-1]; 1 0
} 2 0

values[0] = values[1] + values[4]; 3 0

} 4 0

}
animation
Trace Program with Arrays
After this line is executed, value[1] is 1

public class Test {


public static void main(String[] args) { After the first iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) {
1 1
values[i] = i + values[i-1]; 2 0
} 3 0

values[0] = values[1] + values[4]; 4 0

}
}
animation
Trace Program with Arrays
After i++, i becomes 2

public class Test {


public static void main(String[] args) {
int[] values = new int[5]; After the first iteration

for (int i = 1; i < 5; i++) { 0 0

values[i] = i + values[i-1]; 1 1

2 0
} 3 0

values[0] = values[1] + values[4]; 4 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

for (int i = 1; i < 5; i++) { 0 0


values[i] = i + values[i-1]; 1 1

} 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)

public class Test {


public static void main(String[] args) { After the second iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) {
1 1
values[i] = i + values[i-1]; 2 3
} 3 0

values[0] = values[1] + values[4]; 4 0

}
}
animation
Trace Program with Arrays
After this, i becomes 3.

public class Test {


public static void main(String[] args) { After the second iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) {
1 1
values[i] = i + values[i-1]; 2 3
} 3 0

values[0] = values[1] + values[4]; 4 0

}
}
animation
Trace Program with Arrays
i (=3) is still less than 5.

public class Test {


public static void main(String[] args) { After the second iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) {
1 1
values[i] = i + values[i-1]; 2 3
} 3 0

values[0] = values[1] + values[4]; 4 0

}
}
animation
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)

public class Test {


public static void main(String[] args) { After the third iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) {
1 1
values[i] = i + values[i-1]; 2 3
} 3 6

values[0] = values[1] + values[4]; 4 0

}
}
animation
Trace Program with Arrays
After this, i becomes 4

public class Test {


public static void main(String[] args) { After the third iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) {
1 1
values[i] = i + values[i-1]; 2 3
} 3 6

values[0] = values[1] + values[4]; 4 0

}
}
animation
Trace Program with Arrays
i (=4) is still less than 5

public class Test {


public static void main(String[] args) { After the third iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) {
1 1
values[i] = i + values[i-1]; 2 3
} 3 6

values[0] = values[1] + values[4]; 4 0

}
}
animation
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)

public class Test {


public static void main(String[] args) { After the fourth iteration

int[] values = new int[5];


0 0
for (int i = 1; i < 5; i++) {
1 1
values[i] = i + values[i-1]; 2 3
} 3 6

values[0] = values[1] + values[4]; 4 10

}
}
animation
Trace Program with Arrays
After i++, i becomes 5

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
After the fourth iteration
values[i] = i + values[i-1];
} 0 0

1 1
values[0] = values[1] + values[4];
2 3
}
3 6
} 4 10
animation

Trace Program with Arrays


i ( =5) < 5 is false. Exit the loop

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) { After the fourth iteration
values[i] = i + values[i-1];
0
} 0

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)

public class Test {


public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) { 0 11
values[i] = i + values[i-1]; 1 1
} 2 3
values[0] = values[1] + values[4]; 3 6
} 4 10
}
Processing Arrays
See the examples in the text.
1. (Initializing arrays with input values)
2. (Initializing arrays with random values)
3. (Printing arrays)
4. (Summing all elements)
5. (Finding the largest element)
6. (Finding the smallest index of the largest element)
7. (Random shuffling)
8. (Shifting elements)
Initializing arrays with input values

[Link] input = new [Link]([Link]);


[Link]("Enter " + [Link] + " values: ");
for (int i = 0; i < [Link]; i++)
myList[i] = [Link]();
Initializing arrays with random values

for (int i = 0; i < [Link]; i++) {


myList[i] = [Link]() * 100;
}
Printing arrays

for (int i = 0; i < [Link]; i++) {


[Link](myList[i] + " ");
}
Summing all elements

double total = 0;
for (int i = 0; i < [Link]; i++) {
total += myList[i];
}
Finding the largest element

double max = myList[0];


for (int i = 1; i < [Link]; i++) {
if (myList[i] > max) max = myList[i];
}
Random shuffling
for (int i = 0; i < [Link] - 1; i++) { myList
// Generate an index j randomly i [0] .
int j = (int)([Link]() [1] .
* [Link]); .
[i] .
// Swap myList[i] with myList[j] .
double temp = myList[i]; . swap
myList[i] = myList[j]; A random index [j]
myList[j] = temp;
}
Shifting Elements
Enhanced for Loop (for-each loop)
JDK 1.5 introduced a new for loop that enables you to traverse the complete array
sequentially without using an index variable. For example, the following code
displays all elements in the array myList:

for (double value: myList)


[Link](value);

In general, the syntax is

for (elementType value: arrayRefVar) {


// Process the value
}

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:

int[] deck = new int[52];


// Initialize cards
for (int i = 0; i < [Link]; i++)
deck[i] = i;
Problem: Deck of Cards, cont.
Problem: Deck of Cards, cont.
Problem: Deck of Cards
This problem builds a foundation for future more interesting and
realistic applications:
[Link]
[Link]
See Exercise 20.15.
Problem: Lotto Numbers
Suppose you play the Pick-10 lotto. Each ticket has 10
unique numbers ranging from 1 to 99. You buy a lot of
tickets. You like to have your tickets to cover all numbers
from 1 to 99. Write a program that reads the ticket
numbers from a file and checks whether all numbers are
covered. Assume the last number in the file is 0.

LottoNumbers
Run

Lotto Numbers Sample Data LottoNumbers Run


Problem: Lotto Numbers
isCovered isCovered isCovered isCovered isCovered

false [0] true [0] true [0] true [0] true


[0]
[1] false [1] false [1] true [1] true [1] true

[2] false [2] false [2] false [2] true [2] true

[3] false [3] false [3] false [3] false [3] false

. . . . .

. . . . .

. . . . .

[97] [97] false [97] false [97] false [97] false


false
[98] [98] false [98] false [98] false [98] true
false

(a) (b) (c) (d) (e)


Copying Arrays
Often, in a program, you need to duplicate an array or a part of an
array. In such cases you could attempt to use the assignment
statement (=), as follows:

list2 = list1;
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[[Link]];

for (int i = 0; i < [Link]; i++)


targetArray[i] = sourceArray[i];
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);

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] + " ");
}
}

Invoke the method

int[] list = {3, 1, 2, 6, 4, 2};


printArray(list);

Invoke the method


printArray(new int[]{3, 1, 2, 6, 4, 2});

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.

• For a parameter of a primitive type value, the actual value is


passed. Changing the value of the local parameter inside the
method does not affect the value of the variable outside the
method.

• For a parameter of an array type, the value of the parameter


contains a reference to an array; this reference is passed to the
method. Any changes to the array that occur inside the method
body will affect the original array that was passed as the
argument.
Simple Example
public class Test {
public static void main(String[] args) {
int x = 1; // x represents an int value
int[] y = new int[10]; // y represents an array of int values

m(x, y); // Invoke m with arguments x and y

[Link]("x is " + x);


[Link]("y[0] is " + y[0]);
}

public static void m(int number, int[] numbers) {


number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
}
Call Stack

When invoking m(x, y), the values of x and y are passed


to number and numbers. Since y contains the reference
value to the array, numbers now contains the same
reference value to the same array.
Call Stack

When invoking m(x, y), the values of x and y are


passed to number and numbers. Since y contains the
reference value to the array, numbers now contains
the same reference value to the same array.
Heap
Heap

The arrays are


5555 stored in a
0 heap.
Space required for the
main method
int[] y: reference
int x: 1 0

The JVM stores the array in an area of memory,


called heap, which is used for dynamic memory
allocation where blocks of memory are allocated and
freed in an arbitrary order.
Passing Arrays as Arguments

• Objective: Demonstrate differences of


passing primitive data type variables and
array variables.

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

Space required for the Space required for the


main method main method
int[] a reference int[] a reference
a[1]: 2
a[0]: 1
Invoke swap(int n1, int n2). Invoke swapFirstTwoInArray(int[] array).
The primitive type values in The arrays are The reference value in a is passed to the
a[0] and a[1] are passed to the stored in a swapFirstTwoInArray method.
swap method. heap.
Returning an Array from a Method
public static int[] reverse(int[] list) {
int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}
list
return result;
} result

int[] list1 = {1, 2, 3, 4, 5, 6};


int[] list2 = reverse(list1);
animation
Trace the reverse Method
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
Declare result and create array
public static int[] reverse(int[] list) {
int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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);

After this, i becomes 1 and j


public static int[] reverse(int[] list) { becomes 4
int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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) is less than 6


public static int[] reverse(int[] list) {
int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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]];

for (int i = 0, j = [Link] - 1;


i < [Link]; i++, j--) {
result[j] = list[i];
}

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

Linear Search Animation


Key List
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

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;
}

Trace the method


int[] list = {1, 4, 4, 2, 5, -3, 6, 2};
int i = linearSearch(list, 4); // returns 1
int j = linearSearch(list, -4); // returns -1
int k = linearSearch(list, -3); // returns 5
Binary Search
For binary search to work, the elements in the array
must already be ordered. Without loss of generality,
assume that the array is in ascending order.
e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79
The binary search first compares the key with the
element in the middle of the array.
Binary Search, cont.
Consider the following three cases:
• If the key is less than the middle element, you
only need to search the key in the first half of the
array.
• If the key is equal to the middle element, the
search ends with a match.
• If the key is greater than the middle element, you
only need to search the key in the second half of
the array.
animation

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

low mid high

[7] [8]
key < 59 list 59 60

low high

[6] [7] [8]


59 60
Binary Search, cont.
The binarySearch method returns the index of the
element in the list that matches the search key if it is
contained in the list. Otherwise, it returns

-insertion point - 1.

The insertion point is the point at which the key would be


inserted into the list.
From Idea to Soluton
/** Use binary search to find the key in the list */
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = [Link] - 1;

while (high >= low) {


int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 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]
}

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

list[0] list[1] list[2] list[3] ... list[10]

...

list[0] list[1] list[2] list[3] ... list[10]


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+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;
}
}

// Swap list[i] with list[currentMinIndex] if necessary;


if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin; Invoke it
}
} selectionSort(yourList)
}
The [Link] Method

Since sorting is frequently used in programming, Java provides several


overloaded sort methods for sorting an array of int, double, char, short,
long, and float in the [Link] class. For example, the following
code sorts an array of numbers and an array of characters.

double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};


[Link](numbers);

char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};


[Link](chars);
Java 8 now provides [Link](list) that utilizes the multicore
for fast sorting.
The [Link](list) Method
The [Link](list) method can be used to return a string
representation for the list.
Main Method Is Just a Regular Method
You can call a regular method by passing actual
parameters. Can you pass arguments to main? Of course,
yes. For example, the main method in class B is invoked
by a method in A, as shown below:

public class A { class B {


public static void main(String[] args) { public static void main(String[] args) {
String[] strings = {"New York", for (int i = 0; i < [Link]; i++)
"Boston", "Atlanta"}; [Link](args[i]);
[Link](strings); }
} }
}
Command-Line Parameters
class TestMain {
public static void main(String[] args) {
...
}
}

java TestMain arg0 arg1 arg2 ... argn


Processing
Command-Line Parameters
In the main method, get the arguments from
args[0], args[1], ..., args[n], which
corresponds to arg0, arg1, ..., argn in
the command line.
Problem: Calculator
• Objective: Write a program that will perform
binary operations on integers. The program
receives three parameters: an operator and two
integers.

java Calculator 2 + 3
java Calculator 2 - 3
Calculator

Calculator java Calculator 2 / 3


Run

Run java Calculator 2 . 3


Declare/Create Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;

// Create array and assign its reference to variable


refVar = new dataType[10][10];

// Combine declaration and creation in one statement


dataType[][] refVar = new dataType[10][10];

// Alternative syntax
dataType refVar[][] = new dataType[10][10];

380
Declaring Variables of Two-dimensional Arrays
and Creating Two-dimensional Arrays

int[][] matrix = new int[10][10];


or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;

for (int i = 0; i < [Link]; i++)


for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)([Link]() * 1000);

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

You can also use an array initializer to declare, create and


initialize a two-dimensional array. For example,

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

int[][] x = new int[3][4];

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

for (int row = 0; row < [Link]; row++) {


for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = (int)([Link]() * 100);
}
}

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

Students’ answer Objective: write a


program that grades
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.

The way to declare two-dimensional array variables and


create two-dimensional arrays can be generalized to
declare n-dimensional array variables and create n-
dimensional arrays for n >= 3.

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}}
};

Which student Which exam Multiple-choice or essay

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.

1 1 76.4 0.92 10 24 98.7 0.74


1 2 77.7 0.93 1 2 77.7 0.93
... ...
10 23 97.7 0.71 10 23 97.7 0.71
10 24 98.7 0.74 1 1 76.4 0.92

(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

int z = max(x, y);


public static int max(int num1, int num2) {
actual parameters
int result; (arguments)

if (num1 > num2)


result = num1;
else
result = num2;

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

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

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

Object-oriented programming (OOP) involves


programming using objects. An object represents an
entity in the real world that can be distinctly
identified. For example, a student, a desk, a circle, a
button, and even a loan can all be viewed as objects.
An object has a unique identity, state, and behaviors.
The state of an object consists of a set of data fields
(also known as properties) with their current values.
The behavior of an object is defined by a set of
methods.
424
Objects

An object has both a state and behavior. The state defines


the object, and the behavior defines what the object does.

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

/** Construct a circle object */


Circle() {
}
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}
427
Unified Modeling Language (UML) Class
Diagram

428
Example: Defining Classes and
Creating Objects

Objective: Demonstrate creating objects, accessing data,


and using methods.

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.

The + sign indicates +TV() Constructs a default TV object.


a public modifier.
+turnOn(): void Turns on this TV.
+turnOff(): void Turns off this TV.
+setChannel(newChannel: int): void Sets a new channel for this TV.
+setVolume(newVolumeLevel: int): void Sets a new volume level for this TV.
+channelUp(): void Increases the channel number by 1.
+channelDown(): void Decreases the channel number by 1.
+volumeUp(): void Increases the volume level by 1.
+volumeDown(): void Decreases the volume level by 1.

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.

To declare a reference variable, use the syntax:

ClassName objectRefVar;

Example:
Circle myCircle;

445
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();

Assign object reference Create an object


Example:
Circle myCircle = new Circle();

446
Accessing Object’s Members
❑Referencing the object’s data:
[Link]
e.g., [Link]

❑Invoking the object’s method:


[Link](arguments)
e.g., [Link]()

447
Caution
Recall that you use
[Link](arguments) (e.g., [Link](3, 2.5))

to invoke a method in the Math class. Can you invoke getArea()


using [Link]()? The answer is no. All the methods
used before this chapter are static methods, which are defined
using the static keyword. However, getArea() is non-static. It
must be invoked from an object using

[Link](arguments) (e.g., [Link]()).

More explanations will be given in the section on “Static


Variables, Constants, and Methods.”

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.

public class Test {


public static void main(String[] args) {
Student student = new Student();
[Link]("name? " + [Link]);
[Link]("age? " + [Link]);
[Link]("isScienceMajor? " + [Link]);
[Link]("gender? " + [Link]);
}
}

451
Example
Java assigns no default value to a local variable inside a
method.

public class Test {


public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
[Link]("x is " + x);
[Link]("y is " + y);
}
}

Compile error: variable not


initialized
452
Differences between Variables of
Primitive Data Types and Object Types

Created using new Circle()


Primitive type int i = 1 i 1

Object type Circle c c reference c: Circle

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

c1: Circle c2: Circle c1: Circle c2: Circle


radius = 5 radius = 9 radius = 5 radius = 9

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

[Link] date = new [Link]();


[Link]([Link]());

displays a string like Sun Mar 09 13:50:19 EST


2003.

456
Input
import [Link];
public class DateDemo {

public static void main(String args[]) {


// Instantiate a Date object
Date date = new Date();

// display time and date using toString()


[Link]([Link]());
}
}

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.

Random random1 = new Random(3);


[Link]("From random1: ");
for (int i = 0; i < 10; i++)
[Link]([Link](1000) + " ");
Random random2 = new Random(3);
[Link]("\nFrom random2: ");
for (int i = 0; i < 10; i++)
[Link]([Link](1000) + " ");

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.

Instance methods are invoked by an instance of the


class.

Instance variables and methods are specified by


omitting the static keyword.

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

An object cannot access its private members, as shown in (b).


It is OK, however, if the object is declared in its own class, as
shown in (a).

474
Why Data Fields Should Be
private?
To protect data.

To make code easy to maintain.

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.

+Circle() Constructs a default circle object.


+Circle(radius: double) Constructs a circle object with the specified radius.
+getRadius(): double Returns the radius of this circle.
+setRadius(radius: double): void Sets a new radius for this circle.
+getNumberOfObjects(): int Returns the number of circle objects created.
+getArea(): double Returns the area of this circle.

476
Passing Objects to Methods

❑Passing by value for primitive type value (the value


is passed to the parameter)
❑Passing by value for reference type value (the
value is the reference to the object)

477
Passing Objects to Methods, cont.

478
Array of Objects
Circle[] circleArray = new Circle[10];

An array of objects is actually an array of


reference variables. So invoking
circleArray[1].getArea() involves two
levels of referencing as shown in the next
figure. circleArray references to the entire
array. circleArray[1] references to a Circle
object.
479
Array of Objects, cont.
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];

for (int i = 0; i < [Link]; i++) {


circleArray[i] =
481 * 100);
new CircleWithPrivateDataFields([Link]()
/** Print an array of circles and their total area */
public static void printCircleArray(
CircleWithPrivateDataFields[] circleArray) {
[Link]("%-30s%-15s\n", "Radius", "Area");
for (int i = 0; i < [Link]; i++) {
[Link]("%-30f%-15f\n", circleArray[i].getRadius(),
circleArray[i].getArea());
}
[Link]("-----------------------------------------");
// Compute and display the result
[Link]("%-30s%-15f\n", "The total areas of circles is",
sum(circleArray));
}
/** Add circle areas */
public static double sum(
CircleWithPrivateDataFields[] circleArray) {
// Initialize sum
double sum = 0;
// Add areas to sum
for (int i = 0; i < [Link]; i++)
sum += circleArray[i].getArea();
return sum;
} 482
}
Immutable Objects and Classes
If the contents of an object cannot be changed once the object
is created, the object is called an immutable object and its class
is called an immutable class. If you delete the set method in
the Circle class, the class would be immutable because radius
is private and cannot be changed without a set method.

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;

public Student(int ssn, public BirthDate(int newYear,


int year, int month, int day) {
int newMonth, int newDay) {
id = ssn;
birthDate = new BirthDate(year, month, day); year = newYear;
} month = newMonth;
day = newDay;
public int getId() {
}
return id;
}
public void setYear(int newYear) {
public BirthDate getBirthDate() { year = newYear;
return birthDate;
}
}
} }

public class Test {


public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3);
BirthDate date = [Link]();
[Link](2010); // Now the student birth year is changed!
}
}

484
What Class is Immutable?

For a class to be immutable, it must mark all data fields private


and provide no mutator methods and no accessor methods that
would return a reference to a mutable data field object.

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;

public Circle(double radius) {


[Link] = radius;
} this must be explicitly used to reference the data
field radius of the object being constructed
public Circle() {
this(1.0);
} this is used to invoke another constructor

public double getArea() {


return [Link] * [Link] * [Link];
}
} Every instance variable belongs to an instance represented by this,
which is normally omitted
489
Inheritance Basics
1. Reusability is achieved by INHERITANCE
2. Java classes Can be Reused by extending a class. Extending
an existing class is nothing but reusing properties of the
existing classes.

3. The class whose properties are extended is known as super


or base or parent class.
4. The class which extends the properties of super class is
known as sub or derived or child class
5. A class can either extends another class or can implement an
interface
class B extends A { ….. } A <<class>>

A super class
B <<class>>
B sub class

class B implements A { ….. } A <<interface>>

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

NOT SUPPORTED BY JAVA


MultiLevel Inheritance Multiple Inheritance
SUPPORTED BY JAVA
A A A B A B

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

class Z extends A implements C , D


{ …………} Z

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;

• Extends keyword signifies that properties of the super


class are extended to sub class
• Sub class will not inherit private members of super class
Access Control
public protected private
Access Modifiers

Access Location

Same Class Yes Yes Yes


sub classes in same Yes Yes No
package

Other Classes in Yes Yes No


Same package

Subclasses in other Yes Yes No


packages

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;

public Car(String make, String model, int year) {


[Link] = make;
[Link] = model;
[Link] = year;
}

public void drive() {


[Link]("The car is driving.");
}

public void brake() {


[Link]("The car is braking.");
}
}

505
class ElectricCar extends Car {
public int batteryCapacity;

public ElectricCar(String make, String model, int year, int batteryCapacity) {


super(make, model, year);
[Link] = 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]();

ElectricCar electricCar = new ElectricCar("Tesla", "Model 3", 2022, 75);


[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");
}

public static void main(String[] args)


{
Game gm = new Game();
Cricket ck = new Cricket();
[Link]();
[Link]();
gm = ck; //gm refers to Cricket object
[Link](); //calls Cricket's version of type
}
}
ABSTRACT CLASS IN JAVA

• A class which is declared as abstract is known as an abstract


class. It can have abstract and non-abstract methods. It needs to be
extended and its method implemented. It cannot be instantiated.
• Abstract class having constructor, data member and methods

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");
} }
} }

public class Duck extends Animal


{
public void makeSound()
{
[Link](“Quack-Quack");
}
}
Polymorphism
Polymorphism
• Polymorphism is an object-oriented concept that
allows us to create versatile software designs

• 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"

• A polymorphic reference is a variable that can


refer to different types of objects at different
points in time

• The method invoked through a polymorphic


reference can change from one invocation to the
next

• All object references in Java are potentially


polymorphic
Polymorphism
• Suppose we create the following reference
variable:
Occupation job;

• Java allows this reference to point to an


Occupation object, or to any object of any
compatible type
• This compatibility can be established using
inheritance or using interfaces
• Careful use of polymorphic references can lead to
elegant, robust software designs
Method Overloading
• The compiler determines which method is being
invoked by analyzing the parameters

float tryMe(int x) [signature 1] tryMe: int


{
return x + .375;
}

float tryMe(int x, float y) [signature 2] tryMe: int, float


{
return x*y;
}
Method Overriding
public class Parent
{
public float tryMe(int x) Same Signatures
{
return x + .375;
}
}

public class Child extends Parent


{
public float tryMe(int x)
{ Different
return x*x;
}
Method Bodies
}
Overriding Methods
• A child class can override the definition of an
inherited method in favor of its own

• The new method must have the same signature as


the parent's method, but can have a different body

• The type of the object executing the method


determines which version of the method is invoked
Overriding
• A method in the parent class can be invoked
explicitly using the super reference

• If a method is declared with the final modifier, it


cannot be overridden

• The concept of overriding can be applied to data


and is called shadowing variables

• Shadowing variables should be avoided because it

tends to cause unnecessarily confusing code


Overloading vs. Overriding
• Overloading deals with multiple methods with the
same name in the same class, but with different
signatures

• Overriding deals with two methods, one in a parent


class and one in a child class, that have the same
signature
Overloading vs. Overriding

• Overloading lets you define a similar operation in


different ways for different parameters

• Overriding lets you define a similar operation in


different ways for different object types
Polymorphism via Inheritance
References and Inheritance
• An object reference can refer to an object of its
class, or to an object of any class related to it by
inheritance
• For example, if the Holiday class is used to derive
a class called Christmas, then a Holiday reference
could be used to point to a Christmas object

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

• Assigning a parent object to a child reference can


be done also, but it is considered a narrowing
conversion and must be done with a cast

• The widening conversion is the most useful


Polymorphism via Inheritance
• It is the type of the object being referenced, not the
reference type, that determines which method is
invoked
• Suppose the Holiday class has a method called
celebrate, and the Christmas class overrides it

• Now consider the following invocation:


[Link]();

• If day refers to a Holiday object, it invokes the


Holiday version of celebrate; if it refers to a
Christmas object, it invokes the Christmas
version
Example: Animals class hierarchy

• [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 Duck extends Animal


{
public void makeSound()
{
[Link](“Quack-Quack");
}
}
public abstract class Animal
{
abstract void makeSound();
public void move()
{
[Link](“walk”);
}
}

public class Cow extends Animal public class Dog extends Animal
{ {
public void makeSound() public void makeSound()
{ {
[Link]("Moo-Moo"); [Link](“Wuf-Wuf");
} }
} }

public class Duck extends Animal


{
public void makeSound() {
[Link](“Quack-Quack");
}
public void move() { Override the move
[Link](“fly”); method defined in
}
the Animal class.
}
Polymorphism via Inheritance
• Consider the following class hierarchy:

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.

● There are only method bodies.

● Interfaces cannot be instantiated—they can only be implemented


by classes or extended by other interfaces.
Use of Interface in
Java..
● An interface defines a protocol of communication between two
objects.

● An interface declaration contains signatures, but no


implementations, for a set of methods, and might also contain
constant definitions.

● A class that implements an interface must implement all the


methods declared in the interface
Use of Interface in
Java..
● Objects define their interaction with the outside world through
the methods that they expose.

● Methods form the object's interface with the outside world

● An interface is a group of related methods with empty bodies


How Interface is similar to a
class?
An interface is similar to a class in the following ways −
● An interface can contain any number of methods.
● An interface is written in a file with a .java extension, with
the name of the interface matching the name of the file.
● The byte code of an interface appears in a .class file.
● Interfaces appear in packages, and their corresponding
bytecode file must be in a directory structure that matches
the package name.
An interface is different from a class in several ways, including
● You cannot instantiate an interface.
● An interface does not contain any constructors.
● All of the methods in an interface are abstract.
● An interface cannot contain instance [Link] only fields
that can appear in an interface must be declared both
static and final.
● An interface is not extended by a class; it is
implemented by a class.
● An interface can extend multiple interfaces.
Syntax

● 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’.

Key points to note:


1. A user-defined exception must extend Exception class.
2. The exception is thrown using throw keyword.
Example:
class MyException extends Exception{
String str1;
MyException(String str2) {str1=str2;}
public String toString(){
return ("MyException Occurred: "+str1);
}
}
class Example1{
public static void main(String args[]){
try{
[Link]("Start of try block");
throw new MyException(“Error Message");
}
catch(MyException exp){[Link]("Catch Block");
[Link](exp);
}
}
How to handle exceptions in Java?
As I have already mentioned, handling an exception is very important, else it
leads to system failure. But how do you handle these exceptions?
Java provides various methods to handle the Exceptions like:
• try
• catch
• finally
• throw
• throws
try block
The try block contains a set of statements where an exception can occur. It is always
followed by a catch block, which handles the exception that occurs in the associated try
block. A try block must be followed by catch blocks or finally block or both.

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.

public class Testtrycatch1{


public static void main(String args[]){
int data=50/0;//may throw exception
[Link]("rest of the code...");
}
}
Nested try block
class Exception1{
public static void main(String args[]){
try{
try{
[Link]("going to divide by zero");
int b=59/0;
}catch(ArithmeticException e){[Link](e);}
try{
int a[]=new int[5];
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e) {[Link](e);}
[Link]("other statement);
}catch(Exception e)
{[Link]("Exception handeled");}
[Link]("casual flow");
}
}
Multi-catch block
If you have to perform various tasks at the occurrence of various exceptions, you can use
the multi-catch block.
public class SampleMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{[Link]("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{[Link]("task 2 completed");}
catch(Exception e)
{[Link]("task 3 completed");}
[Link]("remaining code");
}
}
finally block

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!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}
}
Example
public class Main {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
} else {
[Link]("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15);
}
}
Java packages
• package: A collection of related classes.
• Can also "contain" sub-packages.
• Sub-packages can have similar names,
but are not actually contained inside.
• [Link] does not contain [Link]

• Uses of Java packages:


• group related classes together
• as a namespace to avoid name collisions
• provide a layer of access / protection
• keep pieces of a project down to a manageable size
JAVA Packages
Packages and directories
• package → directory (folder)
• class → file

• A class named D in package a.b.c should reside in this


file:

a/b/c/[Link]

• (relative to the root of your project)

• The "root" directory of the package hierarchy is


determined by your class path or the directory from
which java was run.
Classpath
• class path: The location(s) in which Java looks for
class files.

• Can include:
• the current "working directory" from which you ran javac
/ java
• other folders
• JAR archives
• URLs
• ...

• Can set class path manually when running java at


command line:
• java -cp /home/stepp/libs:/foo/bar/jbl MyClass
A package declaration
package name;
public class name { ...

Example:
package [Link];
public class Ghost extends Sprite {
...
}

• File [Link] should go in folder pacman/model .


Importing a package
import packageName.*; // all classes

Example:
package [Link];
import [Link].*;
public class PacManGui {
...
Ghost blinky = new Ghost();
}

• PacManGui must import the model package in order to use


it.
Importing a class
import [Link]; // one class

Example:
package [Link];
import [Link];
public class PacManGui {
Ghost blinky = new Ghost();
}

• Importing single classes has high precedence:


• if you import .*, a same-named class in the current dir will override
• if you import .className, it will not
Static import
import static [Link].*;

Example:
import static [Link].*;
...
double angle = sin(PI / 2) + ln(E * E);

• Static import allows you to refer to the members of another


class without writing that class's name.
• Should be used rarely and only with classes whose contents
are entirely static "utility" code.
Referring to packages
[Link]

Example:
[Link] console =
new [Link]([Link]);

• You can use a type from any package without


importing it if you write its full name.
• Sometimes this is useful to disambiguate similar
names.
• Example: [Link] and [Link]
• Or, explicitly import one of the classes.
The default package
• Compilation units (files) that do not declare a
package are put into a default, unnamed, package.

• Classes in the default package:


• Cannot be imported
• Cannot be used by classes in other packages

• Many editors discourage the use of the default


package.

• Package [Link] is implicitly imported in all


programs by default.
• import [Link].*;
Package access
• Java provides the following access modifiers:
• public : Visible to all other classes.
• private : Visible only to the current class (and any
nested types).
• protected : Visible to the current class, any of its
subclasses, and any other types within the same package.
• default (package): Visible to the current class and any
other types within the same package.

• To give a member default scope, do not write a


modifier:
package [Link];
public class Sprite {
int points; // visible to [Link].*
String name; // visible to [Link].*
Package exercise
• Add packages to the Rock-Paper-Scissors
game.
• Create a package for core "model" data.
• Create a package for graphical "view" classes.

• Any general utility code can go into a default


package or into another named utility (util)
package.
• Add appropriate package and import
statements so that the types can use each other
properly.
References:
• [Link]
• [Link]
• [Link]
• [Link]
• Y. Daniel Liang, Intro to Java Programming, Pearson
Education India

You might also like