Java
Java
(Java) ELC-114
Dr. Hanaa Ezzat
Advance Programming
• This Course notes are devoted to present fundamentals of object oriented
programing (JAVA) by introducing basic programming concepts and techniques
before designing custom classes. The fundamental concepts and techniques of
selection statements, loops, methods, and arrays are the foundation for
programming. Building this strong foundation prepares students to learn object-
oriented programming and advanced Java programming.
• This course teaches programming in a problem-driven way that focuses on
problem solving rather than syntax. We make introductory programming
interesting by using thought provoking problems in a broad context. To support
the teaching of programming in a problem-driven way, the course provides a
wide variety of problems at various levels of difficulty to motivate. This course
covers fundamentals of programming, object-oriented programming, GUI
programming, data structures, algorithms, concurrency, networking, database. It
is designed to prepare students to become proficient Java programmers.
Course Objectives
• Fundamentals first by introducing basic programming concepts and techniques, and why
Java
• Learn how to write new programs and projects using Java
• Java and C++, Java Project detail definitions
• Java variable definitions, Loop control (If, Do, While)
• Input data from screen, Operator Associativity, Format
• Java methods, stacks, design program
• Arrays and Multidimensional arrays description, declaration, initialization and apply in
programs
• Describe objects and classes, use classes to model objects, access objects
• String class, fixed string, string builder and buffer, delete and rename file class
• Creating objects, differences between the procedural paradigm and object-oriented
paradigm, develop cases
Course Sources
• Lectures
• Section
• Text book
INTRODUCTION TO JAVA PROGRAMMING COMPREHENSIVE VERSION Tenth Edition,
Y. Daniel Liang, 2015
• Java Programming Tutorial - Object-oriented Programming (OOP) Basics
Ntu.de April 2016
https://www3.ntu.edu.sg/home/ehchua/programming/java/J3a_OOPBasics.html
3
Java, Web, and Beyond
• Java can be used to develop Web
applications.
• Java Applets
• Java Web Applications
• Java can also be used to develop applications
for hand-held devices such as Palm and cell
phones
4
Examples of Java’s Versatility (Applets)
5
PDA and Cell Phone
6
Java’s History
• James Gosling and Sun Microsystems
• Oak
• Java, May 20, 1995, Sun World
• HotJava
• The first Java-enabled Web browser
• Early History Website:
http://java.sun.com/features/1998/05/birthday.html
7
Software development process
New applications
Basic element to design and create a new application
• DFD(Data Flow Diagram)
• 0-Level
• 1-Level
• 2-Level
• E-R Diagram
• Database Design / Tables Design
• Screen Designs / Forms / Login form/ Master Form / Data and application forms
• Reports
DFD(Data Flow Diagram)
0-Level
DELETE
SEARCH STUDENT
STUDENT DATA
DATA
2-Level STUD_INFO
TEACHERS_DATA
TAKES
ADMSSION COLLEGE GENERATES
STUDENTS MANAGEMENT RECORDS
SYSTEM
DELETE
SEARCH STUDENT CLASS
STUDENT DATA FEES RECORDS
DATA RECORDS
CLASS_SETUP
FEES_SETUP
E-R Diagram
STUDENT TEACH TEACHER
SUBJECT
CHOOSE
TAKE CLASS
ADMISSION
PAID FEES
Database Design
➢STUDENT_DATA TABLE
➢TEACHERS_DATA TABLE
➢CLASS_SETUP TABLE
➢FEES_SETUP TABLE
➢SUBJECT_DATA TABLE
Screen Designs
➢Front Form
➢Login Form
➢Master Form
➢Student Setup Form
➢Teacher Setup Form
➢Class Setup Form
➢Fees Setup Form
➢Student Record Form
➢Teacher Record Form
➢Fees Record Form
➢About Form
Front Form
Login Form
Master Form
Student_Setup Form
Teacher Setup Form
Class Setup Form
Fees Setup Form
Student Record Form
Teacher Record Form
Fees Record Form
About Form
Reports
➢STUDENT REPORT
➢TEACHER RECORD REPORT
➢BILL PRINT PREVIEW
User/Operational Manual-
Including security aspects, access
rights, back up, controls etc.
Welcome to your College Management Software
SHOWS DATA
RECORDS SHOWS
FORM THE
REPORTS
CLOSES THE
WHOLE
OPENS APPLICATION
STUDENT
SETUP FORM
OPENS
TEACHER
SETUP FORM OPENS
SUBJECT
SETUP FORM
1
Characteristics of Java
• Java Is Simple Java is partially modeled on C++, but greatly
simplified and improved. Some people refer
• Java Is Object-Oriented to Java as "C++--" because it is like C++ but
• Java Is Distributed with more functionality and fewer negative
aspects.
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
2
Characteristics of Java
• Java Is Simple Java is inherently object-oriented.
Although many object-oriented languages
• Java Is Object-Oriented began strictly as procedural languages,
• Java Is Distributed Java was designed from the start to be
object-oriented. Object-oriented
• Java Is Interpreted programming (OOP) is a popular
• Java Is Robust programming approach that is replacing
traditional procedural programming
• Java Is Secure techniques.
• Java Is Architecture-Neutral
One of the central issues in software
• Java Is Portable development is how to reuse code.
• Java's Performance Object-oriented programming provides
great flexibility, modularity, clarity, and
• Java Is Multithreaded reusability through encapsulation,
• Java Is Dynamic inheritance, and polymorphism.
3
Java Is Object-Oriented
• Software systems developed using procedural programming
languages are based on the paradigm of procedures.
• Object oriented programming models the real world in terms of
objects.
• Everything in the world can be modeled as an object. A circle is an
object, a person is an object, and a Window icon is an object.
• Even a loan can be perceived as an object.
• A Java program is object-oriented because programming in Java is
centered on creating objects, manipulating objects, and making
objects work together.
Java Is Object-Oriented
• Java supports OOP
–Polymorphism
–Inheritance
–Encapsulation
• Java programs contain nothing but definitions and instantiations of
classes
• Everything is encapsulated in a class!
Object-Oriented Design Principles
Abstraction
◼ Distill a complicated system down to its most
fundamental parts and describe these parts in a
simple, precise language.
Encapsulation
◼ Different components of a software system
should not reveal the internal details of their
respective implementations.
Modularity
◼ Different components of a software system are
divided into separated functional units.
6
Inheritance
• A technique that allows the design of general classes that can be
specialized to more particular classes, with the specialized classes reusing
the code from the general class.
• A class that is derived from another class is called a subclass (also a
derived class, extended class, or child class). The class from which the
subclass is derived is called a superclass (also a base class or a parent
class).
7
Characteristics of Java
• Java Is Simple Distributed computing involves several
computers working together on a
• Java Is Object-Oriented network. Java is designed to make
• Java Is Distributed distributed computing easy. Since
networking capability is inherently
• Java Is Interpreted integrated into Java, writing network
• Java Is Robust programs is like sending and receiving
data to and from a file.
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
8
Characteristics of Java
• Java Is Simple You need an interpreter to run Java
programs. The programs are compiled into
• Java Is Object-Oriented the Java Virtual Machine code called
• Java Is Distributed bytecode. The bytecode is machine-
independent and can run on any machine
• Java Is Interpreted that has a Java interpreter, which is part of
• Java Is Robust the Java Virtual Machine (JVM).
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
9
Java Is Interpreted
• You need an interpreter to run Java programs. The programs are
compiled into the Java Virtual Machine code called bytecode.
• The bytecode is machine-independent and can run on any machine
that has a Java interpreter, which is part of the Java Virtual Machine
(JVM).
• Most compilers, including C++ compilers, translate programs in a
high-level language to machine code.
• The code can only run on the native machine. If you run the program
on other machines, it has to be recompiled on the native machine.
Java Is Interpreted
• For instance, if you compile a C++ program in Windows, the
executable code generated by the compiler can only run on the
Windows platform. With Java, you compile the source code once, and
the bytecode generated by a Java compiler can run on any platform
with a Java interpreter.
• The Java interpreter translates the bytecode into the machine
language of the target machine.
Characteristics of Java
• Java Is Simple Java compilers can detect many problems
that would first show up at execution time
• Java Is Object-Oriented in other languages.
• Java Is Distributed
Java has eliminated certain types of error-
• Java Is Interpreted prone programming constructs found in
• Java Is Robust (reliable) other languages.
• Java Is Secure Java has a runtime exception-handling
• Java Is Architecture-Neutral feature to provide programming support
for robustness.
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
12
Java Is Robust
• Robust means reliable. No programming language can ensure
complete reliability.
• Java puts a lot of emphasis on early checking for possible errors,
because Java compilers can detect many problems that would first
show up at execution time in other languages.
• Java has eliminated certain types of error-prone programming
constructs found in other languages. It does not support pointers, for
example, thereby eliminating the possibility of overwriting memory
and corrupting data.
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
Java implements several security
• Java Is Robust mechanisms to protect your system
• Java Is Secure against harm caused by stray programs.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
14
Java Is Secure
• As an Internet programming language, Java is used in a networked
and distributed environment.
• If you download a Java applet (a special kind of program) and run it
on your computer, it will not damage your system because Java
implements several security mechanisms to protect your system
against harm caused by stray programs.
• The security is based on the premise that nothing should be trusted.
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral Write once, run anywhere
16
Java Is Architecture-Neutral
• Java is interpreted. This feature enables Java to be architecture-
neutral, or to use an alternative term, platform-independent. With a
Java Virtual Machine (JVM), you can write one program that will run
on any platform.
• Java’s initial success stemmed from its Web-programming capability.
• You can run Java applets from a Web browser, but Java is for more
than just writing Web applets. You can also run standalone Java
applications directly from operating systems, using a Java interpreter.
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable Because Java is architecture neutral,
Java programs are portable. They can
• Java's Performance be run on any platform without being
• Java Is Multithreaded recompiled.
• Java Is Dynamic
18
Java Is Portable
• Moreover, there are no platform-specific features in the Java
language. In some languages, such as Ada, the largest integer varies
on different platforms.
• But in Java, the range of the integer is the same on every platform, as
is the behavior of arithmetic. The fixed range of the numbers makes
the program portable.
• The Java environment is portable to new hardware and operating
systems. In fact, the Java compiler itself is written in Java.
Java Is Portable
• Today, software vendors usually develop multiple versions of the
same product to run on different platforms (Windows, OS/2,
Macintosh, and various UNIX, IBM AS/400, and IBM mainframes).
• Using Java, developers need to write only one version that can run on
every platform.
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable Java’s performance Because Java is
architecture neutral, Java programs are
• Java's Performance portable. They can be run on any
• Java Is Multithreaded platform without being recompiled.
• Java Is Dynamic
21
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance Multithread programming is smoothly
• Java Is Multithreaded integrated in Java, whereas in other
languages you have to call procedures
• Java Is Dynamic specific to the operating system to enable
multithreading.
22
Java Is Multithreaded
• Multithreading is a program’s capability to perform several tasks
simultaneously.
• For example, downloading a video file while playing the video would
be considered multithreading.
• Multithread programming is smoothly integrated in Java, whereas in
other languages you have to call procedures specific to the operating
system to enable multithreading
Java Is Multithreaded
• Multithreading is particularly useful in graphical user interface (GUI)
and network programming.
• n GUI programming, there are many things going on at the same
time.
• A user can listen to an audio recording while surfing a Web page.
• In network programming, a server can serve multiple clients at the
same time.
• Multithreading is a necessity in multimedia and network
programming.
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
Java was designed to adapt to an evolving
• Java's Performance environment. New code can be loaded on the
• Java Is Multithreaded fly without recompilation. There is no need for
developers to create, and for users to install,
• Java Is Dynamic major new software versions. New features can
be incorporated transparently as needed.
25
JDK Versions
• JDK 1.02 (1995)
• JDK 1.1 (1996)
• JDK 1.2 (1998)
• JDK 1.3 (2000)
• JDK 1.4 (2002)
• JDK 1.5 (2004) a. k. a. JDK 5 or Java 5
• JDK 1.6 (2006) a. k. a. JDK 6 or Java 6
• JDK 1.7 (2010) a. k. a. JDK 7 or Java 7
• JDK 1.8 Last version JDK 8 or Java 8
26
JDK Editions
• Java Standard Edition (J2SE)
• J2SE can be used to develop client-side standalone
applications or applets.
• Java Enterprise Edition (J2EE)
• J2EE can be used to develop server-side applications
such as Java servlets and Java ServerPages.
• Java Micro Edition (J2ME).
• J2ME can be used to develop applications for mobile
devices such as cell phones.
We uses J2SE to introduce Java programming.
27
Popular Java IDEs
• NetBeans Open Source by Sun
• Eclipse Open Source by IBM
• We will use NetBeans
28
NetBeans IDE 8.0.2
A Simple Java Program
Listing 1.1
//This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Welcome
Run
30
1 st Program
• File/ New project
• In the Name and Location page of the wizard, do the following (as
shown in the figure below):
• In the Project Name field, type HellowApp.
• Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.
• In the Create Main Class field, type hellowapp.HelloWApp.
• Click Finish.
• The project is created and opened in the IDE. You should see the
following components:
• The Projects window, which contains a tree view of the components
of the project, including source files, libraries that your code depends
on, and so on.
• The Source Editor window with a file called HelloWorldApp open.
• The Navigator window, which you can use to quickly navigate
between elements within the selected class.
Adding Code to the Generated Source File
• Because you have left the Create Main Class checkbox selected in the
New Project wizard, the IDE has created a skeleton main class for you.
You can add the "Hello Class 3" message to the skeleton code by
replacing the line:
• // TODO code application logic here
•
• with the line:
• System.out.println("Hello Class 3");
• Save the change by choosing File > Save.
• The file should look something like the following code sample.
Compiling and Running the Program
• Because of the IDE's Compile on Save feature, you do not have to
manually compile your project in order to run it in the IDE. When you
save a Java source file, the IDE automatically compiles it.
• The Compile on Save feature can be turned off in the Project
Properties window. Right-click your project, select Properties. In the
Properties window, choose the Compiling tab. The Compile on Save
checkbox is right at the top.
Run Project
• Note that in the Project Properties window you can configure
numerous settings for your project: project libraries, packaging,
building, running, etc.
• To run the program:
• Choose Run > Run Project.
• The next figure shows what you should now see.
Building and Deploying the Application
• Once you have written and test run your application, you can use the
Clean and Build command to build your application for deployment.
When you use the Clean and Build command, the IDE runs a build
script that performs the following tasks:
• Deletes any previously compiled files and other build outputs.
• Recompiles the application and builds a JAR file containing the
compiled files.
• To build your application:
• Choose Run > Clean and Build Project.
• From Dos command type
• java -jar
"C:\Users\Hanaa\Documents\NetBeansProjects\hellowApp\dist\hello
wApp.jar"
Creating and Editing Using NotePad
To use NotePad, type
notepad Welcome.java
from the DOS prompt.
45
Creating and Editing Using WordPad
To use WordPad, type
write Welcome.java
from the DOS prompt.
46
Creating, Compiling, and Running
Programs
Create/Modify Source Code
Result
Java Virtual
Machine
Any
Computer
48
Trace a Program Execution
Enter main method
49
Trace a Program Execution
Execute statement
50
Trace a Program Execution
51
Compiling and Running Java from
the Command Window
• Set path to JDK bin directory
• set path=c:\Program Files\java\jdk1.6.0\bin
• Set classpath to include the current directory
• set classpath=.
• Compile
• javac Welcome.java
• Run
• java Welcome
52
Compiling and Running Java from
TextPad
• See Supplement II.A on the Website for details
53
Anatomy of a Java Program
• Comments
• Reserved words
• Modifiers
• Statements
• Blocks
• Classes
• Methods
• The main method
54
Comments
Three types of comments in Java.
56
Modifiers
Java uses certain reserved words called modifiers that
specify the properties of the data, methods, and
classes and how they can be used. Examples of
modifiers are public and static. Other modifiers are
private, final, abstract, and protected. A public datum,
method, or class can be accessed by other programs.
A private datum or method cannot be accessed by
other programs. Modifiers are discussed in Chapter 6,
“Objects and Classes.”
57
Statements
A statement represents an action or a sequence of
actions. The statement System.out.println("Welcome to
Java!") in the program is a statement to display the
greeting "Welcome to Java!" Every statement in Java
ends with a semicolon (;).
58
Blocks
A pair of braces in a program forms a block that groups
components of a program.
59
Classes
The class is the essential Java construct. A class is a
template or blueprint for objects. To program in Java,
you must understand classes and be able to write and
use them. The mystery of the class will continue to be
unveiled throughout this book. For now, though,
understand that a program is defined by using one or
more classes.
60
Classes
• A class consists of
• a collection of variables, or fields, and
• a set of functions, called methods.
• A class serves as a template of objects.
61
Primitive Types
62
Operators (1/3)
Operator Purpose
+ addition of numbers, concatenation of Strings
+= add and assign numbers, concatenate and assign Strings
- subtraction
-= subtract and assign
* multiplication
*= multiply and assign
/ division
/= divide and assign
% take remainder
%= take remainder and assign
++ increment by one
-- decrement by one
63
Operators (2/3)
Operator Purpose
> greater than
>= greater than or equal to
< less than
<= less than or equal to
! boolean NOT
!= not equal to
&& boolean AND
|| boolean OR
== boolean equals
= assignment
~ bitwise NOT
?: conditional
64
Operators (3/3)
Operator Purpose
Instanceof type checking
| bitwise OR
|= bitwise OR and assign
^ bitwise XOR
^= bitwise XOR and assign
& bitwise AND
&= bitwise AND and assign
>> shift bits right with sign extension
>>= shift bits right with sign extension and assign
<< shift bits left
<<= shift bits left and assign
>>> unsigned bit shift right
>>>= unsigned bit shift right and assign
65
Control Statements
• if-else
• switch
• while loop
• for loop
• do-while loop
66
Methods
What is
System.out.println “Hello Calass 2”;
68
Example
Example
Displaying Text in a Message
Dialog Box
you can use the showMessageDialog method in the
JOptionPane class. JOptionPane is one of the many
predefined classes in the Java system, which can be
reused rather than “reinventing the wheel.”
71
The showMessageDialog Method
JOptionPane.showMessageDialog(null,
"Welcome to Java!",
"Display Message",
JOptionPane.INFORMATION_MESSAGE);
72
Two Ways to Invoke the Method
There are several ways to use the showMessageDialog
method. For the time being, all you need to know are
two ways to invoke it.
One is to use a statement as shown in the example:
JOptionPane.showMessageDialog(null, x,
y, JOptionPane.INFORMATION_MESSAGE);
where x is a string for the text to be displayed, and y is
a string for the title of the message dialog box.
The other is to use a statement like this:
JOptionPane.showMessageDialog(null, x);
where x is a string for the text to be displayed.
73
• Course designed for
• People who want to develop software with JAVA
• Those know programming vocabulary
/**
*
* @author Hanaa
*/
public class HellowApp { → Class declaration
/**
* @param args the command line arguments
*/
public static void main(String[] args) { → Main method
System.out.println("Hello Class 3!"); → Executable code
}
executable code must end with ;
• In the Name and Location page of the wizard, do the following (as
shown in the figure below):
• In the Project Name field, type HellowApp.
• Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.
• In the Create Main Class field, type hellowapp.HelloWApp.
• Click Finish.
• The project is created and opened in the IDE. You should see the
following components:
• The Projects window, which contains a tree view of the components
of the project, including source files, libraries that your code depends
on, and so on.
• The Source Editor window with a file called HelloWorldApp open.
• The Navigator window, which you can use to quickly navigate
between elements within the selected class.
Adding Code to the Generated Source File
• Because you have left the Create Main Class checkbox selected in the
New Project wizard, the IDE has created a skeleton main class for you.
You can add the "Hello Class 3" message to the skeleton code by
replacing the line:
• // TODO code application logic here
•
• with the line:
• System.out.println("Hello Class 1");
• Save the change by choosing File > Save.
• The file should look something like the following code sample.
Example Add two numbers (addtwonumbers)
• The Java SE Development Kit includes the runtime, compile, and
other tools including:
➢javac – a command line compiler
➢Java – a command line runtime
➢Jar – the packager (packaging get files for archive in zip format)
➢Javadoc – the documentation builder (build documentation on the
program code)
➢…….
Programming Errors
• Syntax Errors
• Detected by the compiler
• Runtime Errors
• Causes the program to abort
• Logic Errors
• Produces incorrect result
1
Syntax Errors
2
Errors in Program
• Correct statement
• With error
• /**
• *
• * @author Hanaa
• */
• public class ShowLogicErrors {
• public static void main(String[] args) {
• System.out.println("Celsius 35 is Fahrenheit degree Wrong answer");
• System.out.println((9 / 5) * 35 + 32);
•
• System.out.println("Celsius 35 is Fahrenheit degree Correct answer");
• System.out.println((5.0 / 9.0) * (35.0 - 32.0));
• }
• }
Sum of two numbers using Scanner(AddTwoNumbers2)
Displaying Text in a Message
Dialog Box
you can use the showMessageDialog method in the
JOptionPane class. JOptionPane is one of the many
predefined classes in the Java system, which can be
reused rather than “reinventing the wheel.”
8
Program to Multiply two numbers(mult)
Program make simple calculation
• To calculate the area of a circle with radius 20
Identifiers
• An identifier is a sequence of characters that consist of
letters, digits, underscores (_), and dollar signs ($).
• An identifier must start with a letter, an underscore (_),
or a dollar sign ($). It cannot start with a digit.
• An identifier cannot be a reserved word.
• An identifier cannot be true, false, or null.
• An identifier can be of any length.
14
Variables
// Compute the first area
radius = 20.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ +
area + " for radius "+radius);
15
Declaring Variables
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;
16
Default value for data types in Java
• int → 0
• char → '\u0000‘
• boolean → false
• Double→0.0d
• String (or any object) →null
• Float → 0.0f
Assignment Statements
x = 1; // Assign 1 to x;
radius = 20.0; // Assign 20.0 to radius;
a = 'A'; // Assign 'A' to a;
18
Declaring and Initializing in One Step
• int x = 1;
• double d = 1.4;
19
Constants
final datatype CONSTANTNAME = VALUE;
20
Numerical Data Types
21
Numeric Operators
22
Integer Division
+, -, *, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
23
Remainder Operator
Remainder is very useful in programming. For example, an even
number % 2 is always 0 and an odd number % 2 is always 1. So
you can use this property to determine whether a number is
even or odd. Suppose today is Saturday and you and your
friends are going to meet in 10 days. What day is in 10
days? You can find that day is Tuesday using the following
expression:
24
Number Literals
A literal is a constant value that appears directly
in the program. For example, 34, 1,000,000, and
5.0 are literals in the following statements:
int i = 34;
long x = 1000000;
double d = 5.0;
25
Integer Literals
An integer literal can be assigned to an integer variable as
long as it can fit into the variable. A compilation error
would occur if the literal were too large for the variable to
hold. For example, the statement byte b = 1000 would
cause a compilation error, because 1000 cannot be stored
in a variable of the byte type.
An integer literal is assumed to be of the int type, whose
value is between -231 (-2147483648) to 231–1
(2147483647). To denote an integer literal of the long
type, append it with the letter L or l. L is preferred
because l (lowercase L) can easily be confused with 1 (the
digit one).
26
Floating-Point Literals
Floating-point literals are written with a decimal point. By
default, a floating-point literal is treated as a double type
value. For example, 5.0 is considered a double value, not a
float value. You can make a number a float by appending
the letter f or F, and make a number a double by
appending the letter d or D. For example, you can use
100.2f or 100.2F for a float number, and 100.2d or 100.2D
for a double number.
27
Compute area with constant input from screen
Compute area with constant input
PI = 3.14159
// Compute area
double area = radius * radius * PI;
Program calculate average
Scientific Notation
Floating-point literals can also be specified in
scientific notation, for example, 1.23456e+2,
same as 1.23456e2, is equivalent to 123.456,
and 1.23456e-2 is equivalent to 0.0123456. E (or
e) represents an exponent and it can be either in
lowercase or uppercase.
33
Arithmetic Expressions
3 + 4 x 10( y − 5)(a + b + c ) 4 9+ x
− + 9( + )
5 x x y
is translated to
34
How to Evaluate an Expression
Though Java has its own way to evaluate an
expression behind the scene, the result of a Java
expression and its corresponding arithmetic
expression are the same. Therefore, you can safely
apply the arithmetic rule for evaluating a Java
expression. 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) addition
54 - 1
(6) subtraction
53
35
Problem: Converting Temperatures
Write a program that converts a Fahrenheit degree to
Celsius using the formula:
celsius = ( 95 )( fahrenheit − 32)
36
Problem: Calulate Time
150 sec. = 2 min 30 sec
1
Problem: Displaying Current Time
Write a program that displays current time in GMT in the
format hour:minute:second such as 1:45:19.
The currentTimeMillis method in the System class returns
the current time in milliseconds since the midnight,
January 1, 1970 GMT. (1970 was the year when the Unix
operating system was formally introduced.) You can use
this method to obtain the current time, and then compute
the current second, minute, and hour as follows.
Elapsed
time
ShowCurrentTime
Time
Current Time
Unix Epoch
01-01-1970 System.currentTimeMills()
Run
00:00:00 GMT
3
Shortcut Assignment Operators
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8
6
Increment and Decrement Operators
7
Increment and Decrement Operators, cont.
8
Increment and Decrement Operators, cont.
9
Assignment Expressions and Assignment Statements
10
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
11
Conversion Rules
When performing a binary operation involving two
operands of different types, Java automatically
converts the operand based on the following rules:
12
Type Casting
Implicit casting
double d = 3; (type widening)
Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is
truncated)
What is wrong? int x = 5 / 2.0;
range increases
13
Problem: Keeping Two Digits After Decimal Points
Write a program that displays the sales tax with decimal
point.
14
Problem: Computing Loan Payments
16
Problem: Computing Loan Payments
17
The String Type
The char type only represents one character. To represent a string
of characters, use the data type called String. For example,
String is actually a predefined class in the Java library just like the
System class and JOptionPane class. The String type is not a
primitive type. It is known as a reference type. Any Java class can
be used as a reference type for a variable. “Objects and Classes.”
For the time being, you just need to know how to declare a String
variable, how to assign a string to the variable, and how to
concatenate strings.
20
String Concatenation
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
21
Programming Style and Documentation
• Appropriate Comments
• Naming Conventions
• Proper Indentation and Spacing
Lines
• Block Styles
22
Appropriate Comments
Include a summary at the beginning of the program to
explain what the program does, its key features, its
supporting data structures, and any unique techniques it
uses.
23
Block Styles
Use end-of-line style for braces.
End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
27
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.
28
Debugger
Debugger is a program that facilitates debugging. You can
use a debugger to
29
Debugging in NetBeans
How to Debug
30
To input string from console
• Write a program to read “Hello world” from the screen check if you
entered the correct statement
Program1
• Write a program to give two random numbers, ask about the
summation of two numbers from screen, compare the result give
message is the answer true or false
Program2 (ComputeChange)
• Suppose you want to develop a program that changes a given amount
of money into smaller monetary units. The program lets the user
enter an amount as a double value representing a total in dollars and
cents, and outputs a report listing the monetary equivalent in the
maximum number of dollars, quarters, dimes, nickels, and pennies, in
this order, to result in the minimum number of coins.
Program2 Steps
Here are the steps in developing the program:
1. Prompt the user to enter the amount as a decimal number, such as 11.56.
2. Convert the amount (e.g., 11.56) into cents (1156).
3. Divide the cents by 100 to find the number of dollars. Obtain the remaining cents using
the cents remainder 100.
4. Divide the remaining cents by 25 to find the number of quarters. Obtain the remaining
cents using the remaining cents remainder 25.
5. Divide the remaining cents by 10 to find the number of dimes. Obtain the remaining
cents using the remaining cents remainder 10.
6. Divide the remaining cents by 5 to find the number of nickels. Obtain the remaining
cents using the remaining cents remainder 5.
7. The remaining cents are the pennies.
8. Display the result.
Program PrintTable
• (Print a table) Write a program that displays the following table. Cast
floatingpoint numbers into integers.
•a b pow(a, b)(a^B)
•1 2 1 (1^2)
•2 3 8 (2^3)
•3 4 81 (3^4)
•4 5 1024 (4^5)
•5 6 15625 (5^6)
Converting Strings to Integers
The input returned from the input dialog box is a string. If
you enter a numeric value such as 123, it returns “123”.
To obtain the input as a number, you have to convert a
string into a number.
42
Types of variables
• Two major types of variables
• Primitives
• Numeric, Integer, and floating point decimal
• Single character
• Boolean (True/False)
• Complex object
• Strings
• Dates
• Everything Else
Local Variable in Functions
• Variable inside a function are local to the function
The Boolean Type and Operators
Often in a program you need to compare two values,
such as whether i is greater than j. Java provides six
comparison operators (also known as relational
operators) that can be used to compare two values. The
result of the comparison is a Boolean value: true or
false.
49
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
50
Example for Boolean Expression
• The following simple example program demonstrates the logical operators.
• public class Test {
•
• public static void main(String args[]) {
• boolean a = true;
• boolean b = false;
• System.out.println("a && b = " + (a&&b));
• System.out.println("a || b = " + (a||b) );
• System.out.println("!(a && b) = " + !(a && b));
• }
• }
Example for Boolean Expression
• Result
a && b = false
a || b = true
!(a && b) = true
variable types
• Local variables
• Instance variables
• Class/static variables
Local Variables
• Local variables are declared in methods, constructors, or blocks
• Local variables are created when the method, constructor or block is
entered and the variable will be destroyed once it exits the method,
constructor or block
• There is no default value for local variables so local variables should
be declared and an initial value should be assigned before the first
use.
• When Function finished executing variable go away
Local Variable Example
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age); }
public static void main(String args[]){ Test test = new Test();
test.pupAge(); } }
Reeult:
Puppy age is: 7
Local Variable Example
• If remove age=0 the program give error as local variable must
initializes
Instance variables:
• Instance variables are declared in a class, but outside a method,
constructor or any block.
• Instance variables hold values that must be referenced by more than
one method, constructor or block, or essential parts of an object's
state that must be present throughout the class.
• Instance variables can be declared in class level
• Instance variables have default values. For numbers the default value
is 0, for Booleans it is false and for object references it is null.
Instance variables Example
Class/static variables:
• Class variables also known as static variables are declared with the
static keyword in a class, but outside a method, constructor or a
block.
• There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
• Static variables are created when the program starts and destroyed
when the program stops.
• Default values are same as instance variables. For numbers, the
default value is 0; for Booleans, it is false; and for object references, it
is null.
Class/static variables Example
Java Enums
• Enums restrict a variable to have one of only a few predefined values.
The values in this enumerated list are called enums.
• With the use of enums it is possible to reduce the number of bugs in
your code.
Java Enums
• Ex.
Java Modifiers
• Ex. Create two random number and get the summation of the two
numbers from input screen
• We use While Loop
Program (SubtractionQuiz)
• Write a program to generate two random numbers single-digit
integers )
• 2. If number1 < number2, swap number1 with number2
• Prompt the student to answer “what is number1 – number2” if
answer correct print “You are correct” if not print the correct answer
Loop Control Types
• Loop Control
While
• The While condition repeated as soon as condition TRUE
• While Syntax
while(Boolean_expression)
{ //Statement1;
//Statement; … }
While
• Do example
For
• For Statement
• The initialization step is executed first,
• Next, the Boolean expression is evaluated. If it is true, the body of
the loop is executed. If it is false, the body of the loop will not be
executed and control jumps to the next statement past the for loop.
• Syntax
• After the body of the for loop gets executed, the control jumps back
up to the update statement
For
• Syntax
for(initialization;
Boolean_expression;
update)
{ //Statement1;
//Statement2;…. }
For
• For Ex.
Do While
• A do...while loop is similar to a while loop, except that a do...while
loop is guaranteed to execute at least one time.
• Do Syntax
do { //Statements;
//Statment2;….}
while(Boolean_expression)
Do While
• Do Ex.
If Statement
• Decision making structures have one or more conditions to be
evaluated or tested by the program,
• along with a statement or statements that are to be executed if the
condition is determined to be
• true, and optionally, other statements to be executed if the condition
is determined to be false.
• Following is the general form of a typical decision making structure
found in most of the programming languages: Java
One-way if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { System.out.println("The area"
statement(s);
} + " for the circle of radius "
+ radius + " is " + area);
}
false false
Boolean (radius >= 0)
Expression
true true
(A) (B)
19
If Statement
• If Types
Note
if i > 0 { if (i > 0) {
System.out.println("i is positive"); System.out.println("i is positive");
} }
(a) Wrong (b) Correct
if (i > 0) { if (i > 0)
System.out.println("i is positive"); Equivalent System.out.println("i is positive");
}
(a) (b)
21
If Statement
• If Ex.
IF Else
• If Followed by else
• Syntax
if(Boolean_expression)
{ //Executes when the Boolean expressions is true }
Else
{ //Executes when the Boolean expressions is false }
IF Else
• If Else Ex.
if...else Example
if (radius >= 0) {
area = radius * radius * 3.14159;
1
Nested IF
• Use another IF when IF is True or When IF is False
• Syntax
if(Boolean_expression 1)
{ //Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{ //Executes when the Boolean expression 2 is true } }
Nested IF
• Nested IF Ex.
Ex.
• Write a program to calculate BMI
• bmi = weightInKilograms / (heightInMeters * heightInMeters)
Switch /Case
• A switch statement allows a variable to be tested for equality against
a list of values. Each value is called a case, and the variable being
switched on is checked for each case.
Switch / Case 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.
8
Switch / Case 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. The case statements are executed in sequential
order, but the order of the cases (including the
default case) does not matter. However, it is good
programming style to follow the logical sequence
of the cases and place the default case at the end.
9
Switch /Case
• Switch Syntax
switch(expression)
{ case value : //Statements break;
//optional case value : //Statements break; //optional //You can have
any number of case statements. default : //Optional //Statements }
Switch /Case
• Switch / Case Ex.
Common Errors
Adding a semicolon at the end of an if clause is a common
mistake.
if (radius >= 0); Wrong
{
area = radius*radius*PI;
System.out.println(
"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.
13
Input from Screen
• Import Java utility scanner
• Command
import java.util.Scanner; // Scanner is in the java.util package
• Must written before the public class Test1 {….}
• // Create a Scanner object
Scanner input = new Scanner(System.in);
// Prompt the user to enter number
double number1 = input.nextDouble();
Input Example
• Write a program to read 3 different numbers from screen and
calculate average of the 3 numbers
• Program test11
Input Example
• Average Ex.
Random Function
• Ex.
And Ex.
• Write a program to convert a decimal number to hexadecimal
• This done by dividing the number /16
And Ex.
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)
23
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)
24
Problem: Determining Leap Year?
Conditional Operator
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);
System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);
27
Formatting Output
Use the printf statement.
System.out.printf(format, items);
Where format is a string that may consist of substrings and
format specifiers. A format specifier specifies how an item
should be displayed. An item may be a numeric value,
character, boolean value, or a string. Each specifier begins
with a percent sign.
28
Frequently-Used Specifiers
Specifier Output Example
%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.460000
%s a string "Java is cool"
int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
Married Filing
Marginal Married Filing
Single Jointly or Qualified Head of Household
Tax Rate Separately
Widow(er)
10% 0 – 8,350 0 – 16,700 0 – 8,350 $ – 11,950
34
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method Invoke a method
1
Method Signature
Method signature is the combination of the method name and the
parameter list.
2
Formal Parameters
The variables defined in the method header are known as
formal parameters.
3
Actual Parameters
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
4
Return Value Type
A method may return a value. The returnValueType is the data type
of the value the method returns. If the method does not return a
value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
5
Testing Max Methods
• maxTest prog.
This program demonstrates calling a method
maxTest to return the largest of the int values
6
Testing Max Methods
• MaxTest Prog.
Calling Methods, cont.
9
Trace Method Invocation
i is now 5
10
Trace Method Invocation
j is now 2
11
Trace Method Invocation
invoke max(i, j)
12
Trace Method Invocation
invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2
13
Trace Method Invocation
declare variable result
14
Trace Method Invocation
(num1 > num2) is true since num1
is 5 and num2 is 2
15
Trace Method Invocation
result is now 5
16
Trace Method Invocation
return result, which is 5
17
Trace Method Invocation
return max(i, j) and assign the
return value to k
18
Trace Method Invocation
Execute the print statement
19
Note
A return statement is required for a value-returning method. The
method shown below in (a) is logically correct, but it has a
compilation error because the Java compiler thinks it possible that
this method does not return any value.
To fix this problem, delete if (n < 0) in (a), so that the compiler will
see a return statement to be reached regardless of how the if
statement is evaluated.
20
Reuse Methods from Other Classes
NOTE: One of the benefits of methods is for reuse. The max
method can be invoked from any class besides TestMax. If
you create a new class Test, you can invoke the max method
using ClassName.methodName (e.g., TestMax.max).
21
Call Stacks
Space required for Space required for Space required for Space required for
the main method the main method the main method the main method
k: k: k: k: 5 Stack is empty
j: 2 j: 2 j: 2 j: 2
i: 5 i: 5 i: 5 i: 5
(a) The main (b) The max (c) The max method (d) The max method is (e) The main
method is invoked. method is invoked. is being executed. finished and the return method is finished.
value is sent to k.
22
Trace Call Stack
i is declared and initialized
i: 5
23
Trace Call Stack
j is declared and initialized
j: 2
i: 5
24
Trace Call Stack
Declare k
25
Trace Call Stack
Invoke max(i, j)
26
Trace Call Stack
pass the values of i and j to num1
and num2
num2: 2
num1: 5
Space required for the
main method
k:
j: 2
i: 5
27
Trace Call Stack
result:
num2: 2
num1: 5
Space required for the
main method
k:
j: 2
i: 5
28
Trace Call Stack
result:
num2: 2
num1: 5
Space required for the
main method
k:
j: 2
i: 5
29
Trace Call Stack
30
Trace Call Stack
31
Trace Call Stack
Execute print statement
32
Scope of Local Variables
• A local variable: a variable defined inside a
method.
Scope: the part of the program where the
variable can be referenced.
• 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 declared before it can be
used.
33
Scope of Local Variables
You can declare a local variable with the
same name multiple times in different non-
nesting blocks in a method, but you cannot
declare a local variable twice in nested
blocks.
34
Scope of Local Variables, cont.
A variable declared in the initial action part of a for loop
header has its scope in the entire loop. But a variable
declared inside a for loop body has its scope limited in the
loop body from its declaration and to the end of the block
that contains the variable.
35
Scope of Local Variables, cont.
36
Rounding Methods
• double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a
double value.
• double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a
double value.
• double rint(double x)
x is rounded to its nearest integer. If x is equally close to two integers,
the even one is returned as a double.
• int round(float x)
Return (int)Math.floor(x+0.5).
• long round(double x)
Return (long)Math.floor(x+0.5).
37
min, max, and abs
• max(a, b)and min(a, b) Examples:
Returns the maximum or
minimum of two parameters.
Math.max(2, 3) returns 3
• abs(a)
Math.max(2.5, 3) returns
Returns the absolute value of the
parameter.
3.0
Math.min(2.5, 3.6)
• random() returns 2.5
Returns a random double value
in the range [0.0, 1.0). Math.abs(-2) returns 2
Math.abs(-2.1) returns
2.1
39
Stepwise Refinement (Optional)
The concept of method abstraction can be applied to the
process of developing programs. When writing a large
program, you can use the “divide and conquer” strategy,
also known as stepwise refinement, to decompose it into
subproblems. The subproblems can be further
decomposed into smaller, more manageable problems.
40
Ex. Program to check Test Void Grade
Print Calendar Example
Let us use the PrintCalendar example to demonstrate the
stepwise refinement approach.
42
Print Calendar Example
Let us use the PrintCalendar example to demonstrate the
stepwise refinement approach.
43
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
44
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
45
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
46
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
47
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
48
Design Diagram
printCalendar
(main)
readInput printMonth
printMonthTitle printMonthBody
getMonthName getStartDay
getTotalNumOfDays
getNumOfDaysInMonth
isLeapYear
49
Print Calendar Ex.
51
52
53
54
Arrays
Array is a data structure that represents a collection of the same types
of data.
1
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
myList reference
myList[0] 5.6
myList[1] 4.5
myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34
myList[7] 45.45
myList[8] 99.993
myList[9] 11123
2
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;
3
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
4
Declaring and Creating in One Step
5
The Length of an Array
Once an array is created, its size is fixed. It cannot be
changed. You can find its size using
arrayRefVar.length
For example,
myList.length returns 10
6
Default Values
When an array is created, its elements are
assigned the default value of
7
Indexed Variables
The array elements are accessed through the index.
The array indices are 0-based, i.e., it starts from 0 to
arrayRefVar.length-1. In the example, myList holds ten
double values and the indices are from 0 to 9.
arrayRefVar[index];
8
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].
9
Array Initializers
10
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;
11
Note
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;
13
Trace Program with Arrays
14
Trace Program with Arrays
15
Trace Program with Arrays
16
Trace Program with Arrays
17
Trace Program with Arrays
18
Trace Program with Arrays
19
Trace Program with Arrays
20
Trace Program with Arrays
21
Trace Program with Arrays
22
Trace Program with Arrays
23
Trace Program with Arrays
24
Trace Program with Arrays
25
Trace Program with Arrays
26
Trace Program with Arrays
27
Trace Program with Arrays
28
Trace Program with Arrays
29
Array Ex. 2
• Read list of items, get average, and how many number of array list
greater than average
30
Array Ex. 1
31
Concatenate Two Arrays using arraycopy
import java.util.Arrays;
public class Concat {
public static void main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};
int aLen = array1.length;
int bLen = array2.length;
int[] result = new int[aLen + bLen];
System.arraycopy(array1, 0, result, 0, aLen);
System.arraycopy(array2, 0, result, aLen, bLen);
System.out.println(Arrays.toString(result)); }}
Output
[1, 2, 3, 4, 5, 6]
Check if Int Array contains a given value
public class Contains {
public static void main(String[] args) {
int[] num = {1, 2, 3, 4, 5};
int toFind = 3;
boolean found = false;
for (int n : num) {
if (n == toFind) {
found = true;
break; } }
if(found)
System.out.println(toFind + " is found.");
else
System.out.println(toFind + " is not found."); }}
Output
3 is found.
Check if an array contains given value using Stream
import java.util.stream.IntStream;
public class Contains {
public static void main(String[] args) {
int[] num = {1, 2, 3, 4, 5};
int toFind = 7;
boolean found = IntStream.of(num).anyMatch(n -> n == toFind);
if(found)
System.out.println(toFind + " is found.");
else
System.out.println(toFind + " is not found."); }}
Output
7 is not found
Processing Arrays
Let us see list of examples:
1. (Initializing arrays with input values)
2. (Printing arrays)
3. (Summing all elements)
4. (Finding the largest element)
5. (Finding the smallest index of the largest element)
6. (Random shuffling)
7. (Shifting elements)
4
Initializing arrays with input values
5
Printing arrays
6
Summing all elements
7
Finding the largest element
8
Random shuffling
Swap 1st number in array with another random element from array
9
Shifting Elements
10
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:
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.
11
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[sourceArray.length];
12
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);
Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);
13
Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
Anonymous array
14
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.
16
Passing Arrays as Arguments
17
Passing Arrays as Arguments
18
Returning an Array from a Method
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
return result;
} result
19
Trace the reverse Method
int[] list1 = {1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
list 1 2 3 4 5 6
result 0 0 0 0 0 0
20
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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 0
21
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 0
22
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 0
23
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 1
24
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 1
25
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 0 1
26
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
27
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
28
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 0 2 1
29
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
30
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
31
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 0 3 2 1
32
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
33
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
34
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 0 4 3 2 1
35
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
36
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
37
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 0 5 4 3 2 1
38
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
39
Trace the reverse Method, cont.
int[] list1 = new int[]{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[list.length];
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
40
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
i (=6) < 6 is false. So exit the
public static int[] reverse(int[] list) { loop.
int[] result = new int[list.length];
return result;
}
list 1 2 3 4 5 6
result 6 5 4 3 2 1
41
Trace the reverse Method, cont.
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
Return result
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
return result;
}
list 1 2 3 4 5 6
list2
resul 6 5 4 3 2 1
t
42
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 < list.length; i++)
if (key == list[i]) [0] [1] [2] …
return i; list
return -1;
} key Compare key with list[i] for i = 0, 1, …
}
43
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.
44
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
45
Linear Search Examples
46
Linear Search Examples
47
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.
48
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.
49
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
50
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.
51
Binary Search Example
52
The Arrays.binarySearch 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 java.util.Arrays 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};
System.out.println("Index is " +
java.util.Arrays.binarySearch(list, 11));
Return is 4
char[] chars = {'a', 'c', 'g', 'x', 'y', 'z'};
System.out.println("Index is " +
java.util.Arrays.binarySearch(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.
53
Linear Search Example
Search for 2 in array {4, 5, 1, 2, 9, -3}
• 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 < list.length; i++) {
• if (key == list[i])
• return i;
• }
• return -1;
• }
• public static void main(String[] args) {
• int[] list = {4, 5, 1, 2, 9, -3};
• System.out.println(linearSearch(list, 2));
54
Binary Search Example
Binary search for 2 in list {-3, 1, 2, 4, 9, 23}
55
Sorting Arrays
Sorting, like searching, is also a common task in computer
programming. Many different algorithms have been
developed for sorting. This section introduces two simple,
sorting algorithms: selection sort and insertion sort.
1
Selection Sort
Selection sort finds the small number in the list and places it first. It then finds the smallest
number remaining and places it next to first, and so on until the list contains only a single
number. Figure below shows how to sort the list {2, 9, 5, 4, 8, 1, 6} using selection sort.
swap
3
Sort Array Method
Invoke it
selectionSort(yourList)
4
Selection Sort Example
5
Insertion Sort
int[] myList = {2, 9, 5, 4, 8, 1, 6}; // Unsorted
The insertion sort Step 1: Initially, the sorted sublist contains the 2 9 5 4 8 1 6
algorithm sorts a list first element in the list. Insert 9 to the sublist.
of values by
repeatedly inserting Step2: The sorted sublist is {2, 9}. Insert 5 to the 2 9 5 4 8 1 6
sublist.
an unsorted element
into a sorted sublist
Step 3: The sorted sublist is {2, 5, 9}. Insert 4 to 2 5 9 4 8 1 6
until the whole list the sublist.
is sorted.
Step 4: The sorted sublist is {2, 4, 5, 9}. Insert 8 2 4 5 9 8 1 6
to the sublist.
2 9 5 4 8 1 6
2 9 5 4 8 1 6
2 5 9 4 8 1 6
2 4 5 9 8 1 6
2 4 5 8 9 1 6
1 2 4 5 8 9 6
1 2 4 5 6 8 9
7
The Arrays.sort 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 java.util.Arrays class. For example, the following
code sorts an array of numbers and an array of characters.
8
Multidimensional Arrays
• Thus far, you have used one-dimensional arrays to model linear
collections of elements. You can use a two-dimensional array to
represent a matrix or a table.
9
Multidimensional Arrays
• For example, the following table that describes the distances between
the cities can be represented using a two-dimensional array.
10
Declare/Create Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;
// Alternative syntax
dataType refVar[][] = new dataType[10][10];
11
Declaring Variables of Two-dimensional
Arrays and Creating Two-dimensional Arrays
double[][] x;
12
Two-dimensional Array Illustration
0 1 2 3 4 0 1 2 3 4 0 1 2
0 0 0 1 2 3
1 1 1 4 5 6
2 2 7 2 7 8 9
3 3 3 10 11 12
4 4 int[][] array = {
{1, 2, 3},
matrix = new int[5][5]; matrix[2][1] = 7; {4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
matrix.length? 5 array.length? 4
matrix[0].length? 5 array[0].length? 3
13
Declaring, Creating, and Initializing Using Shorthand
Notations
int[][] array = {
int[][] array = new int[4][3];
{1, 2, 3}, array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, Same as array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};
14
Lengths of Two-dimensional Arrays
int[][] x = new int[3][4];
x
x[0][0] x[0][1] x[0][2] x[0][3] x[0].length is 4
x[0]
x[1] x[1][0] x[1][1] x[1][2] x[1][3] x[1].length is 4
x[2]
x[2][0] x[2][1] x[2][2] x[2][3] x[2].length is 4
x.length is 3
15
Lengths of Two-dimensional Arrays
int[][] array = { array.length
{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
16
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},
{2, 3, 4, 5}, matrix.length is 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
matrix[4].length is 1
{5}
};
17
Ragged Arrays
18
Example Two Dimensional array
• Write a program to read and array of 3 rows and four columns and
calculate the sum of all array elements
19
Example Program
20
Processing Two-Dimensional Arrays
Examples
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)
21
Initializing arrays with input values
22
Initializing arrays with random values
23
Printing arrays
24
Summing all elements
25
Summing elements by column
26
Random shuffling
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
int i1 = (int)(Math.random() * matrix.length);
int j1 = (int)(Math.random() * 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;
}
}
27
Two dimensional array example
• Write a program to print two dimensional array
• [3 4 5]
• [7 8 9]
Matrix Example
• Multiply two matrix
• For matrix multiplication to take place, the number of columns of first
matrix must be equal to the number of rows of second matrix. In our
example, i.e.
c1 = r2
• Also, the final product matrix is of size r1 x c2, i.e.
product[r1][c2]
How the output calculated
• In the above program, there are two functions:
• multiplyMatrices() which multiplies the two given matrices and returns the
product matrix
• displayProduct() which displayes the output of the product matrix on the
screen
• The multiplication takes places as
(a11 x b11) + (a12 x b21) + (a13 x b31) (a11 x b12) + (a12 x b22) + (a13 x b3
(a21 x b11) + (a22 x b21) + (a23 x b31) (a21 x b12) + (a22 x b22) + (a23 x b32
• Results as
(3 x 2) + (-2 x -9) + (5 x 0) = 24 (3 x 3) + (-2 x 0) + (5 x 4) = 29
(3 x 2) + ( 0 x -9) + (4 x 0) = 6 (3 x 3) + ( 0 x 0) + (4 x 4) = 25
Problem: Grading Multiple-Choice Test
• Objective: write a
Students’ Answers to the Questions:
program that grades
0 1 2 3 4 5 6 7 8 9
multiple-choice test.
Student 0 A B A C C D E E A D
Student 1 D B A B C A E E A D
Student 2 E D D A C B E E A D
Student 3 C B A E D C E E A D Key to the Questions:
Student 4 A B D C C D E E A D 0 1 2 3 4 5 6 7 8 9
Student 5 B B E C C D E E A D
Student 6 B B A C C D E E A D Key D B D C C D A E A D
Student 7 E B E C C D E E A D
35
Problem: Grading Multiple-Choice Test
36
Problem: Grading Multiple-Choice Test
37
Multidimensional Arrays
Occasionally, you will need to represent n-dimensional
data structures. In Java, you can create n-dimensional
arrays for any integer n.
39
Two Dimension Array Exa.
• Write a program to find the nearest two points
40
Two Dimension Array Exa.
41
Example
Write a program in Java to print such pattern like right angle
triangle with number increased by 1.The pattern like :
1
23
456
7 8 9 10
Consider no of rows =4
Pyramids Example
Write a program in Java to print such pattern like a pyramid with
a number which will repeat the number in the same row.
1
22
333
4444
No of rows 4
Multidimensional Arrays EX.
• Write a program to calculate temperature average, humidity average
for couple of days consider reading Tem. and humidity every hour
• Ex. No of days 2 and no of hours 3
Multidimensional Arrays EX.
• Write a program to guess the birthday using multidimensional array
String
• Java defines one operator for String objects: +. It is used to
concatenate two strings. For example, this statement String myString
= "I" + " like " + "Java.";
• Java program StringDemo
String
• The String class contains several methods that we can use. Here are a
few.
• We can test two strings for equality by using equals( ).
• We can obtain the length of a string by calling the length( ) method.
• We can obtain the character at a specified index within a string by
calling charAt( ). The general forms of these three methods are
shown here:
boolean equals(String object) int length( ) char charAt(int index)
Program StringDemo2 run these methods
String
• Of course, you can have arrays of strings, just like you can have arrays
of any other type of object. For example:
• String str[] = { "one", "two", "three" }
Object Oriented Programming
(OOPs) Concept in Java
• https://www.geeksforgeeks.org/object-oriented-programming-oops-
concept-in-java/
Polymorphism
61
Polymorphism
• Polymorphism: Polymorphism refers to the ability of OOPs programming
languages to differentiate between entities with the same name efficiently.
This is done by Java with the help of the signature and declaration of these
entities
67
• Encapsulation
An object encapsulates the methods and data that are contained
inside it .the rest of the system interacts with an object only through a
well defined set of services that it provides.
• Encapsulation 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.Other 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
Example
•.
• In the above program the class EncapsulateDemo is encapsulated as
the variables are declared as private. The get methods like getAge() ,
getName() , getRoll() are set as public, these methods are used to
access these variables. The setter methods like setName(), setAge(),
setRoll() are also declared as public and are used to set the values of
the variables.
• The program to access variables of the class EncapsulateDemo is
shown below:
Output:
Geek's name: Harsh
Geek's age: 19
Geek's roll: 51
Advantages of Encapsulation:
• Data Hiding: The user will have no idea about the inner implementation of
the class. It will not be visible to the user that how the class is storing
values in the variables. He only knows that we are passing the values to a
setter method and variables are getting initialized with that value.
• Increased Flexibility: We can make the variables of the class as read-only
or write-only depending on our requirement. If we wish to make the
variables as read-only then we have to omit the setter methods like
setName(), setAge() etc. from the above program or if we wish to make the
variables as write-only then we have to omit the get methods like
getName(), getAge() etc. from the above program
• Reusability: Encapsulation also improves the re-usability and easy to
change with new requirements.
• Testing code is easy: Encapsulated code is easy to test for unit testing.
Inheritance
75
Inheritance
Inheritance in Java
• 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.
Important terminology
• Super Class: The class whose features are inherited is known as super
class(or a base class or a parent class).
• Sub Class: The class that inherits the other class is known as sub class(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 Syntax
Syntax
class derived-class extends base-class
{
//methods and fields
}
Inheritance is the object-oriented programming concept where an
object is based on another object. Inheritance is the mechanism of
code reuse. The object that is getting inherited is called superclass and
the object that inherits the superclass is called subclass
Inheritance Example
• Example: In below example of inheritance, class Bicycle is a base
class, class MountainBike is a derived class which extends Bicycle class
and class Test is a driver class to run program.
Output:
• No of gears are 3
• speed of bicycle is 100
• seat height is 25
• In above program, when an object of MountainBike class is created, a
copy of the all methods and fields of the superclass acquire memory
in this object. That is why, by using the object of the subclass we can
also access the members of a superclass.
Please note that during inheritance only object of subclass is created,
not the superclass. For more, refer Java Object Creation of Inherited
Class.
• In practice, inheritance and polymorphism are used together in java
to achieve fast performance and readability of code.
• Illustrative image of the program:
Types of Inheritance in Java
There are different types of inheritance which is supported by Java
• Single Inheritance : In single inheritance, subclasses inherit the
features of one superclass. In image below, the class A serves as a
base class for the derived class B.
Types of Inheritance in Java
• Multilevel Inheritance :
In Multilevel Inheritance, a derived class will be inheriting a base class
and as well as the derived class also act as the base class to other class.
In below image, the class A serves as a base class for the derived class
B, which in turn serves as a base class for the derived class C. In Java, a
class cannot directly access the grandparent’s members.
access the grandparent’s members.
Types of Inheritance in Java
• Hierarchical Inheritance : In Hierarchical Inheritance, one class serves
as a superclass (base class) for more than one sub class.In below
image, the class A serves as a base class for the derived class B,C and
D.
• Multiple Inheritance (Through Interfaces) : In Multiple inheritance
,one class can have more than one superclass and inherit features
from all parent classes. Please note that Java does not support
multiple inheritance with classes. In java, we can achieve multiple
inheritance only through Interfaces. In image below, Class C is derived
from interface A and B
Abstraction
91
Data Abstraction
• An essential element of object-oriented programming is abstraction.
Humans manage complexity through abstraction. For example,
people do not think of a car as a set often of thousands of individual
parts. They think of it as a well-defined object with its own unique
behavior. This abstraction allows people to use a car to drive to the
grocery store without being overwhelmed by the complexity of the
parts that form the car. They can ignore the details of how the engine,
transmission, and braking systems work. Instead they are free to
utilize the object as a whole.
Data Abstraction
• 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.
• Consider a real-life example of a man driving a car. The man only
knows that pressing the accelerators will increase the speed of car or
applying brakes will stop the car but he does not know about how on
pressing the accelerator the speed is actually increasing, he does not
know about the inner mechanism of the car or the implementation of
accelerator, brakes etc in the car. This is what abstraction is.
Abstraction
• In java, abstraction is achieved by interfaces and abstract classes. We
can achieve 100% abstraction using interfaces.
Abstract classes and Abstract methods :
• An abstract class is a class that is declared with abstract keyword.
• An abstract method is a method that is declared without an implementation.
• An abstract class may or may not have all abstract methods. Some of them can be
concrete methods
• A method defined abstract must always be redefined in the subclass,thus making
overriding compulsory OR either make subclass itself abstract.
• Any class that contains one or more abstract methods must also be declared with
abstract keyword.
• There can be no object of an abstract class.That is, an abstract class can not be
directly instantiated with the new operator.
• An abstract class can have parametrized constructors and default constructor is
always present in an abstract class.
When to use abstract classes and abstract methods
with an example
• There are situations in which we will want to define a superclass that
declares the structure of a given abstraction without providing a complete
implementation of every method. That is, sometimes we will want to
create a superclass that only defines a generalization form that will be
shared by all of its subclasses, leaving it to each subclass to fill in the
details.
• Consider a classic “shape” example, perhaps used in a computer-aided
design system or game simulation. The base type is “shape” and each
shape has a color, size and so on. From this, specific types of shapes are
derived(inherited)-circle, square, triangle and so on – each of which may
have additional characteristics and behaviors. For example, certain shapes
can be flipped. Some behaviors may be different, such as when you want to
calculate the area of a shape. The type hierarchy embodies both the
similarities and differences between the shapes.
Program Output
Shape constructor called Circle
constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0
4
Encapsulation vs Data Abstraction
• Encapsulation is data hiding(information hiding) while Abstraction is
detail hiding(implementation hiding).
• While encapsulation groups together data and methods that act upon
the data, data abstraction deals with exposing the interface to the
user and hiding the details of implementation.
Advantages of Abstraction
• It reduces the complexity of viewing the things.
• Avoids code duplication and increases reusability.
• Helps to increase security of an application or program as only
important details are provided to the user.
Classes and Objects
7
Classes and Objects in Java
• Classes and Objects are basic concepts of Object Oriented
Programming which revolve around the real life entities.
Class
• A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common
to all objects of one type. In general, class declarations can include these
components, in order:
• Modifiers : A class can be public or has default access.
• Class name: The name should begin with a initial letter (capitalized by
convention).
• Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
• Interfaces(if any): A comma-separated list of interfaces implemented by
the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
• Body: The class body surrounded by braces, { }.
Class
• Constructors are used for initializing new objects. Fields are variables
that provides the state of the class and its objects, and methods are
used to implement the behavior of the class and its objects.
Object
• It is a basic unit of Object Oriented Programming and represents the
real life entities. A typical Java program creates many objects, which
as you know, interact by invoking methods. An object consists of :
• State : It is represented by attributes of an object. It also reflects the
properties of an object.
• Behavior : It is represented by methods of an object. It also reflects
the response of an object with other objects.
• Identity : It gives a unique name to an object and enables one object
to interact with other objects.
Example of an object : dog
• Objects correspond to things found in the real world. For example, a
graphics program may have objects such as “circle”, “square”, “menu”.
An online shopping system might have objects such as “shopping
cart”, “customer”, and “product”.
• Declaring Objects (Also called instantiating a class)
• When an object of a class is created, the class is said to be
instantiated. All the instances share the attributes and the behavior
of the class. But the values of those attributes, i.e. the state are
unique for each object. A single class may have any number of
instances.
Initializing an object
• The new operator instantiates a class by allocating memory for a new
object and returning a reference to that memory. The new operator
also invokes the class constructor.
GUI
Graphical User Interface
GUI (Graphical User Interface)
• Java Swing is a lightweight Graphical User Interface (GUI) toolkit that
includes a rich set of widgets. It includes package lets you make GUI
components for your Java applications, and It is platform
independent.
Java Swing Hierarchy Diagram
Java Swing Hierarchy Diagram
• GUI components are also called controls (e.g., Microsoft ActiveX Control),
widgets (e.g., Eclipse's Standard Widget Toolkit, Google Web Toolkit), which
allow users to interact with (or control) the application.
Top-Level Containers: Frame, Dialog and Applet
• Each GUI program has a top-level container. The commonly-used top-
level containers in AWT are Frame, Dialog and Applet:
• A Frame provides the "main window" for your GUI application. It has
a title bar (containing an icon, a title, the minimize, maximize/restore-
down and close buttons), an optional menu bar, and the content
display area. To write a GUI program, we typically start with a subclass
extending from java.awt. Let us see next example
GUI1 program
package gui1;
/** * * @author hanaa */
import javax.swing.*;
public class GUI1 {
30
Write a program with java swing to create two buttons with the names “start” and
“reset” and use the flow layout function to remove overlap.
package gui9;
import java.awt.*;
import javax.swing.*;
public class GUI9 {
public static void main(String[] args) {
JFrame frame = new JFrame("GUI Test one");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(450, 400);
JButton b1 = new JButton("Start");
JButton b2 = new JButton("Reset");
frame.getContentPane().add(b1);
frame.getContentPane().add(b2);
frame.setLayout(new FlowLayout(FlowLayout.CENTER));
frame.setVisible(true);} }
31
Java BorderLayout
• A BorderLayout places components in up to five areas: top, bottom,
left, right, and center. It is the default layout manager for every java
Jframe
Java FlowLayout
• FlowLayout is the default layout manager for every JPanel. It simply
lays out components in a single row one after the other.
Java GridBagLayout
• It is the more sophisticated of all layouts. It aligns components by
placing them within a grid of cells, allowing components to span more
than one cell.
GUI4
• Write a program to create the below menu
Tree in Java
• Write a program to represent a tree
• Vegetables is a folder as it have child and fruits is a folder as it have
child
• Press a folder it expands as in expanded tree
Program result
42
Select any item from swing controls drag it and drop it to the
container
Drag Button and Label, drop them in container and change its names
51
Write a program to demonstrates how to display text in
different fonts using setFont() method of Font class.
• Program result (Program name Main)
52
53
Example to display text(Font Name) in different fonts
(Program name (Main1)
54
55
56
Java GUI Palette
• Once the Jframe has been
created, we will find our
palette on the right hand side,
this will contain multiple tabs
for which we can use for our
GUI program.
• Two of the most important
tabs are the swing containers
and the swing controls.
57
Java GUI Palette (Swing Containers)
• For swing containers, it contains all the kinds of panels that is needed
in the program, dragging any component and putting it on the frame
is the ideal way to use it.
58
Java GUI Palette (Swing Containers)
• The normal panel in the swing containers is usually the most go to
component holder for anything needed, it doesn’t require anything
other than resizing and adding borders and a title to it, the other
types are usually for the more complex programming and design
ideas.
59
Java GUI Palette (Swing Controls)
• To start using Swing controls, first we add them to a panel, so that
those components would have their own parent and can be easily
moved, accessed and resized, so we can reach the optimal design
with ease.
• Firstly is the Label, the label as it would sound is a component used to
define a certain label for the user, we can just drag it into the panel
and rename it to make easy for us to use.
60
Adding panel into the frame
61
Adding the label into the panel
62
Swing Controls (Label)
To change the name of the label simply double click on it or in the
properties section bottom right of the screen, Click on “text” and
change the name of the “jlabel#” into whatever needed.
63
Swing Controls (Text Field)
Those are used, usually alongside the label, to let the user enter a value
or any sort, for example as a name, age, status, etc.
64
Swing Controls (Text Area)
Normally in a text field, you will only be able to write inputs in one short line,
for example a word or a number, but in the case of needing to write multiple
sentences or paragraphs, we would have to use text area, this swing control
provides me with everything necessary to let the user write as much as like in
the area provided.
65
Swing Controls (password field)
As you would normally guess, this field is specifically used for passwords, since
passwords need to be written by the user and not seen by others, it has to be
censored, and this is the job of this field, to censor what is written into dots so
that only the user would know what is entered, to make a login window much
easier and safer.
66
Swing Controls (Button)
The button is one of the most commonly used swing controls, because
it gives the ability for the user to use the button to enter, clear, exit,
basically whatever the programmer wants it to be.
67
Swing Controls ( Toggle button)
As the name would suggest, this button is used for toggle on and off, so
the button has only two states, it’s either on or off.
68
Swing Controls (Radio buttons and Radio buttons group)
This one is very helpful In making the user choose between multiple choices,
normally when they are picked, they will be single for each one of them, so we
would have to use radio buttons group in order to manage to group them
together as in not to be able to choose all of them, but to choose only one at a
time each time, radio buttons group would have been programmed through
coding too and not just picked into the program.
69
Swing Controls (Combo box)
Another method of being able to let the user chose between multiple choices
is the combo box, this method is usually preferred as it takes much less space
than the radio buttons and can take infinite number of choices as well.
70
Swing Controls (Check Box)
The check box is a very common and familiar thing that we all deal with almost
on a daily basis, it can either be grouped with another check boxes or be a single
check box for a specific ordeal or whatever task that needs to be done, so it has
two states either checked or unchecked.
71
String Class
1
String Class
• A String object is immutable: Its content cannot be changed once the
string is created.
• Strings are objects. You can invoke the charAt(index) method to
obtain a character at the specified index from a string, the length()
method to return the size of a string, the substring method to return
a substring in a string, and the indexOf and lastIndexOf methods to
return the first or last index of a matching character or a substring.
We will take a closer look at strings in this section.
• The String class has 13 constructors and more than 40 methods for
manipulating strings.
• Not only is it very useful in programming, but it is also a good
example for learning classes and objects.
2
Constructing a String
• You can create a string object from a string literal or from an array of
characters. To create a string from a string literal, use the syntax:
String newString = new String(stringLiteral);
• The argument stringLiteral is a sequence of characters enclosed inside
double quotes.
• The following statement creates a String object message for the string
literal "Welcome to Java":
String message = new String("Welcome to Java");
• Java treats string literal as an object thus the following string valid
String message = "Welcome to Java";
• Create string from an array to create array “Good Day”
char[] charArray = {'G', 'o', 'o', 'd', ' ', 'D', 'a', 'y'};
String message = new String(charArray);
3
Strings Are Immutable
A String object is immutable; its contents cannot be changed.
Does the following code change the contents of the string?
String s = "Java";
s = "HTML";
• The answer is no. The first statement creates a String object
with the content "Java" and assigns its reference to s. The
second statement creates a new String object with the
content "HTML" and assigns its reference to s. The first
String object still exists after the assignment, but it can no
longer be accessed, because variable s now points to the
new object, as shown below
4
Trace Code
String s = "Java";
s = "HTML";
5
Trace Code
String s = "Java";
s = "HTML";
6
Interned Strings
Since strings are immutable and are frequently used, to
improve efficiency and save memory, the JVM uses a
unique instance for string literals with the same character
sequence. Such an instance is called interned. For example,
the following statements:
7
String s1 = "Welcome to Java"; s1
: String
s3
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
8
Trace Code
s1
String s1 = "Welcome to Java"; : String
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
9
Trace Code
s1
String s1 = "Welcome to Java"; : String
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
s2 : String
A string object for
"Welcome to Java"
10
Trace Code
s1
String s1 = "Welcome to Java"; : String
s3
String s2 = new String("Welcome to Java"); Interned string object for
"Welcome to Java"
String s3 = "Welcome to Java";
s2 : String
A string object for
"Welcome to Java"
display
s1 == s2 is false
s1 == s3 is true
11
Replacing and Splitting Strings
• The String class provides the methods for replacing and splitting
strings, as shown in below figure
12
String Comparisons
java.lang.String
+equals(s1: String): boolean Returns true if this string is equal to string s1.
+equalsIgnoreCase(s1: String): Returns true if this string is equal to string s1 case-
boolean insensitive.
+compareTo(s1: String): int Returns an integer greater than 0, equal to 0, or less than 0
to indicate whether this string is greater than, equal to, or
less than s1.
+compareToIgnoreCase(s1: String): Same as compareTo except that the comparison is case-
int insensitive.
+regionMatches(toffset: int, s1: String, Returns true if the specified subregion of this string exactly
offset: int, len: int): boolean matches the specified subregion in string s1.
+regionMatches(ignoreCase: boolean, Same as the preceding method except that you can specify
toffset: int, s1: String, offset: int, whether the match is case-sensitive.
len: int): boolean
+startsWith(prefix: String): boolean Returns true if this string starts with the specified prefix.
+endsWith(suffix: String): boolean Returns true if this string ends with the specified suffix.
13
String Comparisons
• equals
if (s1.equals(s2)){
// s1 and s2 have the same contents
}
if (s1 == s2) {
// s1 and s2 have the same reference
}
14
String Comparisons, cont.
• compareTo(Object object)
if (s1.compareTo(s2) > 0) {
// s1 is greater than s2
}
else if (s1.compareTo(s2) == 0) {
// s1 and s2 have the same contents
}
else
// s1 is less than s2
15
String Length, Characters, and Combining Strings
java.lang.String
+length(): int Returns the number of characters in this string.
+charAt(index: int): char Returns the character at the specified index from this string.
+concat(s1: String): String Returns a new string that concatenate this string with string s1.
string.
16
Finding String Length
Finding string length using the length() method:
message = "Welcome";
message.length() (returns 7)
17
Retrieving Individual Characters in a String
Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message W e l c o m e t o J a v a
18
String Concatenation
String s3 = s1.concat(s2);
String s3 = s1 + s2;
s1 + s2 + s3 + s4 + s5 same as
(((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);
19
Extracting Substrings
java.lang.String
+subString(beginIndex: int): Returns this string’s substring that begins with the character at the
String specified beginIndex and extends to the end of the string, as
shown in Figure 8.6.
+subString(beginIndex: int, Returns this string’s substring that begins at the specified
endIndex: int): String beginIndex and extends to the character at index endIndex – 1, as
shown in Figure 8.6. Note that the character at endIndex is not
part of the substring.
20
Extracting Substrings
You can extract a single character from a string using the
charAt method. You can also extract a substring from a
string using the substring method in the String class.
Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
message W e l c o m e t o J a v a
java.lang.String
+toLowerCase(): String Returns a new string with all characters converted to lowercase.
+toUpperCase(): String Returns a new string with all characters converted to uppercase.
+trim(): String Returns a new string with blank characters trimmed on both sides.
+replace(oldChar: char, Returns a new string that replaces all matching character in this
newChar: char): String string with the new character.
+replaceFirst(oldString: String, Returns a new string that replaces the first matching substring in
newString: String): String this string with the new substring.
+replaceAll(oldString: String, Returns a new string that replace all matching substrings in this
newString: String): String string with the new substring.
+split(delimiter: String): Returns an array of strings consisting of the substrings split by the
String[] delimiter.
22
Examples
"Welcome".toLowerCase() returns a new string, welcome.
"Welcome".toUpperCase() returns a new string,
WELCOME.
" Welcome A".trim() returns a new string, WelcomeA.
"Welcome".replace('e', 'A') returns a new string, WAlcomA.
"Welcome".replaceFirst("e", "AB") returns a new string,
WABlcome.
"Welcome".replace("e", "AB") returns a new string,
WABlcomAB.
"Welcome".replace("el", "AB") returns a new string,
WABcome.
23
Splitting a String
String[] tokens = "Java#HTML#Perl".split("#", 0);
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " ");
displays
Java HTML Perl
24
Matching, Replacing and Splitting by Patterns
You can match, replace, or split a string by specifying a pattern.
This is an extremely useful and powerful feature, commonly
known as regular expression. Regular expression is complex to
beginning students. For this reason, two simple patterns are
used in this section.
"Java".matches("Java");
"Java".equals("Java");
"Java is fun".matches("Java.*");
"Java is cool".matches("Java.*");
25
Matching, Replacing and Splitting by Patterns
26
Matching, Replacing and Splitting by Patterns
27
Finding a Character or a Substring in a String
java.lang.String
+indexOf(ch: char): int Returns the index of the first occurrence of ch in the string.
Returns -1 if not matched.
+indexOf(ch: char, fromIndex: Returns the index of the first occurrence of ch after fromIndex in
int): int the string. Returns -1 if not matched.
+indexOf(s: String): int Returns the index of the first occurrence of string s in this string.
Returns -1 if not matched.
+indexOf(s: String, fromIndex: Returns the index of the first occurrence of string s in this string
int): int after fromIndex. Returns -1 if not matched.
+lastIndexOf(ch: int): int Returns the index of the last occurrence of ch in the string.
Returns -1 if not matched.
+lastIndexOf(ch: int, Returns the index of the last occurrence of ch before fromIndex
fromIndex: int): int in this string. Returns -1 if not matched.
+lastIndexOf(s: String): int Returns the index of the last occurrence of string s. Returns -1 if
not matched.
+lastIndexOf(s: String, Returns the index of the last occurrence of string s before
fromIndex: int): int fromIndex. Returns -1 if not matched.
28
Finding a Character or a Substring in a String
29
Convert Character and Numbers to Strings
30
• https://www.iare.ac.in/sites/default/files/lecture_notes/IARE_OOPS_
THROUGH_JAVA_LECTURE_NOTES.pdf
Objects and Classes
32
Motivations
After learning the preceding topics, you are capable of
solving many programming problems using selections,
loops, methods, and arrays. However, these Java features
are not sufficient for developing graphical user interfaces
and large scale software systems. Suppose you want to
develop a graphical user interface as shown below. How
do you program it?
33
Objectives
• To describe objects and classes, and use classes to model objects .
• To use UML graphical notations to describe classes and objects
• To demonstrate defining classes and creating objects .
• To create objects using constructors .
• To access objects via object reference variables .
• To define a reference variable using a reference type .
• To access an object’s data and methods using the object member access operator (.) .
• To define data fields of reference types and assign default values for an object’s data
fields .
• To distinguish between object reference variables and primitive data type variables .
• To use classes Date, Random, and JFrame in the Java library .
• To distinguish between instance and static variables and methods .
• To define private data fields with appropriate get and set methods .
• To encapsulate data fields to make classes easy to maintain .
• To develop methods with object arguments and differentiate between primitive-type
arguments and object-type arguments .
• To store and process objects in arrays .
34
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.
35
Object-Oriented Programming
• Object-oriented programming is an approach to building computer
programs that mimics how objects are assembled in the physical
world.
• By using this style of development, you can create programs that are
more reusable, reliable, and understandable.
• To get to that point, you first must explore how Java embodies the
principles of object oriented programming.
36
Object-Oriented Programming
For a real-life example of object-oriented design, consider a stereo system.
Most systems are built by hooking together a bunch of different objects,
which are more commonly called components, such as the following:
• Speaker components play midrange and high-frequency sounds.
• Subwoofer components play low bass frequency sounds.
• Tuner components receive radio broadcast signals.
• CD player components read audio data from CDs.
These components are designed to interact with each other using standard
input and output connectors. Even if you bought the speakers, subwoofer,
tuner, and CD player from different companies, you can combine them to
form a stereo system as long as they have standard connectors.
37
Object-Oriented Programming
• Object-oriented programming works under the same principle: You
put together a program by combining newly created objects and
existing objects in standard ways. Each object serves a specific role in
the overall program.
• An object is a self-contained element of a computer program that
represents a related group of features and is designed to accomplish
specific tasks.
38
Object-Oriented Programming
• Object-oriented programming organizes a program around its data
(that is, objects) and a set of well-defined interfaces to that data. An
object-oriented program can be characterized as data controlling
access to code. As you will see, by switching the controlling entity to
data, you can achieve several organizational benefits.
Objects and Classes
• Object-oriented programming is modeled on the observation that in the
physical world,
• objects are made up of many kinds of smaller objects.
• However, the capability to combine objects is only one aspect of object-
oriented programming. Another important feature is the use of classes.
• A class is a template used to create an object. Every object created from
the same class has similar features.
• Classes embody all features of a particular set of objects. When you write a
program in an object-oriented language, you don’t define individual
objects. Instead, you define classes used to create those objects.
40
Objects and Classes
• For example, you could create a Modem class that describes the features of
all computer modems. Most modems have the following common features:
• They connect to a computer’s serial port.
• They send and receive information.
• They dial phone numbers.
• The Modem class serves as an abstract model for the concept of a modem.
To actually have something concrete you can manipulate in a program, you
must use the Modem class to create a Modem object. The process of
creating an object from a class is called instantiation, which is why object
also are called instances.
• A Modem class can be used to create many different Modem objects in a
program, and each of these objects could have different features, such as
the following:
• Some are internal modems and others are external modems.
• Some use the COM1 port and others use the COM2 port.
• Some have error control, and others don’t.
41
Objects and Classes
• Even with these differences, two Modem objects still have enough in
common to be recognizable as related objects. Below figure shows a
Modem class and several objects created from that template.
42
Objects and Classes
• Another example: Using Java, you could create a class to represent all
command buttons—clickable boxes that appear on windows, dialog
boxes, and other parts of a program’s graphical user interface
• When the CommandButton class is developed, it could define these
features:
• The text displayed on the button
• The size of the button
• Aspects of its appearance, such as whether it has a 3D shadow
• The CommandButton class also could define how a button behaves,
deciding the following things:
• Whether the button requires a single click or a double-click
• Whether it should ignore mouse clicks entirely
• What it does when successfully clicked
43
Objects and Classes
• After you define the CommandButton class, you can create instances
of that button—in other words, CommandButton objects. The objects
all take on the basic features of a clickable button as defined by the
class, but each one could have a different appearance and slightly
different behavior depending on what you need that object to do.
• By creating a CommandButton class, you don’t have to keep rewriting
the code for each command button that you want to use in your
programs. In addition, you can reuse the CommandButton class to
create different kinds of buttons as you need them, both in this
program and in others
44
Objects and Classes
• When you write a Java program, you design and construct a set of
classes. When your program runs, objects are instantiated from those
classes and used as needed. Your task as a Java programmer is to
create the right set of classes to accomplish what your program needs
to accomplish.
• Fortunately, you don’t have to start from scratch. The Java language
includes thousands of classes that implement most of the
functionality you will need. These classes are called the Java class
library, and they are installed along with a development tool such as
the JDK.
45
Attributes and Behavior
• A Java class consists of two distinct types of information: attributes
and behavior.
• Behavior refers to the things that a class of objects can do to
themselves and other objects. Behavior can be used to change the
attributes of an object, receive information from other objects, and
send messages to other objects asking them to perform tasks.
• Behavior for a class of objects is implemented using methods.
46
Attributes of a Class of Objects
• A Java class consists of two distinct types of information: attributes
and behavior.
• Attributes are the data that differentiates one object from another.
They can be used to determine the appearance, state, and other
qualities of objects that belong to that class.
• A volcanic exploration vehicle could have the following attributes:
• Status—Exploring, moving, returning home
• Speed—Measured in miles per hour
• Temperature—Measured in Fahrenheit degrees
47
Object oriented programming
• Represent the real world
• Baby
Name
Sex
Weight
Decibels
# poops so far
48
• Objects group together
➢Primitives (int, double, char, etc..)
➢Objects (String, etc…)
• Baby
String name
boolean isMale
double weight
double decibels
int numPoops
49
Why use classes?
• Why not just primitives?
// little baby alex
String nameAlex;
double weightAlex;
// little baby david
String nameDavid;
double weightDavid;
// little baby david
String nameDavid2;
double weightDavid2;
50
51
52
53
54
55
56
57
58
59
Constructors
60
Constructors
61
Tree Example
• Write a program to draw the below tree
• Printing a Tree Example using Swing utility
62
63
64
65
Methods
• Methods are groups of related statements in a class that perform a
specific task. They are used to accomplish specific tasks on their own
objects and on other objects and are comparable to functions and
subroutines in other programming languages.
• Objects communicate with each other using methods. A class or an
object can call methods in another class or object for many reasons,
including the following:
➢To report a change to another object
➢To tell the other object to change something about itself
➢To ask another object to do something
66
Method
67
Class
68
Objects
Class Name: Circle A class template
Data Fields:
radius is _______
Methods:
getArea
70
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field
72
Example: Defining Classes and Creating
Objects
73
Example: Defining Classes and Creating
Objects
74
75
76
Constructors
Constructors are a special
Circle() {
}
kind of methods that are
invoked to construct
objects.
Circle(double newRadius) {
radius = newRadius;
}
77
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.
78
Creating Objects Using Constructors
new ClassName();
Example:
new Circle();
new Circle(5.0);
79
Default Constructor
A class may be declared without constructors. In
this case, a no-arg constructor with an empty
body is implicitly declared in the class. This
constructor, called a default constructor, is
provided automatically only if no constructors are
explicitly declared in the class.
80
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.
ClassName objectRefVar;
Example:
Circle myCircle;
81
Declaring/Creating Objects in a Single Step
82
Accessing Objects
• Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius
83
Trace Code
Declare myCircle
myCircle
84
Trace Code, cont.
myCircle no value
: Circle
radius: 5.0
Create a circle
85
Trace Code, cont.
: Circle
radius: 5.0
86
Trace Code, cont.
myCircle reference value
: Circle
radius: 5.0
yourCircle no value
Declare yourCircle
87
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle no value
: Circle
Create a new radius: 0.0
Circle object
88
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
value
myCircle reference
Circle yourCircle = new Circle();
radius: 5.0
referencevalue
yourCircle reference value
radius: 1.0
89
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
: Circle
Change radius in
yourCircle radius: 100.0
90
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.
92
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.
93
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.
94
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
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
radius = 1
96
Copying Variables of Primitive Data
Types and Object Types
Primitive type assignment i = j
Before: After:
i 1 i 2
j 2 j 2
Before: After:
c1 c1
c2 c2
97
Garbage Collection
As shown in the previous figure, after the
assignment statement c1 = c2, c1 points
to the same object referenced by c2. The
object previously referenced by c1 is no
longer referenced. This object is known as
garbage. Garbage is automatically
collected by JVM.
98
Garbage Collection, cont
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.
99
The Date Class
Java provides a system-independent encapsulation of date and
time in the java.util.Date 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.
java.util.Date
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.
100
The Date Class Example
For example, the following code
101
The Random Class
You have used Math.random() 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
java.util.Random class.
java.util.Random
+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.
102
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);
System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
System.out.print(random1.nextInt(1000) + " ");
Random random2 = new Random(3);
System.out.print("\nFrom random2: ");
for (int i = 0; i < 10; i++)
System.out.print(random2.nextInt(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
103
Instance
Variables, and Methods
104
Static Variables, Constants,
and Methods
Static variables are shared by all the instances of the
class.
105
Static Variables, Constants,
and Methods, cont.
106
Static Variables, Constants,
and Methods, cont.
instantiate
circle1 Memory
radius = 5 5 radius
UML Notation: numberOfObjects = 2
+: public variables or methods
underline: static variables or methods
107
Visibility Modifiers and Accessor/ Methods
• Constants in a class are shared by all objects of the class. Thus,
constants should be declared as final static. For example, the
constant PI in the Math class is defined as:
• final static double PI = 3.14159265358979323846;
• The new circle class, named CircleWithStaticMembers, is defined in
next ex.
108
109
EX.
• It is a common design error to define an instance method that should
have been defined as static. For example, the method factorial(int n)
should be defined as static, as shown next, because it is independent
of any specific instance.
111
Visibility Modifiers and Accessor/ 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.
The public modifier makes a method or variable completely
available to all classes. You have used it in every application
you have written so far, with a statement such as the
following:
public static void main(String[] arguments) {
// ...
}
112
Visibility Modifiers and Accessor/ Methods
• The main() method of an application has to be public.
Otherwise, it could not be called by a Java interpreter (such
as java) to run the class.
• Because of class inheritance, all public methods and
variables of a class are inherited by its subclasses.
• 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.
113
The private modifier makes methods and data fields accessible only from within its own
class. Figure illustrates how a public, default, and private data field or method in class
C1 can be accessed from a class C2 in the same package and from a class C3 in a different
package.
package p1; package p2;
public class C1 { public class C2 { public class C3 {
public int x; void aMethod() { void aMethod() {
int y; C1 o = new C1(); C1 o = new C1();
private int z; can access o.x; can access o.x;
can access o.y; cannot access o.y;
public void m1() { cannot access o.z; cannot access o.z;
}
void m2() { can invoke o.m1(); can invoke o.m1();
} can invoke o.m2(); cannot invoke o.m2();
private void m3() { cannot invoke o.m3(); cannot invoke o.m3();
} } }
} } }
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.
114
NOTE
115
Why Data Fields Should Be private?
To protect data.
116
Encapsulation
• Encapsulation is the process that prevents class variables from being
read or modified by other classes. The only way to use these variables
is by calling methods of the class, if they are available
117
Passing Objects to Methods
• You can pass objects to methods. Like passing an array, passing an object is actually passing the
reference of the object. The following code passes the myCircle object as an argument to the
printCircle method:
119
Array of Objects
Circle[] circleArray = new Circle[10];
… Circle object 1
121
Example
• You can create a Point2D object for a point with the specified x- and
y-coordinates, use the distance method to compute the distance
from this point to another point, and use the toString() method to
return a string representation of the point.
• Program name testpoint2d1
122
123
124
• This program creates two objects of the Point2D class (lines 15–16).
The toString()
• method returns a string that describes the object (lines 17–18).
Invoking p1.distance(p2)
• returns the distance between the two points (line 20).
125
The Character Class
java.lang.Character
127
Ex. What is the result of the below program
public class Testex {
Result
run:
3 /* the result 3 no of the uppercase letters
BUILD SUCCESSFUL (total time: 0 seconds)
128
Ex. What is the result of the below program
public class Test {
public static void main(String[] args) {
System.out.println("Hi, ABC, good".matches("ABC "));
System.out.println("Hi, ABC, good".matches(".*ABC.*"));
System.out.println("A,B;C".replaceAll(",;", "#"));
System.out.println("A,B;C".replaceAll("[,;]", "#"));
String[] tokens = "A,B;C".split("[,;]");
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " "); } }
Result
run:
false
true
A,B;C
A#B#C
ABC
BUILD SUCCESSFUL (total time: 0 seconds)
129
130
StringBuilder and StringBuffer
The StringBuilder/StringBuffer class is an
alternative to the String class. In general, a
StringBuilder/StringBuffer can be used wherever a string
is used. StringBuilder/StringBuffer is more flexible than
String. You can add, insert, or append new contents into
a string buffer, whereas the value of a String object is
fixed once the string is created.
131
StringBuilder and StringBuffer
• The StringBuilder class is similar to StringBuffer except that the
methods for modifying the buffer in StringBuffer are synchronized,
which means that only one task is allowed to execute the methods.
Use StringBuffer if the class might be accessed by multiple tasks
concurrently, because synchronization is needed in this case to
prevent corruptions.
132
StringBuilder Constructors
java.lang.StringBuilder
133
Modifying Strings in the Builder
java.lang.StringBuilder
+append(data: char[]): StringBuilder Appends a char array into this string builder.
+append(data: char[], offset: int, len: int): Appends a subarray in data into this string builder.
StringBuilder
+append(v: aPrimitiveType): StringBuilder Appends a primitive type value as a string to this
builder.
+append(s: String): StringBuilder Appends a string to this string builder.
+delete(startIndex: int, endIndex: int): Deletes characters from startIndex to endIndex.
StringBuilder
+deleteCharAt(index: int): StringBuilder Deletes a character at the specified index.
+insert(index: int, data: char[], offset: int, Inserts a subarray of the data in the array to the builder
len: int): StringBuilder at the specified index.
+insert(offset: int, data: char[]): Inserts data into this builder at the position offset.
StringBuilder
+insert(offset: int, b: aPrimitiveType): Inserts a value converted to a string into this builder.
StringBuilder
+insert(offset: int, s: String): StringBuilder Inserts a string into this builder at the position offset.
+replace(startIndex: int, endIndex: int, s: Replaces the characters in this builder from startIndex
String): StringBuilder to endIndex with the specified string.
+reverse(): StringBuilder Reverses the characters in the builder.
+setCharAt(index: int, ch: char): void Sets a new character at the specified index in this
134
builder.
Example Append
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("Welcome");
stringBuilder.append(' ');
stringBuilder.append("to");
stringBuilder.append(' ');
stringBuilder.append("Java");
135
Examples
stringBuilder.insert(11, "HTML and ");
Befor “Welcome to Java” after “Welcome to HTML and Java”
stringBuilder.delete(8, 11) changes the builder to Welcome Java.
delete from char 8 to 11
stringBuilder.deleteCharAt(8) changes the builder to Welcome o Java.
stringBuilder.reverse() changes the builder to avaJ ot emocleW.
stringBuilder.replace(11, 15, "HTML")
changes the builder to Welcome to HTML.
stringBuilder.setCharAt(0, 'w') sets the builder to welcome to Java.
136
The toString, capacity, length, setLength,
and charAt Methods
java.lang.StringBuilder
137
Problem: Finding Palindromes
138
Ex.
139
140
141
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:
142
Command-Line Parameters
class TestMain {
public static void main(String[] args) {
...
}
}
143
Processing Command-Line Parameters
144
Regular Expressions
146
Matching Strings
"Java".matches("Java");
"Java".equals("Java");
"Java is fun".matches("Java.*")
"Java is cool".matches("Java.*")
"Java is powerful".matches("Java.*")
147
Regular Expression Syntax
Regular Expression Matches Example
java.lang.String
+matches(regex: String): boolean Returns true if this string matches the pattern.
+replaceAll(regex: String, Returns a new string that replaces all
replacement: String): String matching substrings with the replacement.
+replaceFirst(regex: String, Returns a new string that replaces the first
replacement: String): String matching substring with the replacement.
+split(regex: String): String[] Returns an array of strings consisting of the
substrings split by the matches.
149
Examples
String s = "Java Java Java".replaceAll("v\\w", "wi") ;
String[] s = "Java1HTML2Perl".split("\\d");
150
The File Class
The File class is intended to provide an abstraction that
deals with most of the machine-dependent complexities
of files and path names in a machine-independent
fashion. The filename is a string. The File class is a
wrapper class for the file name and its directory path.
151
java.io.File
Obtaining file
properties and +File(pathname: String) Creates a File object for the specified pathname. The pathname may be a
directory or a file.
manipulating +File(parent: String, child: String) Creates a File object for the child under the directory parent. child may be a
file filename or a subdirectory.
+File(parent: File, child: String) Creates a File object for the child under the directory parent. parent is a File
object. In the preceding constructor, the parent is a string.
+exists(): boolean Returns true if the file or the directory represented by the File object exists.
+canRead(): boolean Returns true if the file represented by the File object exists and can be read.
+canWrite(): boolean Returns true if the file represented by the File object exists and can be written
+isDirectory(): boolean Returns true if the File object represents a directory.
+isFile(): boolean Returns true if the File object represents a file.
+isAbsolute(): boolean Returns true if the File object is created using an absolute path name.
+isHidden(): boolean Returns true if the file represented in the File object is hidden. The exact
definition of hidden is system-dependent. On Windows, you can mark a fil
hidden in the File Properties dialog box. On Unix systems, a file is hidden
its name begins with a period character '.'.
+getAbsolutePath(): String Returns the complete absolute file or directory name represented by the File
object.
+getCanonicalPath(): String Returns the same as getAbsolutePath() except that it removes redundant
names, such as "." and "..", from the pathname, resolves symbolic links (on
Unix platforms), and converts drive letters to standard uppercase (on Win3
platforms).
+getName(): String Returns the last name of the complete directory and file name represented by
the File object. For example, new File("c:\\book\\test.dat").getName() retur
test.dat.
+getPath(): String Returns the complete directory and file name represented by the File object.
For example, new File("c:\\book\\test.dat").getPath() returns c:\book\test.d
+getParent(): String Returns the complete parent directory of the current directory or the file
represented by the File object. For example, new
File("c:\\book\\test.dat").getParent() returns c:\book.
+lastModified(): long Returns the time that the file was last modified.
+delete(): boolean Deletes this
152 file. The method returns true if the deletion succeeds.
+renameTo(dest: File): boolean Renames this file. The method returns true if the operation succeeds.
Problem: Explore File Properties
Objective: Write a program that demonstrates how to
create files in a platform-independent way and use the
methods in the File class to obtain their properties. Figure
shows a sample run of the program on Windows, and a
sample run on Unix.
153
154
Explore File Properties Program Result
Does it exist? true
The file has 162 bytes
Can it be read? true
Can it be written? true
Is it a directory? false
Is it a file? true
Is it absolute? false
Is it hidden? false
Absolute path is C:\Users\Hanaa\Documents\NetBeansProjects\TestFileClass\image\us.gif
Last modified on Tue Mar 18 12:59:44 EET 2014
BUILD SUCCESSFUL (total time: 0 seconds)
155
156
Text I/O
A File object encapsulates the properties of a file or a
path, but does not contain the methods for
reading/writing data from/to a file. In order to perform
I/O, you need to create objects using appropriate Java I/O
classes. The objects contain the methods for
reading/writing data from/to a file. This section
introduces how to read/write strings and numeric values
from/to a text file using the Scanner and PrintWriter
classes.
157
Writing Data Using PrintWriter
java.io.PrintWriter
+PrintWriter(filename: String) Creates a PrintWriter for the specified file.
+print(s: String): void Writes a string.
+print(c: char): void Writes a character.
+print(cArray: char[]): void Writes an array of character.
+print(i: int): void Writes an int value.
+print(l: long): void Writes a long value.
+print(f: float): void Writes a float value.
+print(d: double): void Writes a double value.
+print(b: boolean): void Writes a boolean value.
Also contains the overloaded A println method acts like a print method; additionally it
println methods. prints a line separator. The line separator string is defined
Also contains the overloaded by the system. It is \r\n on Windows and \n on Unix.
printf methods. The printf method was introduced in §3.6, “Formatting
Console Output and Strings.”
.
158
Writing Data Using PrintWriter
159
Writing Data Using PrintWriter
• Program Result
160
Reading Data Using Scanner
java.util.Scanner
+Scanner(source: File) Creates a Scanner that produces values scanned from the specified file.
+Scanner(source: String) Creates a Scanner that produces values scanned from the specified string.
+close() Closes this scanner.
+hasNext(): boolean Returns true if this scanner has another token in its input.
+next(): String Returns next token as a string.
+nextByte(): byte Returns next token as a byte.
+nextShort(): short Returns next token as a short.
+nextInt(): int Returns next token as an int.
+nextLong(): long Returns next token as a long.
+nextFloat(): float Returns next token as a float.
+nextDouble(): double Returns next token as a double.
+useDelimiter(pattern: String): Sets this scanner’s delimiting pattern.
Scanner
161
Reading Data Using Scanner
162
Reading Data Using Scanner
163
Chapter 8
Objects and Classes
164
Motivations
After learning the preceding chapters, you are capable of
solving many programming problems using selections,
loops, methods, and arrays. However, these Java features
are not sufficient for developing graphical user interfaces
and large scale software systems. Suppose you want to
develop a graphical user interface as shown below. How
do you program it?
165
Objectives
• To describe objects and classes, and use classes to model objects
• To use UML graphical notations to describe classes and objects
• To demonstrate defining classes and creating objects
• To create objects using constructors
• To access objects via object reference variables
• To define a reference variable using a reference type
• To access an object’s data and methods using the object member access operator
• To define data fields of reference types and assign default values for an object’s
data fields
• To distinguish between object reference variables and primitive data type
variables
• To use classes Date, Random, and JFrame in the Java library
• To distinguish between instance and static variables and methods
• To define private data fields with appropriate get and set methods
• To encapsulate data fields to make classes easy to maintain
• To develop methods with object arguments and differentiate between primitive-
type arguments and object-type arguments
• To store and process objects in arrays
166
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.
167
Objects
Class Name: Circle A class template
Data Fields:
radius is _______
Methods:
getArea
168
Classes
169
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field
171
Example: Defining Classes and
Creating Objects
172
Example
• This section gives two examples of defining classes and uses the
classes to create objects.
• A program that defines the Circle class and uses it to create objects.
The program constructs three circle objects with radius 1, 25, and 125
and displays the radius and area of each of the three circles. It then
changes the radius of the second object to 100 and displays its new
radius and area.
173
174
175
Constructors
Constructors are a special
Circle() {
}
kind of methods that are
invoked to construct
objects.
Circle(double newRadius) {
radius = newRadius;
}
176
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.
177
Creating Objects Using
Constructors
new ClassName();
Example:
new Circle();
new Circle(5.0);
178
Default Constructor
A class may be declared without constructors. In
this case, a no-arg constructor with an empty
body is implicitly declared in the class. This
constructor, called a default constructor, is
provided automatically only if no constructors are
explicitly declared in the class.
179
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.
ClassName objectRefVar;
Example:
Circle myCircle;
180
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
181
Accessing Objects
• Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius
182
Trace Code
Declare myCircle
yourCircle.radius = 100;
183
animation
Trace Code, cont.
radius: 5.0
Create a circle
184
animation
Trace Code, cont.
185
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle no value
Declare yourCircle
186
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle no value
: Circle
Create a new radius: 0.0
Circle object
187
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
radius: 1.0
188
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
: Circle
Change radius in
yourCircle radius: 100.0
189
Caution
Recall that you use
Math.methodName(arguments) (e.g., Math.pow(3, 2.5))
to invoke a method in the Math class. Can you invoke getArea() using
Circle1.getArea()? 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
191
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.
192
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.
193
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
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
radius = 1
195
Copying Variables of Primitive
Data Types and Object Types
Primitive type assignment i = j
Before: After:
i 1 i 2
j 2 j 2
Before: After:
c1 c1
c2 c2
196
Garbage Collection
As shown in the previous figure, after the
assignment statement c1 = c2, c1 points
to the same object referenced by c2. The
object previously referenced by c1 is no
longer referenced. This object is known as
garbage. Garbage is automatically
collected by JVM.
197
Garbage Collection, cont
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.
198
The Date Class
Java provides a system-independent encapsulation of date and
time in the java.util.Date 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.
java.util.Date
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.
199
The Date Class Example
For example, the following code
200
The Random Class
You have used Math.random() 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
java.util.Random class.
java.util.Random
+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.
201
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);
System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
System.out.print(random1.nextInt(1000) + " ");
Random random2 = new Random(3);
System.out.print("\nFrom random2: ");
for (int i = 0; i < 10; i++)
System.out.print(random2.nextInt(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
202
Displaying GUI Components
When you develop programs to create graphical user
interfaces, you will use Java classes such as JFrame, JButton,
JRadioButton, JComboBox, and JList to create frames,
buttons, radio buttons, combo boxes, lists, and so on. Here
is an example that creates two windows using the JFrame
class.
TestFrame Run
203
animation
Trace Code Declare, create,
and assign in one
statement
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); JFrame frame2 = title:
new JFrame(); frame2.setTitle("Window 2"); width:
frame2.setSize(200, 150); height:
frame2.setVisible(true); visible:
204
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1"); Set title property
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); JFrame frame2 = title: "Window 1"
new JFrame(); frame2.setTitle("Window 2"); width:
frame2.setSize(200, 150); height:
frame2.setVisible(true); visible:
205
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame Set size property
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible:
frame2.setVisible(true);
206
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200 Set visible
frame2.setTitle("Window 2"); height: 150 property
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);
207
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);
Declare, create,
frame2 reference and assign in one
statement
: JFrame
title:
width:
height:
visible:
208
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);
frame2 reference
Set title property
: JFrame
title: "Window 2"
width:
height:
visible:
209
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);
frame2 reference
: JFrame
title: "Window 2" Set size property
width: 200
height: 150
visible:
210
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);
frame2 reference
: JFrame
title: "Window 2"
Set visible
width: 200
property
height: 150
visible: true
211
Adding GUI Components to Window
You can add graphical user interface components, such as
buttons, labels, text fields, combo boxes, lists, and menus,
to the window. The components are defined using classes.
Here is an example to create buttons, labels, text fields,
check boxes, radio buttons, and combo boxes.
GUIComponents Run
212
Instance
Variables, and Methods
213
Static Variables, Constants,
and Methods
Static variables are shared by all the instances of the
class.
214
Static Variables, Constants,
and Methods, cont.
215
Static Variables, Constants,
and Methods, cont.
instantiate
circle1 Memory
radius = 5 5 radius
UML Notation: numberOfObjects = 2
+: public variables or methods
underline: static variables or methods
216
Example of
Using Instance and Class Variables and
Method
Objective: Demonstrate the roles of
instance and class variables and their
uses. This example adds a class variable
numberOfObjects to track the number of
Circle objects created.
Circle2
TestCircle2 Run
217
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.
218
package p1; package p2;
public class C1 { public class C2 { public class C3 {
public int x; void aMethod() { void aMethod() {
int y; C1 o = new C1(); C1 o = new C1();
private int z; can access o.x; can access o.x;
can access o.y; cannot access o.y;
public void m1() { cannot access o.z; cannot access o.z;
}
void m2() { can invoke o.m1(); can invoke o.m1();
} can invoke o.m2(); cannot invoke o.m2();
private void m3() { cannot invoke o.m3(); cannot invoke o.m3();
} } }
} } }
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.
219
NOTE
220
Why Data Fields Should Be
private?
To protect data.
221
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.
222
Passing Objects to Methods
TestPassObject Run
223
Passing Objects to Methods, cont.
224
Array of Objects
Circle[] circleArray = new Circle[10];
… Circle object 1
226
Array of Objects, cont.
Summarizing the areas of the circles
TotalArea Run
227
Objects and Classes
1
Motivations
After learning the preceding chapters, you are capable of
solving many programming problems using selections,
loops, methods, and arrays. However, these Java features
are not sufficient for developing graphical user interfaces
and large scale software systems. Suppose you want to
develop a graphical user interface as shown below. How
do you program it?
2
Objectives
• To describe objects and classes, and use classes to model objects
• To use UML graphical notations to describe classes and objects
• To demonstrate defining classes and creating objects
• To create objects using constructors
• To access objects via object reference variables
• To define a reference variable using a reference type
• To access an object’s data and methods using the object member access operator
• To define data fields of reference types and assign default values for an object’s
data fields
• To distinguish between object reference variables and primitive data type
variables
• To use classes Date, Random, and JFrame in the Java library
• To distinguish between instance and static variables and methods
• To define private data fields with appropriate get and set methods
• To encapsulate data fields to make classes easy to maintain
• To develop methods with object arguments and differentiate between primitive-
type arguments and object-type arguments
• To store and process objects in arrays
3
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.
4
Objects
Class Name: Circle A class template
Data Fields:
radius is _______
Methods:
getArea
5
Classes
6
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field
8
Example: Defining Classes and
Creating Objects
9
Example
• This section gives two examples of defining classes and uses the
classes to create objects.
• A program that defines the Circle class and uses it to create objects.
The program constructs three circle objects with radius 1, 25, and 125
and displays the radius and area of each of the three circles. It then
changes the radius of the second object to 100 and displays its new
radius and area.
10
11
12
Constructors
Constructors are a special
Circle() {
}
kind of methods that are
invoked to construct
objects.
Circle(double newRadius) {
radius = newRadius;
}
13
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.
14
Creating Objects Using
Constructors
new ClassName();
Example:
new Circle();
new Circle(5.0);
15
Default Constructor
A class may be declared without constructors. In
this case, a no-arg constructor with an empty
body is implicitly declared in the class. This
constructor, called a default constructor, is
provided automatically only if no constructors are
explicitly declared in the class.
16
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.
ClassName objectRefVar;
Example:
Circle myCircle;
17
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
18
Accessing Objects
• Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius
19
Trace Code
Declare myCircle
yourCircle.radius = 100;
20
animation
Trace Code, cont.
radius: 5.0
Create a circle
21
animation
Trace Code, cont.
22
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle no value
Declare yourCircle
23
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle no value
: Circle
Create a new radius: 0.0
Circle object
24
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
radius: 1.0
25
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
: Circle
Change radius in
yourCircle radius: 100.0
26
Caution
Recall that you use
Math.methodName(arguments) (e.g., Math.pow(3, 2.5))
to invoke a method in the Math class. Can you invoke getArea() using
Circle1.getArea()? 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
28
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.
29
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.
30
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
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
radius = 1
32
Copying Variables of Primitive
Data Types and Object Types
Primitive type assignment i = j
Before: After:
i 1 i 2
j 2 j 2
Before: After:
c1 c1
c2 c2
33
Garbage Collection
As shown in the previous figure, after the
assignment statement c1 = c2, c1 points
to the same object referenced by c2. The
object previously referenced by c1 is no
longer referenced. This object is known as
garbage. Garbage is automatically
collected by JVM.
34
Garbage Collection, cont
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.
35
The Date Class
Java provides a system-independent encapsulation of date and
time in the java.util.Date 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.
java.util.Date
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.
36
The Date Class Example
For example, the following code
37
The Random Class
You have used Math.random() 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
java.util.Random class.
java.util.Random
+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.
38
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);
System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
System.out.print(random1.nextInt(1000) + " ");
Random random2 = new Random(3);
System.out.print("\nFrom random2: ");
for (int i = 0; i < 10; i++)
System.out.print(random2.nextInt(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
39
Displaying GUI Components
When you develop programs to create graphical user
interfaces, you will use Java classes such as JFrame, JButton,
JRadioButton, JComboBox, and JList to create frames,
buttons, radio buttons, combo boxes, lists, and so on. Here
is an example that creates two windows using the JFrame
class.
TestFrame Run
40
animation
Trace Code Declare, create,
and assign in one
statement
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); JFrame frame2 = title:
new JFrame(); frame2.setTitle("Window 2"); width:
frame2.setSize(200, 150); height:
frame2.setVisible(true); visible:
41
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1"); Set title property
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); JFrame frame2 = title: "Window 1"
new JFrame(); frame2.setTitle("Window 2"); width:
frame2.setSize(200, 150); height:
frame2.setVisible(true); visible:
42
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame Set size property
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible:
frame2.setVisible(true);
43
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200 Set visible
frame2.setTitle("Window 2"); height: 150 property
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);
44
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);
Declare, create,
frame2 reference and assign in one
statement
: JFrame
title:
width:
height:
visible:
45
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);
frame2 reference
Set title property
: JFrame
title: "Window 2"
width:
height:
visible:
46
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);
frame2 reference
: JFrame
title: "Window 2" Set size property
width: 200
height: 150
visible:
47
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150); : JFrame
frame1.setVisible(true); title: "Window 1"
JFrame frame2 = new JFrame(); width: 200
frame2.setTitle("Window 2"); height: 150
frame2.setSize(200, 150); visible: true
frame2.setVisible(true);
frame2 reference
: JFrame
title: "Window 2"
Set visible
width: 200
property
height: 150
visible: true
48
Adding GUI Components to Window
You can add graphical user interface components, such as
buttons, labels, text fields, combo boxes, lists, and menus,
to the window. The components are defined using classes.
Here is an example to create buttons, labels, text fields,
check boxes, radio buttons, and combo boxes.
GUIComponents Run
49
Instance
Variables, and Methods
50
Static Variables, Constants,
and Methods
Static variables are shared by all the instances of the
class.
51
Static Variables, Constants,
and Methods, cont.
52
Static Variables, Constants,
and Methods, cont.
instantiate
circle1 Memory
radius = 5 5 radius
UML Notation: numberOfObjects = 2
+: public variables or methods
underline: static variables or methods
53
Example of
Using Instance and Class Variables and
Method
Objective: Demonstrate the roles of
instance and class variables and their
uses. This example adds a class variable
numberOfObjects to track the number of
Circle objects created.
Circle2
TestCircle2 Run
54
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.
55
package p1; package p2;
public class C1 { public class C2 { public class C3 {
public int x; void aMethod() { void aMethod() {
int y; C1 o = new C1(); C1 o = new C1();
private int z; can access o.x; can access o.x;
can access o.y; cannot access o.y;
public void m1() { cannot access o.z; cannot access o.z;
}
void m2() { can invoke o.m1(); can invoke o.m1();
} can invoke o.m2(); cannot invoke o.m2();
private void m3() { cannot invoke o.m3(); cannot invoke o.m3();
} } }
} } }
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.
56
NOTE
57
Why Data Fields Should Be
private?
To protect data.
58
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.
59
Passing Objects to Methods
TestPassObject Run
60
Passing Objects to Methods, cont.
61
Array of Objects
Circle[] circleArray = new Circle[10];
… Circle object 1
63
Array of Objects, cont.
Summarizing the areas of the circles
TotalArea Run
64