Revision Slide Test 1
Revision Slide Test 1
to Object-oriented
programming and software
development
Lecture 1 – Part 1
Based on Slides of Dr. Norazah Yusof
Procedural Programming
n Traditional programming languages were
procedural.
n C, Pascal, BASIC, Ada and COBOL
n Programming in procedural languages
involves choosing data structures
(appropriate ways to store data), designing
algorithms, and translating algorithm into
code.
2
Procedural Programming
n In procedural programming, data and
operations on the data are separated.
n This methodology requires sending data to
procedure/functions.
3
Procedural Programming
Data Element
Function A Function B
4
Object-Oriented Programming
n Object-oriented programming (OOP) is
centered on creating objects rather than
procedures/ functions.
n Objects are a melding of data and procedures
that manipulate that data.
n Data in an object are known as attributes.
n Procedures/functions in an object are known
as methods.
5
Object-Oriented Programming
Object
Attributes (data)
Methods
(behaviors / procedures) 6
Object-Oriented Programming
n Object-oriented programming combines data and
behavior (or method) via encapsulation.
n Data hiding is the ability of an object to hide data
from other objects in the program.
n Only an objects methods should be able to directly
manipulate its attributes.
n Other objects are allowed to manipulate an object’s
attributes via the object’s methods.
n This indirect access is known as a programming
interface.
7
Object-Oriented Programming
Object
Attributes (data)
Programming typically private to this object
Interface
Other
objects
Methods
8
(behaviors / procedures)
Object-Oriented Programming
Languages
· Pure OO Languages
Smalltalk, Eiffel, Actor, Java
· Hybrid OO Languages
C++, Objective-C, Object-Pascal
9
The Vocabulary of OOP - Class
n The most important term is the class.
n A class is the template or blueprint from which objects
are actually made.
n All codes that you write in Java is inside a class.
n The standard Java library supplies several thousand
classes.
n You can create your own classes in Java to describe
the objects of the problem domains of your applications
and to adapt the classes that are supplied by the
standard library to your own purposes.
n A class encapsulates the attributes and actions that
11
Classes and Objects
The Vehicle class defines the
attributes and methods that Kancil object
will exist in all objects
The Kancil object is an
that are an instances of the instance of the Car class.
vehicle class.
Car class
The Nazaria object is an
instance of the Car class.
Nazaria object
12
The Vocabulary of OOP -
Encapsulation
n Encapsulation is a key concept in working with objects.
n Combining data and behavior in one package and
hiding the implementation of the data from the user of
the object.
n The data in an object are called its instance fields,
and the procedures that operate on the data are
called its methods.
n The key to making encapsulation work is to have
methods never directly access instance fields in a
class other than their own.
n Programs should interact with object data only
through the object's methods.
n By encapsulating object data, you maximize
reusability, reduce data dependency, and minimize
debugging time. 13
The Vocabulary of OOP –
Data Hiding
n Data hiding is important for several reasons.
n It protects of attributes from accidental
corruption by outside objects.
n It hides the details of how an object works, so
the programmer can concentrate on using it.
n It allows the maintainer of the object to have
the ability to modify the internal functioning of
the object without “breaking” someone else's
code.
14
The Vocabulary of OOP –
Code Reusability
n Object-Oriented Programming (OOP) has encouraged
component reusability.
n A component is a software object contains data and
methods that represents a specific concept or service.
n Components typically are not stand-alone programs.
n Components can be used by programs that need the
component’s service.
n Reuse of code promotes the rapid development of larger
software projects.
15
The Vocabulary of OOP – Inheritance
n Inheritance is the ability of one class to extend the
capabilities of another.
n it allows code defined in one class to be
reused in other classes
n Consider the class Car. A Car is a specialized form
of the Vehicle class.
n So, is said that the Vehicle class is the base or parent
class of the Car class.
n The Car class is the derived or child class of the
Vehicle class.
16
The Vocabulary of OOP - Inheritance
Vehicle represents all
of the generic attributes Vehicle is the
Vehicle parent class.
and methods of a vehicle.
is-a relationship
Car and Truck are Car and Truck are
child classes of Car Truck Specialized versions of
Vehicle. a Vehicle.
17
The Vocabulary of OOP –
Polymorphism
n Polymorphism means "many forms."
n A reference variable is always of a single,
unchangeable type, but it can refer to a
subtype object.
n A single object can be referred to by reference
variables of many different types—as long as
they are the same type or a supertype of the
object. The reference variable's type (not the
object's type), determines which methods can
be called!
n Polymorphism allows extensibility.
18
Self-test: Introduction to Object Oriented
Programming
1. State the differences between procedural
programming and Object Oriented
Programming.
2. What is an Object and what is a Class?
What is the difference between them?
3. What is an Attribute?
4. What is a Method?
5. What is encapsulation? How it relates to
information hiding?
6. What is inheritance? How it relates to
polymorphism?
19
Introduction to Object-oriented
programming and software
development
Lecture 1- Part 2
Based on Slides of Dr. Norazah Yusof
Object Orientation Principle
n Divide-and-conquer
n Encapsulation and Modularity
n Public Interface
n Information Hiding
n Generality
n Extensibility
n Abstraction
21
Principles of Object Orientation
n Divide-and-Conquer Principle
n The first step in designing a program is to divide
the overall program into a number of objects that
will interact with each other to solve the problem.
n Problem solving: Break problems (programs) into
small, manageable tasks.
22
Principles of Object Orientation
n Encapsulation Principle
n The next step in designing a program is to decide
for each object, what attribute it has and what
actions it will take.
n The goal is that each object is a self-contained
module with a clear responsibility and the
attributes and actions necessary to carry out its
role
n Problem solving: Each object knows how to solve
its task and has the information it needs.
23
Principles of Object Orientation
(cont)
n Interface Principle
n For object to work cooperatively and efficiently, we
have to clarify exactly how they are to interact, or
interface, with one another.
n Each object should present a clear public interface
that determines how other objects will be used.
24
Principles of Object Orientation
(cont)
n Information Hiding Principle
n To enable objects to work together cooperatively,
certain details of their individual design and
performance should be hidden from other objects.
n Each object should shield its users from
unnecessary details of how it performs its role.
25
Principles of Object Orientation
(cont)
n Generality Principle
n To make an object as generally useful as possible,
we design them not for a particular task but rather for
a particular kind of task. This principle underlies the
use of software libraries.
n Objects should be designed to be as general as
possible.
n Objects are designed to solve a kind of task rather
than a singular task.
26
Principles of Object Orientation
(cont)
n Extensibility Principle
n One of the strength of the object-oriented approach
is the ability to extend an object’s behavior to handle
new tasks.
n An object should be designed so that their
functionality can be extended to carry out more
specialized tasks.
27
Principles of Object Orientation
(cont)
28
Benefits of Object-oriented
programming
n Save development time (and cost) by reusing code
n once an object class is created it can be used
in other applications
n Easier debugging
n classes can be tested independently
n reused objects have already been tested
29
Self-test: Introduction to Object Oriented
Programming
1. What are the seven basic principles of object
orientation? Provide a brief description of
each.
2. State the benefits of object oriented
programming.
30
Introduction to JAVA
Programming Language
Lecture 2
Based on Slides of Dr. Norazah Yusof
31
Origins of the Java Language
n Java was created by Sun Microsystems team led by Patrick
Naughton and James Gosling (1991)
n Originally named Oak (Gosling liked the look of an oak tree that
was right outside his window at Sun)
n Intended to design a small computer language that could be
used for consumer devices/appliances such as the cable TV
switchboxes.
n It is a difficult task because these devices do not have a lot
of power or memory, the language had to be small and
generate very tight code. Also, because different
manufacturers may choose different central processing units
(CPUs), it was important that the language not be tied to any
single architecture.
n The team developed a two-step translation process to simplify
the task of compiler writing for each class of appliances
32
Origins of the Java Language
n Significance of Java translation process
n Writing a compiler (translation program) for each
type of appliance processor would have been very
costly
n Instead, developed intermediate language that is the
same for all types of processors : Java byte-code
n Therefore, only a small, easy to write program was
needed to translate byte-code into the machine code
for each processor
33
Origins of the Java Language
n Patrick Naughton and Jonathan Payne at Sun
Microsystems developed a Web browser that could
run programs over the Internet (1994) and evolved
into the HotJava browser.
n Beginning of Java's connection to the Internet
n To show off the power of applets, they made the
browser capable of executing code inside web
pages.
n Netscape Incorporated made its Web browser
capable of running Java programs (1995)
n Other companies follow suit
34
The Java Language
n Java is a full-featured, general-purpose programming
language that is capable of developing robust mission-
critical applications.
n Today it is used for developing stand alone applications,
desktops, web programming, servers, and mobile
devices.
n Java can be run on the web browser called the applets.
n Java can also be used to develop applications on the
server side, called Java servlets or Javaserver pages
(JSP)
n Java can be used to develop applications for small hand-
held devices, such as personal digital assistants and cell
phones.
35
The Java Language Specification
n Java language specification defines the Java standard
and the technical definition of the language that includes
the syntax and semantics of the Java programming
language.
n stable
n Java application program interface (API) contains
predefined classes and interfaces for developing Java
programs.
n Still expanding
36
Java API
n Java 1.0 was introduced in 1995.
n December 1998, Sun announced the Java 2 platform –
the brand that applies to current Java technology.
n There are 3 editions of the Java API:
n Java 2 standard edition (J2SE)
n client-side standalone applications or applets
n Java 2 Enterprise Edition (J2EE)
n server-side applications, such as Java servlets and
JavaServer Pages
n Java 2 Micro Edition (J2ME)
n mobile devices, such as cell phones
37
Java Language
38
Java API
39
J2SE version
n There are many versions of J2SE.
n The latest version is J2SE 6.0.
n Sun releases each version of J2SE with a Java
Development toolkit (JDK)
n For J2SE 5.0, the Java development toolkit is called JDK
5.0 – formerly was known as JDK1.5
n JDK consists of a set of separate programs for
developing and testing Java programs, each of which is
invoked from a command line.
40
Java Development Tools
n Java development tool is a software that provides an integrated development
environment (IDE) for rapidly developing Java programs.
n Other Java development tools on the market (besides JDK 5.0):
n JBuilder by Borland
n NetBeans Open Source by Sun
n Eclipse Open Source by IBM
n Other useful tools:
n Code warrior by Metrowerks
n TextPad Editor
n JCreator LE
n JEdit
n JGrasp
n BlueJ
n DrJava
41
Java Program
n Java program can be written in many ways:
n Applications
n Applets
n Servlets
42
Java Applications
n A Java applications or "regular" Java programs are
standalone programs that can be executed from any
computer with a JVM.
n It is a class with a method named main
n When a Java application program is run, the run-time
system automatically invokes the method named main
n All Java application programs start with the main
method
43
Java Applets
n A Java applet (little Java application) is a Java
program that is meant to be run from a Web browser
n Can be run from a location on the Internet
n Can also be run with an applet viewer program for
debugging
n Applets always use a windowing interface
44
Java Servlets
n A Java servlets are special kind of Java programs
that run from a Web server to generate dynamic Web
contents.
45
Objects and Methods in Java
n Java is an object-oriented programming
(OOP) language
n Programming methodology that views a
program as consisting of objects that interact
with one another by means of actions (called
methods)
n Objects of the same kind are said to have the
same type or be in the same class
46
The Compiler and the Java Virtual
Machine
n A programmer writes Java programming
statements for a program.
n These statements are known as source code.
n A text editor is used to edit and save a Java
source code file.
n Source code files have a .java file extension.
n A compiler is a program that translates source
code into an executable form.
47
The Compiler and the Java Virtual
Machine
n A compiler is run using a source code file as
input.
n Syntax errors that may be in the program will be
discovered during compilation.
n Syntax errors are mistakes that the programmer
has made that violate the rules of the
programming language.
n The compiler creates another file that holds the
translated instructions.
48
Byte-Code and the Java Virtual
Machine (JVM)
n The compilers for most programming languages
translate high-level programs directly into the machine
language for a particular computer
n Since different computers have different machine
languages, a different compiler is needed for each one
n In contrast, the Java compiler translates Java programs
into byte-code, a machine language for a fictitious
computer called the Java Virtual Machine
n Once compiled to byte-code, a Java program can be
used on any computer, making it very portable
49
The Compiler and the Java Virtual
Machine
n Byte code files end with the .class file extension.
n The JVM is a program that emulates a micro-
processor.
n The JVM executes instructions as they are read.
n JVM is often called an interpreter.
n Java is often referred to as an interpreted
language.
50
Program Development Process
Saves Java statements
Text editor Source code
(.java)
a d b y
Is re
Produces Byte code
Java compiler (.class)
t e d by
t er p re
Is in
Java Results in Program
Virtual Execution
Machine
51
Portability
53
Portability
Byte code
(.class)
Java Virtual
Java Virtual
Machine for Windows
Machine for Unix
Java Virtual Java Virtual
Machine for Linux Machine for Macintosh
54
Anatomy of a Java
Program
Lecture 3
Based on Slides of Dr. Norazah Yusof
55
Creating, Compiling, and Running
Programs
56
Parts of a Java Program
n A Java source code file contains one or more
Java classes.
n If more than one class is in a source code file,
only one of them may be public.
n The public class and the filename of the
source code file must match.
ex: A class named HelloApp must be in a file named
HelloApp.java
n Each Java class can be separated into parts.
57
Parts of a Java Program
n Example: HelloApp.java
n To compile the example:
n javac HelloApp.java
n Notice the .java file extension is needed.
created.
n To run the example:
n java HelloApp
n Notice there is no file extension here.
58
This area is the body of the class HelloApp.
All of the data and methods for this class
will be between these curly braces.
59
Analyzing the Example
// This is my first Java program.
This is Java main method.
public class HelloApp Every Java application must
{ have a main method
public static void main(String [] args)
{
This area is the body of the main method.
All of the actions to be completed during
the main method will be between these curly braces.
}
60
Analyzing the Example
// This is my first Java program.
public class HelloApp
{
public static void main(String [] args)
{
System.out.println("Programming is great fun!");
} This is the Java Statement that
is executed when the program runs.
61
Anatomy of a Java Program
n Comments
n Keywords
n Modifiers
n Statements
n Blocks
n Classes
n Methods
n The main method
n Package 62
Comments
63
Comments on several lines
64
Key Words
n Words that have a specific meaning to the
compiler
n Key words in the sample program are:
•public •void •boolean •private
•class •int •continue •protected
•static •double •return •package
(See Appendix A, “Java Keywords” from your textbook)
68
Statements
n represents an action or a sequence of actions.
n Example of statement:
System.out.println("Welcome to Java!")
is a statement to display the greeting
"Welcome to Java!"
n Every statement in Java ends with a semicolon (;).
69
Blocks
Classes
n class is the essential Java construct.
n Classes are central to Java
n Programming in Java consists of defining a number of
classes:
n Every program is a class (A program is defined by using one
or more classes.)
n All programmer-defined types are classes
71
Classes
n Example 1:
public class ClassA {
public static void main (String[] args) {
System.out.println ("Try your best");
}
}
72
Classes
class ClassB {
public static void main (String[] args) {
ClassA obj1 = new ClassA();
System.out.println (“Your age: “ + (2009 -
obj1.getYearBorn()));
System.out.println (“My message: “ + obj1.methodA());
73
}
Methods
75
main Method
public class ClassName
{
public static void main(String[] args) {
// Statements;
}
Thisvoid
is theindicates
parameter of the main
methodThe
This } is public,Keyword
main method fromis always the data type
in Java
i.e. visible
method. It takes arguments of an array
returned
meaning from
that
anywhere that can see this class.
static, this
this method
method is
can nothing or
of Strings. The data type String starts
no value.
be run without creating an instance of
with an upper case S. The square
the class.
brackets indicate an array. 76
Command-Line Arguments
C:\norazah> javac Greetings.java
C:\norazah> java Greetings Aqilah Ahmad
Hello, Aqilah Ahmad
78
import
n Full library class names include the package
name. For example:
java.awt.Color
javax.swing.JButton
n import statements at the top of the source file
let you refer to library classes by their short
names: Fully-qualified
import javax.swing.JButton; name
...
JButton go = new JButton("Go");
79
import (cont’d)
n You can import names for all the classes in a
package by using a wildcard .*:
import java.awt.*; Imports all classes
from awt, awt.event,
import java.awt.event.*; and swing packages
import javax.swing.*;
n java.lang is imported automatically into all
classes; defines System, Math, Object,
String, and other commonly used classes.
80
Package
package book;
import cert.*; // Import all classes in the cert
package class Goo {
public static void main(String[] args) {
Sludge o = new Sludge();
o.testIt();
} 82
}
Source File Declaration Rules
n A source code file can have only one public
class.
n If the source file contains a public class, the
filename must match the public class name.
n A file can have only one package statement, but
multiple imports.
n The package statement (if any) must be the first
(non-comment) line in a source file.
n The import statements (if any) must come after
the package and before the class declaration.
83
Source File Declaration Rules (cont.)
84
Identifiers and Variables
Lecture 4
Based on Slides of Dr. Norazah Yusof
85
Identifiers
n All the Java components —classes, variables,
and methods—need names.
n In Java these names are called identifiers,
and, there are rules for what constitutes a
legal Java identifier.
n Beyond what's legal, Java programmers (and
Sun) have created conventions for naming
methods, variables, and classes.
86
Rules for naming Identifiers
n Identifiers must start with a letter, a currency character ($), or a
connecting character such as the underscore ( _ ). Identifiers
cannot start with a number!
n After the first character, identifiers can contain any combination
of letters, currency characters, connecting characters, or
numbers.
n Identifier can be any length. In practice, there is no limit to the
number of characters an identifier can contain.
n You can't use a Java keyword as an identifier. (See Appendix A,
“Java Keywords,” for a list of reserved words).
n Identifiers in Java are case-sensitive; utm and Utm are two
different identifiers.
n Identifier cannot be true, false or null.
87
Sun's Java Code Conventions
The naming standards that Sun recommends:
n Classes and interfaces The first letter should be
capitalized, and if several words are linked together to
form the name, the first letter of the inner words
should be uppercase (a format that's sometimes
called "camelCase").
n For classes, the names should typically be nouns. For
example:
n Animal
n Account
n PrintWriter
n Serializable
89
Sun's Java Code Conventions
n Methods The first letter should be lowercase,
and then normal camelCase rules should be
used.
n In addition, the names should typically be
verb-noun pairs. For example:
n getBalance
n doCalculation
n setCustomerName
n calcArea
90
Sun's Java Code Conventions
n Variables Like methods, the camelCase
format should be used, starting with a
lowercase letter.
n Sun recommends short, meaningful names,
which sounds good to us. Some examples:
n nama
n buttonWidth
n accountBalance
n myString
91
Sun's Java Code Conventions
n Constants Java constants are created by
marking variables static and final.
n They should be named using uppercase
letters with underscore characters as
separators:
n MIN__HEIGHT
92
Programming Style and
Documentation
n Appropriate Comments
n Naming Conventions
n Proper Indentation and Spacing
Lines
n Block Styles
93
Appropriate Comments
94
Proper Indentation and Spacing
n Indentation
n Indent two spaces.
n Spacing
n Use blank line to separate segments of the
code.
95
Block Styles
96
Variables
n Variables are used to store data in a
program.
n There are two types of variables in Java:
1. Primitives
2. Reference variables
97
Primitives Variables
1. A primitive can be one of eight types: char, boolean, byte,
short, int, long, double, or float.
2. Once a primitive has been declared, its primitive type can
never change, although in most cases its value can change.
3. Primitive variables can be declared as class variables (statics),
instance variables, method parameters, or local variables.
4. One or more primitives, of the same primitive type, can be
declared in a single line.
5. Examples of primitive variable declarations:
i. char huruf;
ii. boolean myBooleanPrimitive;
iii. int x, y, z; // declare three int primitives
iv. double area;
98
Declaring primitive type
n Example of declaring Java variables with primitive types
int numberOfBeans;
double oneWeight, totalWeight;
n The declaration of a variable can be combined with its
initialization via an assignment statement
int count = 0;
double distance = 55 * .5;
char grade = 'A';
99
100
Reference Variables
1. A reference variable is used to refer to (or access) an object.
2. A reference variable is declared to be of a specific type and
that type can never be changed.
3. A reference variable can be used to refer to any object of the
declared type, or of a subtype of the declared type (a
compatible type).
4. Reference variables can be declared as static variables,
instance variables, method parameters, or local variables.
5. One or more reference variables, of the same type, can be
declared in a single line.
6. Examples of reference variable declarations:
i. Object o;
ii. Animal myNewPetReferenceVariable;
iii. String s1, s2, s3; //declare three String vars.
101
Instance Variables
1. Instance variables are defined inside the class, but outside of
any method, and are only initialized when the class is
instantiated.
2. Instance variables are the fields that belong to each unique
object.
3. For example, the following code defines fields (instance
variables) for the radius of circle objects:
public class Circle extends Object //Class header
{
private double radius;
4. Each circle instance will know its own radius. In other words,
each instance can have its own unique values for this field.
5. The term "field," "instance variable," "property," or "attribute,"
mean virtually the same thing.
102
Local Variables
1. Local variables are variables declared within a method.
2. That means the local variable starts its life inside the method,
it's also destroyed when the method has completed.
3. Local variables are always on the stack, not the heap.
4. Although the value of the variable might be passed into, say,
another method that then stores the value in an instance
variable, the variable itself lives only within the scope of the
method.
5. Before a local variable can be used, it must be initialized with a
value. For example:
class TestServer {
public void logIn() {
int count = 10;
}
}
103
Local Variables
1. Local variable declarations can't use most of
the modifiers that can be applied to instance
variables, such as public (or the other
access modifiers private, protected),
transient, volatile, abstract, or static.
2. But local variables can be marked final.
104
Local Variables
n A local variable can't be referenced in any code outside the method in
which it's declared.
n For example,
class TestServer {
public void logIn() {
int count = 10;
}
public void doSomething(int i) {
count = i; // Won't compile! Can't access
// count outside method login()
}
}
}
Local Variables
n The code produces the following output:
local variable count is 10
instance variable count is 9
107
Final Variables
1. Declaring a variable with the final keyword makes
it a constant.
2. Constant represent permanent data that never
changes.
3. For primitives, this means that once the variable is
assigned a value, the value can't be altered.
4. Syntax to declare a constant:
final datatype CONSTANTNAME = VALUE;
5. Example:
final double PI = 3.14159; //PI as constant
final int SIZE = 3;
108
Final Variables (Is it legal?)
class Roo {
final int size = 42;
public void changeSize() {
size = 16;
}
}
109
Final Variables
1. A reference variable marked final can't
ever be reassigned to refer to a different
object.
2. The data within the object can be modified,
but the reference variable cannot be
changed.
3. In other words, a final reference still allows
you to modify the state of the object it refers
to, but you can't modify the reference
variable to make it refer to a different object.
110
Variable scoping
n Once a variable is declared and initialized, a natural question
is "How long will this variable be around?"
public class Layout { // class
static int s = 343; // static variable
int x; // instance variable
{ x = 7;
int x2 = 5; } // initialization block
public Layout() {
x += 8;
int x3 = 6;} // constructor
public void doStuff() { // method
int y = 0; // local variable
for(int z = 0; z < 4; z++) { // 'for' code block
y += z + x; }
} 111
}
Variable scoping
n s is a static variable.
n x is an instance variable.
n y is a local variable (sometimes called a
"method local" variable).
n z is a block variable.
n x2 is an init block variable, a flavor of local
variable.
n x3 is a constructor variable, a flavor of local
variable.
112
Variable scoping
n There are four basic scopes:
1. Static variables have the longest scope; they are
created when the class is loaded, and they survive as
long as the class stays loaded in the JVM.
2. Instance variables are the next most long-lived; they
are created when a new instance is created, and they
live until the instance is removed.
3. Local variables are next; they live as long as their
method remains on the stack. As we'll soon see,
however, local variables can be alive, and still be "out
of scope".
4. Block variables live only as long as the code block is
executing.
113
Scoping errors
n One common mistake happens when a
variable is shadowed and two scopes
overlap.
1. Attempting to access an instance variable
from a static context (typically from main() ).
2. Attempting to access a local variable from a
nested method.
3. Attempting to use a block variable after the
code block has completed
114
Scoping errors
n One common mistake happens when a variable is shadowed
and two scopes overlap.
1. Attempting to access an instance variable from a static
context (typically from main() ).
Example:
class ScopeErrors1 {
int x = 5;
public static void main(String[] args) {
x++; // won't compile, x is an 'instance' variable
}
}
115
Scoping errors
2. Attempting to access a local variable from a nested
method.
Example:
public class ScopeErrors2 {
public static void main(String [] args) {
ScopeErrors s = new ScopeErrors();
s.go() ; }
void go() {
int y = 5;
go2() ;
y++; // once go2() completes, y is back in scope }
void go2() {
y++; // won't compile, y is local to go()
} 116
}
Scoping errors
3. Attempting to use a block variable after the code block has
completed.
Example:
void go3() {
for(int z = 0; z < 5; z++) {
boolean test = false;
if(z == 3) { test = true; break;
}
} System.out.print(test); // 'test' is an ex-variable,
// it has ceased to be...}
117
Assignment statements
Lecture 5
Based on Slides of Dr. Norazah Yusof
118
Assignment statement
n In Java, the assignment statement is used to change the
value of a variable
n The equal sign (=) is used as the assignment operator
n An assignment statement consists of a variable on the left
side of the operator, and an expression on the right side of the
operator
Variable = Expression;
n An expression consists of a variable, number, or mix of
variables, numbers, operators, and/or method invocations.
For example:
temperature = 98.6;
count = numberOfBeans;
n The assignment operator is automatically executed from right-
to-left, so assignment statements can be chained
number2 = number1 = 3;
119
Assignment compatibility
n In general, the value of one type cannot be stored in a
variable of another type.
n A double value cannot be stored in an int variable.
n An int cannot be assigned to a variable of type
boolean, nor can a boolean be assigned to a variable
of type int
n Example:
int intVariable = 2.99; //Illegal
n However, there are exceptions to this
double doubleVariable = 2;
n For example, an int value can be stored in a double
type
120
Assignment compatibility
n What would happen if you assign an integer literal
to a byte variable?
byte b = 3;
byte c = 8;
byte d = 500;
121
Assignment compatibility
n What would happen if you assign an integer literal
to a byte variable?
byte b = 3; //No problem, 3 fits in a byte
byte c = 8; // No problem, 8 fits in a byte
byte d = 500; // 500 does not fit a byte
C:\JavaProg\ByteTest.java:3: possible loss of precision
found : int
required: byte
byte a = 500;
122
Type casting
n Casting lets you convert primitive values from one type to another.
n Two type of casting:
1. Implicit casting – the conversion happens automatically
2. Explicit casting – programmer tells the compiler the type to cast
n Example of implicit cast:
int a = 100;
long b = a; // Implicit cast, an int value always
//fits in a long
n Example of explicit cast:
double d = 4.5;
int i;
i = (int)d; // The value of variable i is 4
// The value of variable d is 4.5
//Explicit cast, the integer could lose info
123
Widening conversion
n putting a smaller thing (say, a byte) into a bigger
container (like an int).
n an implicit cast happens when you're doing a
widening conversion :
small-value-into-large-container.
n Integer values may be assigned to a double
variable without explicit casting, because any
integer value can fit in a 64-bit double.
n Example:
double d = 100L; // Implicit cast
124
Narrowing conversion
n put a larger thing (say, a long) into a smaller container
(like a int).
n The large-value-into-small-container conversion requires
explicit cast.
n An explicit type cast is required to assign a value of
larger type (e.g., float) to a variable with smaller value
type (e.g. int)
n Example:
float a = 100.001f;
int b = (int)a; // Explicit cast, the float
//could lose info
125
Assignment compatibility
126
Selftest
n Is the following legal/illegal?
1. int x = 3957.229;
2. long s = 56L; byte b = (byte)s;
3. byte a = 128;
127
Selftest
n Is the following legal/illegal?
1. int x = 3957.229; //compilation error
2. long s = 56L; byte b = (byte)s; //OK
3. byte a = 128; // byte can only hold up to 127
128
Arithmetic operators and expressions
n As in most languages, expressions can be formed in Java using
variables, constants, and arithmetic operators.
n Java has five (5) arithmetic operators.
130
Shorthand assignment statement
Example: Equivalent To:
count += 2; count = count + 2;
sum -= discount; sum = sum – discount;
bonus *= 2; bonus = bonus * 2;
time /= time =
rushFactor; time / rushFactor;
change %= 100; change = change % 100;
amount *= amount = amount * (count1
count1 + count2; + count2);
131
Arithmetic Operators and Expressions
Promotion
n If an arithmetic operator is combined with int
operands, then the resulting type is int
n If an arithmetic operator is combined with one or two
double operands, then the resulting type is double
n If different types are combined in an expression, then
the resulting type is the right-most type on the
following list that is found within the expression
byteshortintlongfloatdouble
char
n Exception: If the type produced should be byte
or short (according to the rules above), then the
type produced will actually be an int
132
Arithmetic Operators and Expressions
133
Precedence rule
n Parentheses rule: Evaluate expressions in parentheses separately.
Evaluate nested parentheses from the inside out.
n Operator precedence rule: Operators in the same expression are
evaluated in the order determined by their precedence (from the
highest to the lowest).
Operator Precedence
method call highest precedence
- (unary)
new, type cast
*, /, %
+, - (binary)
= lowest precedence
134
Precedence rule
n When two operations have equal precedence, the order
of operations is determined by associativity rules
n Unary operators of equal precedence are grouped
right-to-left
n +-+rate is evaluated as +(-(+rate))
n Binary operators of equal precedence are grouped
left-to-right
n base + rate + hours is evaluated as
n (base + rate) + hours
n Exception: A string of assignment operators is
grouped right-to-left
n n1 = n2 = n3; is evaluated as n1 = (n2 = n3);
135
Precedence rule
Evaluation of z – (a + b / 2) * w / y
137
Increment and decrement operator
n If n is equal to 2, then 2*(++n) evaluates to 6
n If n is equal to 2, then 2*(n++) evaluates to 5
n Using increment and decrement operators
makes expressions short, but it also makes them
complex and difficult to read.
n Avoid using these operators in expressions that
modify multiple variables, or the same variable
for multiple times such as this: int k = ++i + i.
138
String, Scanner and
JOptionPane class
Lecture 6
Based on Slides of Dr. Norazah Yusof
139
The String Class
n Java has no primitive data type that holds a series of
characters.
n The String class from the Java standard library is
used for this purpose.
n In order to be useful, the a variable must be created
to reference a String object.
String name;
n Notice the S in String is upper case.
n By convention, class names should always begin with
an upper case character.
140
String Objects
n A variable can be assigned a String literal.
String ucapan1 = “Selamat”;
n Strings are the only objects that can be created in
this way.
n A variable can be created using the new keyword.
String ucapan2 = new String(“Sejahtera”);
n This is the method that all other objects must use
when they are created.
141
String Objects
n Example:
public class StringDemo {
public static void main(String[] args) {
String ucapan1 = "Selamat";
String ucapan2 = new String("Sejahtera");
System.out.print(ucapan1+" ");
System.out.println(ucapan2);
}
}
142
Reference Variables
n Objects are not stored in variables, however. Objects
are referenced by variables.
n When a variable references an object, it contains the
memory address of the object’s location.
n Then it is said that the variable references the object.
String cityName = "Johor Bahru";
The object that contains the
character string “Johor Bahru”
143
The String Methods
n Since String is a class, objects that are
instances of it have methods.
n One of those methods is the length method.
int stringSize;
stringSize = value.length();
n This statement runs the length method on
the object pointed to by the value variable.
144
The String Method: length()
n Example:
public class StringDemo1 {
public static void main(String[] args) {
String ucapan = "Selamat Datang";
String nama = "Farhana";
int saizRentetan;
saizRentetan = ucapan.length();
System.out.println("Panjang "+ucapan+" ialah "
+saizRentetan+" perkataan.");
saizRentetan = nama.length();
System.out.println("Panjang "+nama+" ialah "
+saizRentetan+" perkataan.");
}
}
145
String Methods
n The String class contains many methods
that help with the manipulation of String
objects.
n String objects are immutable, meaning that
they cannot be changed.
n Many of the methods of a String object can
create new versions of the object.
See example: StringMethods.java
146
The String Method: toLowerCase(),
toUpperCase() and charAt()
n Example:
public class StringDemo2 {
public static void main(String[] args) {
String tempat = "Johor Bahru";
String upper = tempat.toUpperCase();
String lower = tempat.toLowerCase();
char huruf = tempat.charAt(2);
int saizRentetan = tempat.length();
System.out.println(tempat);
System.out.println(upper);
System.out.println(lower);
System.out.println(huruf);
System.out.println(saizRentetan);
}
} 147
The Scanner Class
n To read input from the keyboard we can use the
Scanner class.
n The Scanner class is defined in java.util, so we
will use the following statement at the top of our
programs:
import java.util.Scanner;
148
The Scanner Class
n Scanner objects work with System.in
n To create a Scanner object:
Scanner keyboard = new Scanner (System.in);
149
The JOptionPane Class
n The JOptionPane class is not automatically
available to your Java programs.
n The following statement must be before the
program’s class header:
import javax.swing.JOptionPane;
n This statement tells the compiler where to find
the JOptionPane class.
150
The JOptionPane Class
The JOptionPane class provides methods to
display each type of dialog box.
151
Message Dialogs
n JOptionPane.showMessageDialog method is
used to display a message dialog.
JOptionPane.showMessageDialog(null, "Hello World");
152
Input Dialogs
n An input dialog is a quick and simple way to
ask the user to enter data.
n The dialog displays a text field, an Ok button
and a Cancel button.
n If Ok is pressed, the dialog returns the user’s
input.
n If Cancel is pressed, the dialog returns null.
153
Input Dialogs
String name;
name = JOptionPane.showInputDialog(
"Enter your name.");
n The argument passed to the method is the message to display.
n If the user clicks on the OK button, name references the string
entered by the user.
n If the user clicks on the Cancel button, name references null.
154
The System.exit Method
n A program that uses JOptionPane does not
automatically stop executing when the end of
the main method is reached.
n Java generates a thread, which is a process
running in the computer, when a
JOptionPane is created.
n If the System.exit method is not called,
this thread continues to execute.
155
The System.exit Method
n The System.exit method requires an integer
argument.
System.exit(0);
n This argument is an exit code that is passed back to
the operating system.
n This code is usually ignored, however, it can be used
outside the program:
n to indicate whether the program ended successfully or
as the result of a failure.
n The value 0 traditionally indicates that the program
ended successfully.
156
Converting a String to a Number
n The JOptionPane’s showInputDialog
method always returns the user's input as a
String
n A String containing a number, such as
“127.89” can be converted to a numeric data
type.
157
The Parse Methods
n Each of the numeric wrapper classes, (covered in
Chapter 10) has a method that converts a string to a
number.
n The Integer class has a method that converts a
string to an int,
n The Double class has a method that converts a string
to a double, and
n etc.
n These methods are known as parse methods
because their names begin with the word “parse.”
158
The Parse Methods
// Store 1 in bVar.
byte bVar = Byte.parseByte("1");
// Store 2599 in iVar.
int iVar = Integer.parseInt("2599");
// Store 10 in sVar.
short sVar = Short.parseShort("10");
// Store 15908 in lVar.
long lVar = Long.parseLong("15908");
// Store 12.3 in fVar.
float fVar = Float.parseFloat("12.3");
// Store 7945.6 in dVar.
double dVar = Double.parseDouble("7945.6");
159
Reading an Integer with an Input
Dialog
int number;
String str;
str =
JOptionPane.showInputDialog(
"Enter a number.");
number = Integer.parseInt(str);
160
Reading a double with an Input
Dialog
double price;
String str;
str =
JOptionPane.showInputDialog(
"Enter the retail price.");
price =
Double.parseDouble(str);
161
Creating Class and Object
Lecture 7
Based on Slides of Dr. Norazah Yusof
162
Classes
A Java class member may have:
n instance variables to define data fields/attributes
and
n instance methods to define behaviors.
Additionally, a class provides a special type of
methods, known as constructors, which are invoked
to construct objects from the class.
163
UML Class Diagram for Employee
Class name
Employee
- empnum: int Attributes / instance variables that
- empname: String define the object’s state; can hold
numbers, characters, strings, other
+ setEmpNum(int): void objects
+ getEmpNum(): int
+ setEmpName(String): void
+ getEmpName(): String Actions that an object of this
class can take (behaviors)
164
Data Fields
n Variables declared within class
But outside of any method
n
n Called instance variables (local)
n When not static (global)
n Each class will have own copy of each non-
static data field
n private access for fields
n No other classes can access field’s values
n Only methods of same class allowed to use
private variables
166
Java Programming, Fourth
166
Edition
You name it!
Data Fields (cont’d)
private [static] [final] datatype name;
Usually
private primitive: int, double,
etc., or an object:
May be present: String, Image, Foot
means the field is
shared by all May be present:
objects in the class means the field
is a constant
private int empnum;
167
Creating Instance Methods in a Class
168
168
Method Definitions
n Method header form:
modifier returnType methodName ([parameterList])
n Example:
public double getPrice()
public void setPrice(double aPrice)
n Method names usually sound like verbs.
n The name of a method that returns the value of a
field often starts with get:
getWidth, getX
n The name of a method that sets the value of a field
often starts with set:
setLocation, setText
169
169
Understanding Data Hiding
n Data hiding using encapsulation
n Data fields usually private
n Client application accesses them only through
public interfaces
n Set method
n Controls data values used to set variable
n Get method
n Controls how value retrieved
170
Java Programming, Fourth
170
Edition
Accessor and Mutator Methods
n The methods that retrieve the data of
fields are called accessors.
n The methods that modify the data of
fields are called mutators.
171
Accessors and Mutators
n For the rectangle example, the accessors and
mutators are:
n getLength : Returns the value of the length field.
public double getLength() { }
n getWidth : Returns the value of the width field.
public double getWidth() { }
n setLength : Sets the value of the length field.
public void setLength(double len) { }
n setWidth : Sets the value of the width field.
public void setLength(double w) { }
172
Class Definition
public class Employee {
private int empnum;
private String empname;
Employee
public void setEmpNum(int num) {
- empnum: int empnum = num;
- empname: String }
+ setEmpNum(int): void public int getEmpNum() {
+ getEmpNum(): int return empnum;
+ setEmpName(String): void }
+ getEmpName(): String
public void setEmpName(Strig name) {
UML class diagram empname = name;
}
175
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
Assign object reference Create an object
Example:
Employee emp1 = new Employee();
176
Accessing Objects
n After object instantiated, methods accessed using:
nObject’s identifier
n Dot
n Data/Method call
178
Class Definition with default
constructor public class Employee {
private int empnum;
private String empname;
Employee public Employee() {
- empnum: int System.out.println (“Start Employee”);
}
- empname: String
+ Employee() public void setEmpNum(int num) {
+ setEmpNum(int): void empnum = num;
+ getEmpNum(): int }
public int getEmpNum() {
+ setEmpName(String): void
return empnum;
+ getEmpName(): String
}
public void setEmpName(String name) {
empname = name;
UML class diagram
}
public String getEmpName() {
return empname;
} 179
}
Constructors
180
Creating Object == invoking Constructors
181
Constructors (cont’d)
public class Fraction public Fraction (int n, int d)
{ {
private int num, denom; num = n;
denom = d;
public Fraction ( ) reduce ();
{ }
num = 0;
denom = 1; “No- public Fraction (Fraction other)
} args” {
construc num = other.num;
public Fraction (inttor
n) denom = other.denom;
{ }
num = n; ... Copy
denom = 1;
} Continued }
construc
tor 182
Constructors (cont’d)
n A nasty bug:
public class MyWindow
extends JFrame
{
...
// Constructor: Compiles fine, but
public void MyWindow ( ) the compiler thinks
{ this is a method and
...
}
uses MyWindow’s
... default no-args
constructor instead.
183
Constructors (cont’d)
184
Organizing Classes
n Place data fields in logical order
n At beginning of class
n Fields listed vertically
n May place data fields and methods in any
order within a class
n Common to list all data fields first
n Can see names and data types before reading
methods that use data fields
185
Java Programming, Fourth
185
Edition
Employee.java
nExercise 1 - 6 (page
17 - 27)
Passing Arguments to
Methods
Lecture 8
Based on Slides of Dr. Norazah Yusof
189
Method
• A method is a collection of statements that are
grouped together to perform an operation.
• A method is always defined inside a class.
• Method signature or method header is the
combination of the method name and the parameter
list.
method header {
method body
}
190
Parts of a Method Header
Method Return Method Parentheses
Modifiers Type Name
public int getEmpNum ()
{
return empnum;
}
The above method is an instance method.
The type of result returned is returnType where int means the method
returns an integer result.
191
Parts of a Method Header
Method Return Method Parentheses
Modifiers Type Name
public void setEmpNum (int num)
{
empnum = num;
}
The above method is an instance method.
The type of result returned is returnType where void means the method
does not return a result.
192
return Statement
193
return Statement (cont’d)
n A method can have several return statements;
then all but one of them must be inside an if or
else (or in a switch):
public someType myMethod (...)
{
...
if (...)
return <expression1>;
else if (...)
return <expression2>;
...
return <expression3>;
}
194
return Statement (cont’d)
n A boolean method can return true, false, or
the result of a boolean expression:
public boolean myMethod (...)
{
...
if (...)
return true;
...
return n % 2 == 0;
}
195
Calling an instance method
n A method executes when it is called.
n The main method is automatically called when a
program starts, but other methods are executed by
method call statements
n A method with a non-void return value type can also
be invoked as a statement.
n An invocation of an instance method that returns an
integer value may use an assignment statement or
output statement:
int vnum;
vnum = obj1.getEmpNum();
or
System.out.println ("employee num:" +
obj1.getEmpNum()); 196
Calling an instance method
n An invocation of a void instance method is simply a
statement:
objectName.methodName();
n Example:
obj1.setEmpNum(123);
197
Passing Parameters to Constructors
n Any expression that has an appropriate
data type can serve as a parameter:
public static void main (String[] args) {
Employee emp1 = new Employee();
Employee emp2 = new Employee(123); // argument
Employee emp3= new Employee(456, "Ahmad"); // argument
}
public class Employee {
public Employee () { }
public Employee (int num) { // parameters
empnum = num ;}
public Employee (int num, String name) {
empnum = num ;
empname = name;
} 198
Arguments are Passed by Value
n In Java, all arguments of the primitive data types
are passed by value, which means that only a copy
of an argument’s value is passed into a parameter
variable.
n Any change to a parameter variable inside a
method, has no affect to the original argument.
5-200
Passing Parameters : primitive type
length: 12.0
width: 5.0
box1.equals(box2);
Address
public boolean equals(Rectangle r)
{
return (this.calcArea() == r.calcArea());
}
9-206
Returning Objects From Methods
import java.util.*;
public Rectangle inputRectangle() {
public class PassObject3 { Scanner inp = new Scanner (System.in);
double newWidth, newLength;
public static void main(String[ ] args) {
Rectangle box3 = new System.out.print ("Enter width : ");
Rectangle().inputRectangle(); newWidth = inp.nextDouble();
System.out.println (“The area: “ + System.out.print ("Enter length : ");
box3.calcArea()); newLength = inp.nextDouble();
207
Returning Objects From Methods
n Methods can return references to objects.
n Just as with passing arguments, a copy of the
object is not returned, only its address.
n Method return type:
public Rectangle inputRectangle ()
{
…
return new Rectangle(newWidth, newLength);
}
9-208
The toString Method
9-209
The equals Method
n When the == operator is used with reference
variables, the memory address of the objects
are compared.
n The contents of the objects are not
compared.
n All objects have an equals method.
n The default operation of the equals method
is to compare memory addresses of the
objects (just like the == operator).
9-210
The equals Method
n The Rectangle class has an equals method.
n Write a method that only the addresses of the
objects are compared.
n Now, instead of using the == operator to compare two
Rectangle objects, we should use the equals
method.
n Compare objects by their contents rather than by their
memory addresses.
9-211
Methods That Copy Objects
n There are two ways to copy an object.
n You cannot use the assignment operator to
copy reference types
n Reference only copy
n This is simply copying the address of an object
into another reference variable.
n Deep copy (correct)
n This involves creating a new instance of the class
and copying the values from one object into the
new object.
9-212
Copy Constructors
n A copy constructor accepts an existing object
of the same class and clones it
public Rectangle(Rectangle object2)
{
this.width = object2.width;
this.length = object2.length;
}
// Create a rectangle object, rect1
Rectangle rect1 = new Rectangle(5.0, 4.5);
//Create rect2, a copy of rect1
Rectangle rect2 = new Rectangle(rect1);
9-213
The FoodItem class
The class diagram that represents a food item at a market
FoodItem
- description: String
- size: double
- price: double
+ FoodItem()
+ setDesc()
+ setSize()
+ setPrice()
+ getDesc()
+ getSize()
+ getPrice()
+ calcUnitPrice()
+ toString()
219
Methods for Class FoodItem
n For most classes, we need to provide methods that perform
tasks similar to the ones below.
n a method to create a new FoodItem object with a specified
description, size, and price (constructor)
n methods to change the description, size, or price of an existing
FoodItem object (mutators)
n methods that return the description, size, or price of an existing
FoodItem object (accessors)
n a method that returns the object state as a string (a toString()
method).
220
Method Headers for
Class FoodItem
Method Description
public FoodItem(String, n Constructor - creates a new
double, double) object whose three data fields
have the values specified by its
three arguments.
public void setDesc(String)
n Mutator - sets the value of data
field description to the value
public void setSize(double) indicated by its argument.
Returns no value.
n Mutator - sets the value of data
field size to the value indicated
by its argument. Returns no
value.
221
Method Headers for
Class FoodItem, cont’d.
Method Description
public void setPrice(double) n Mutator - sets the value of data
field price to the value
indicated by its argument.
public String getDesc() Returns no value.
n Accessor - returns a reference
to the string referenced by data
field description.
222
Method Headers for
Class FoodItem, cont’d.
Method Description
public double getPrice() n Accessor - returns the value
of data field price.
223
Class FoodItem
/*
* FoodItem.java
* Represents a food item at a market
*/
public class FoodItem {
// data fields
private String description;
private double size;
private double price;
224
Class FoodItem, cont’d.
// methods
// postcondition: creates a new object with data
// field values as specified by the arguments
public FoodItem(String desc, double aSize,
double aPrice) {
description = desc;
size = aSize;
price = aPrice;
}
227
void Methods
n The mutator methods are void methods.
public void setSize(double aSize) {
size = aSize;
}
n Method setSize() sets the value of data field size to the value
passed to parameter aSize.
n A void method is executed for its effect because it does not
return a value; however, it may change the state of an object or
cause some information to be displayed.
228
The return Statement
n Each FoodItem method that is not a void method or a constructor
returns a single result.
public double getPrice() {
return price;
}
The return statement above returns the value of data field price
as the function result.
n Form: return expression;
n Example: return x + y;
n Interpretation: The expression after the keyword return is
returned as the method result. Its data type must be assignment
compatible with the type of the method result.
229
toString() Method
n A toString() method returns a reference to a String object that
represents an object's state.
public String toString() {
return description + ", size : " + size +
", price $" + price;
}
230
Calling methods
n Because a void method does not return a value, a
call to a void method is a Java statement all by itself.
If myCandy is type FoodItem, an example would be
myCandy.setDescription("Snickers, large");
n Because a non-void method returns a value, a call to
a non-void method must occur in an expression:
"price is $" + myCandy.getPrice()
232
Argument/Parameter Correspondence for
FoodItem("Snickers", 6.5, 0.55)
Argument Parameter
"Snickers" desc (references
"Snickers")
6.5 aSize (value is 6.5)
aPrice (value is 0.55)
0.55
client TestFoodItem
(application) class
main()
association
relationship
worker FoodItem
class description: String
size: double
price: double
FoodItem()
setDesc()
setSize()
setPrice()
getDesc()
getSize()
getPrice()
calcUnitPrice()
toString()
236
The equals Method
n The Rectangle class has an equals method.
n If we try the following:
Stock stock1 = new Stock("GMX", 55.3);
Stock stock2 = new Stock("GMX", 55.3);
if (stock1 == stock2) // This is a mistake.
System.out.println("The objects are the same.");
else
System.out.println("The objects are not the
same.");
only the addresses of the objects are compared.
9-237
Static Variable and
Method
Lecture 9
Based on Slides of Dr. Norazah Yusof
238
Static Modifier
n The static modifier is used to create variables
and methods that will exist independently of
any instances created for the class.
n In other words, static members exist before
you ever make a new instance of a class, and
there will be only one copy of the static
member regardless of the number of
instances of that class.
239
Example 1: Static variable
public class Kira {
// Declare and initialize static variable
static int kaunterKira = 0;
public Kira() {
kaunterKira += 1; // Modify the value in
// the constructor
}
public static void main (String [] args) {
new Kira();
new Kira();
new Kira();
System.out.println ("Kiraan Kira ialah " +
kaunterKira);
} 241
}
Example 1: Static variable
n In the preceding code, the static kaunterKira variable
is set to 0 when the Kira class is first loaded by the
JVM, before any Kira instances are created!
n Whenever a Kira instance is created, the Kira
constructor runs and increments the static
kaunterKira variable.
n When this code executes, three Kira instances are
created in main(), and the result is:
Kiraan kira ialah 3
242
Example 2: using instance variable
public class Kira {
int kaunterKira = 0; // Declare and initialize
// instance variable
public Kira() {
kaunterKira += 1; // Modify the value in
// the constructor
}
public static void main (String [] args) {
new Kira();
new Kira();
new Kira();
System.out.println ("Kiraan Kira ialah " +
kaunterKira);
}
}
243
Example 2: using instance variable
n When this code executes, it should still create three
Kira instances in main() , but the result is…a compiler
error!
Kira.java:11: non-static variable kaunterKira cannot
be referenced from a static context
System.out.println ("Kiraan Kira ialah " +
kaunterKira);
^
1 error
Tool completed with exit code 1
244
Static Modifier
n Things you can mark as static:
n Methods
n Variables
n A class nested within another class, but not
within a method
n Initialization blocks
245
Static nested class
n A static nested class is simply a class that's a static
member of the enclosing class:
class BigOuter {
static class Nested { } }
247
Using Static Nested Classes
n You use standard syntax to access a static nested class from its
enclosing class. The syntax for instantiating a static nested class from a
non-enclosing class is a little different from a normal inner class, and
looks like this:
class BigOuter {
static class Nest {
void go(){System.out.println("hi");}
} }
class Broom {
static class B2 {
void goB2() {System.out.println("hi 2"); }
}
public static void main(String[] args) {
BigOuter.Nest n = new BigOuter.Nest();
n.go();
B2 b2 = new B2(); // access the enclosed class
b2.goB2();
}} 248
Static variable
n Static variables store values for the variables
in the common memory location.
n All object of the same class are affected if
one object changes the value of a static
variable.
n Public static variables are referred to using
“dot notation” (if in other classes):
ClassName.staticVar
249
Static variables
250
Static final
n A static final can hold a constant shared by all
objects of the class:
251
Static Methods
double x = Math.random();
double y = Math.sqrt (x);
System.exit();
252
Lab 3 Exercise 1
nThe above program contains the main method and the max method (which
is a static method) which demonstrates calling a method max to return the
largest of the int values.
nIn this example, the main method invokes max(i,j), which is defined in
the same class with the main method.
254
Example of Static Methods
nWhen the max method is invoked, variable i’s value 5 is passed to num1,
and variable j’s value 2 is passed to num2 in the max method.
nThe flow of control transfers to the max method.
nThe max method is executed. When the return statement in the max
method is executed, the max method returns the control to its caller.
255
Call Stacks
n Each time a method is invoked, the system
stores parameters and variables in an area of
memory, known as stack, which stores
elements in last-in-first-out fashion.
n When a method calls another method, the
caller’s stack space is kept intact, and new
space is created to handle the new method
call.
n When a method finishes it work and returns to
its caller, its associated space is released.
256
Call Stacks
257
animation
Trace Call Stack
i is declared and initialized
258
animation
Trace Call Stack
j is declared and initialized
259
animation
Trace Call Stack
Declare k
260
animation
Trace Call Stack
Invoke max(i, j)
261
animation
Trace Call Stack
pass the values of i and j to num1
and num2
262
animation
Trace Call Stack
pass the values of i and j to num1
and num2
263
animation
Trace Call Stack
(num1 > num2) is true
264
animation
Trace Call Stack
Assign num1 to result
265
animation
Trace Call Stack
Return result and assign it to k
266
animation
Trace Call Stack
Execute print statement
267
Static method cannot access an
instance variable
268
Static method cannot access a non-
static method
269
Static method can access a static
method or variable
270
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.
271
Scope of Local Variables, cont.
272
Scope of Local Variables, cont.
273
Scope of Local Variables, cont.
274
Scope of Local Variables, cont.
// Fine with no errors
public static void correctMethod() {
int x = 1;
int y = 1;
// i is declared
for (int i = 1; i < 10; i++) {
x += i;
}
// i is declared again
for (int i = 1; i < 10; i++) {
y += i;
}
} 275
Scope of Local Variables, cont.
// With errors
public static void incorrectMethod() {
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++) {
int x = 0;
x += i;
}
}
276
Method Overloading
n Method overloading is two or more methods
have the same name, but different parameter
lists within one class.
n The Java compiler determines which method
is used based on the method signature.
n Overloaded methods must have different
parameter lists. You cannot overload methods
based on different modifiers or return type.
277
Overloading Methods
Listing 5.3 Overloading the max Method
public static int max(int num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, double num2, double
num3) {
return max(max(num1, num2), num3);
}
278
Lab 3 Exercise 1
Answer Question 1 on page 61 :
i. Determine the output of Program 3.1 & 3.2. Does the
values of i and j for t1, t2 and t3 are same? Why?
ii. Determine the output of Program 3.3. What is the value
of the first, second and third of kaunterTest2? Why this
happen?
iii. Determine the output of Program 3.4. What is the value
of the first, second and third of kaunterTest3? Why this
happen?
iv. Determine the output of Program 3.5. What is the value
of kaunterTest4? Why this happen?
Answer Question 2 on page 63
Answer : Lab 3 Exercise 1
Answer Question 1 on page 61 :
i. Determine the output of Program 3.1 & 3.2.
t1's static i= 1 and instance j=1
t2's static i= 2 and instance j=1
t3's static i= 3 and instance j=1
ii. Determine the output of Program 3.3.
Kiraan Test2 ialah 1 2 3
iii. Determine the output of Program 3.4.
Kiraan Test3 ialah 1 1 1
iv. Determine the output of Program 3.5.
Kiraan Kira ialah 25
Answer Question 3 on page 64 :
System.out.print("Year of start working=" );
startYear = kb.nextInt();
temp = calcYears(thisYear, startYear);
System.out.println("You have been worked for=" + temp);
Enumerated Types
Lecture 10
Based on Slides of Dr. Norazah Yusof
283
Enumerated Types
n Enumeration is a special kind of class, that is
introduced by the keyword enum and enum
constants.
n Syntax: enum typeName {one or more enum
constants}
n Example : enumeration definition:
enum Day {SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY}
n Declaration: Day workday;
Operation:
9-284
n workday = Day.WEDNESDAY;
Enumerated Types
n An enum is a specialized class
Each are objects of type Day, a specialized class
Day.SUNDAY
Day workDay = Day.WEDNESDAY; Day.MONDAY
The workDay variable holds the address
of the Day.WEDNESDAY object Day.TUESDAY
address Day.WEDNESDAY
Day.THURSDAY
Day.FRIDAY
Day.SATURDAY
9-285
Enumerated Types restriction
n enum types are implicitly final,
because they declare constants that
should not be modified
n enum constants are implicitly static
n Any attempt to create an object of an
enum type with operator new results in
a compilation error.
9-286
public class EnumTest1{
enum Day {SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}
public static void main(String[] args){
Day workday;
workday = Day.THURSDAY;
System.out.println ("Today is "+ workday);
System.out.println ("Yesterday was "+
Day.WEDNESDAY);
}
}
287
Enum methods
n Enum class is equipped with a few methods:
n ordinal() method returns an integer value
representing the constant’s ordinal value.
n equals() method accepts an object as its
argument and returns true if that object is equal
to the calling enum constant.
n compareTo() method accepts an object as its
argument and returns negative integer, zero, or
positive value if the calling enum constant’s
ordinal value is less than, equal or greater than
the argument’s ordinal value. 288
Enum methods
n Example 1:
System.out.println ("Ordinal value: "+
workday.ordinal());
n Example 2:
Day myDay = Day.FRIDAY;
if (myDay.equals(workday))
System.out.println ("same day ");
else
System.out.println ("different day ");
289
Garbage Collection
n When an object is created, a certain
amount of memory space is allocated for
storing this object.
n After a certain use, when an object has no
references pointing to it, then the system
will erase the object and make the memory
space available for other uses.
n The erasing of an object is called
deallocation of memory, and this process
is called garbage collection.
Lab 4
Lecture 10 (cont.)
292
Wrapper class
n Primitive types and reference types behave
differently. It is sometimes useful to treat primitive
values as objects. For this reasons, Java
includes wrapper classes for each of the primitive
types. The wrapper class is used to convert a
primitive type like int to an object.
n Boolean, Byte, Short, Character, Integer, Long,
Float and Double are immutable classes whose
instances each hold a single primitive value.
Wrapper class
n Wrappers are classes that wrap up primitive
values in classes that offer utility methods to
manipulate the values.
n The methods are all static so you can use
them without creating an instance of the
matching wrapper class.
n They are also final, once a wrapper has a
value assigned to it, that value cannot be
changed.
Wrapper class
n All wrapper classes except Character provide
two constructors: a primitive of the type being
constructed, and String representation of the
type being constructed. Eg.:
Integer a1 = new Integer(64);
Integer a2 = new Integer(“64”);
or
Float b1 = new Float(1.23f);
Float b1 = new Float(“1.23f”);
int i; // i is a … int i;
Integer j; // j is a … Integer j;
i = 1; i = 1;
j = 2; j = new Integer(2);
i = j; i = j.intValue();
j = i; j = new Integer(i);
Auto boxing and unboxing
n Autoboxing provides automatic conversions between
primitive values and corresponding wrapped objects.
Integer y = new Integer(97); // make it
y++; // unwrap it, increment it, rewrapped it
System.out.println(“y =” + y); // print it y = 98
• Without autoboxing we need to unwrap it, use and
then rewrapped it
Integer y = new Integer(567); // make it
int x = y.intValue(); // unwrap it,
x++; // use it
y = new Integer(x); // rewrapped it
System.out.println(“y =” + y); // print it y = 98
Lab 4
n }
n }
Java Package
Lecture 11
Based on Slides of Dr. Norazah Yusof
312
Putting Classes into Packages
• Every class in Java belongs to a package.
• The class is added to the package when it is compiled.
All the classes that you have used so far were placed in
the active directory (a default package) when the Java
source programs were compiled.
• To put a class in a specific package, you need to add
the following line as the first non-comment and non-
blank statement in the program:
package packagename;
313
Why we need package?
315
Package Directories
Java expects one-to-one mapping of the package name and the file
system directory structure.
Suppose the com directory is under c:\book. The following line adds
c:\book into the classpath:
classpath=.;c:\book;
317
Exercise: Putting Classes into Packages
Problem (Exercise 1, page 80-85)
1.Create three classes named Bulatan , SegiEmpat, dan SegiTigaTepat and place
it in the folder bentuk that is in another folder mypackage from the root
(or package mypackage.bentuk).
2.Create a test program named Contoh3.java that uses the classes. The
test program is placed in different folder named prog3 and in the root
directory.
C: C:
Solution
i.Create directory named mypackage from the root direcotry.
1.Create directory named bentuk under the directory mypackage.
2.Create Bulatan.java and save it into c:\mypackage\bentuk. The Bulatan class
contains the luas() and the paparMaklumat() methods.
// Bulatan.java
1. package bentuk;
2. public class Bulatan {
3. private int titikTengahX, titikTengahY;
4. private int jejari;
5. : 319
6. : }
Exercise: Putting Classes into Packages
Solution continue…
v.Compile Bulatan.java. Make sure Bulatan.java is in c:\mypackage\bentuk
vi.Create Segiempat.java as well as SegiTigaTepat.java and save it into
c:\mypackage\bentuk.
vii.Compile Segiempat.java and SegiTigaTepat.java.
320
Exercise: Using Packages
Problem
This example shows a program created in directory prog3, that uses the
Bulatan, Segiempat dan SegiTigaTepat class in the mypackage.bentuk
package.
Solution
1. Create Contoh3.java as follows and save it into c:\prog3.
The following code gives the solution to the problem.
// Contoh3.java: Demonstrate using the Bulatan class
import bentuk.*;
public class Contoh3 {
public static void main(String[] args) {
Bulatan a = new Bulatan(0, 0, 10);
System.out.println("Maklumat bentuk a");
a.paparMaklumat();
System.out.println("Luas:" + a.luas());
}
} 321
Exercise: Set Environment
Solution
Set the path in a batch file.
set PATH=C:\Program Files\Java\jdk1.5.0_01\bin
set CLASSPATH=.;c:\mypackage;
cd \prog3
Or
Set the path from the computer environment.
322
Using Classes from Packages
There are two ways to use classes from a package.
1. One way is to use the fully qualified name of the class.
import bentuk.Bulatan;
2. The other way is to use the import statement. For example, to import all
the classes in the javax.swing package, you can use
import bentuk.*;
• An import that uses a * is called an import on demand declaration. You can
also import a specific class. For example:
import bentuk.Bulatan;
• The information for the classes in an imported package is not read in at
compile time or runtime unless the class is used in the program. The import
statement simply tells the compiler where to locate the classes.
323
Lab 4
n Do Exercises
Array
Lecture 12
Based on Slides of Dr. Norazah Yusof
325
Introducing Arrays
■ Example
double[] myList = new double[10];
or
double myList[] = new double[10];
329
The Length of an Array
For example,
myList.length
returns 10
330
Default Values
331
Arrays
• Subscript
• Integer contained within square brackets
• Indicates one of array’s variables or elements
double[] myList = new double[10];
myList reference
myList[0] 0
myList[1] 0
Array reference myList[2] 0
variable
myList[3] 0
myList[4] 0
Array element at
myList[5] 0 Element value
index 5
myList[6] 0
myList[7] 0
myList[8] 0
myList[9] 0 332
Arrays
myList reference
myList[0] 0
myList[1] 0
Array reference myList[2] 0
variable
myList[3] 0
myList[4] 0
Array element at
myList[5] 0 Element value
index 5
myList[6] 0
myList[7] 0
myList[8] 0
myList[9] 0 333
Accessing Array Elements
338
Write & Trace the output
class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers
anArray = new int[10]; // allocates memory for 10 integers
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
System.out.println("Element at index 0: " + anArray[0]);
System.out.println("Element at index 1: " + anArray[1]);
System.out.println("Element at index 2: " + anArray[2]);
System.out.println("Element at index 3: " + anArray[3]);
System.out.println("Element at index 4: " + anArray[4]);
System.out.println("Element at index 5: " + anArray[5]);
System.out.println("Element at index 6: " + anArray[6]);
System.out.println("Element at index 7: " + anArray[7]);
System.out.println("Element at index 8: " + anArray[8]);
System.out.println("Element at index 9: " + anArray[9]);
}
}
■ The output from this program is:
Element at index 0: 100
Element at index 1: 200
Element at index 2: 300
Element at index 3: 400
Element at index 4: 500
Element at index 5: 600
Element at index 6: 700
Element at index 7: 800
Element at index 8: 900
Element at index 9: 1000
Using loop to cycle through the
entire array
■ Perform loops that vary loop control variable
Start at 0
■
■ Example
double[] myList = {5.6, 4.5, 3.3,
13.2, 4, 34.33, 34, 45.45, 99.993,
11.3};
343
Declaring, creating, initializing Using
the Shorthand Notation
double[] myList = {5.6, 4.5, 3.3, 13.2, 4, 34.33,
34, 45.45, 99.993, 11.3};
344
CAUTION!!
Using the shorthand notation, you have to declare,
create, and initialize the array all in one statement.
345
Arrays
double[] myList = new double[10];
myList reference
myList[0] 5.6
myList[1] 4.5
Array reference myList[2] 3.3
variable
myList[3] 13.2
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
Trace Program with Arrays
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1];
}
values[0] = values[1] + values[4];
}
}
351
Trace Program with Arrays
Declare array variable values, create an
array, and assign its reference to values
352
Trace Program with Arrays
i becomes 1
353
Trace Program with Arrays
i (=1) is less than 5
354
Trace Program with Arrays
After this line is executed, value[1] is 1
355
Trace Program with Arrays
After i++, i becomes 2
356
Trace Program with Arrays
i (= 2) is less than 5
357
Trace Program with Arrays
After this line is executed,
values[2] is 3 (2 + 1)
358
Trace Program with Arrays
After this, i becomes 3.
359
Trace Program with Arrays
i (=3) is still less than 5.
360
Trace Program with Arrays
After this line, values[3] becomes 6 (3 + 3)
361
Trace Program with Arrays
After this, i becomes 4
362
Trace Program with Arrays
i (=4) is still less than 5
363
Trace Program with Arrays
After this, values[4] becomes 10 (4 + 6)
364
Trace Program with Arrays
After i++, i becomes 5
365
Trace Program with Arrays
i ( =5) < 5 is false. Exit the loop
366
Trace Program with Arrays
After this line, values[0] is 11 (1 + 10)
367
Enhanced for Loop
JDK 1.5 and above 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 scoreArray:
for(int val : scoreArray)
System.out.println(val);
In general, the syntax is
for (elementType value: arrayRefVar) {
// Process the value
}
You still have to use an index variable if you wish to traverse the array
in a different order or change the elements in the array.
368
Array Processing
1. (Printing arrays)
2. (Summing all elements)
3. (Finding the largest element)
4. (Finding the smallest index of the largest
element)
369
Example: Print an Array
■ Print an array of int and an array of double:
public class PrintArrays { These
static final int ARRSIZE = 10; // The array's size
must be
static ...
static int intArr[] = new int[ARRSIZE]; // Create the int array
static double realArr[] = { 1.1, 2.2, 3.3, 4.4,
5.5, 6.6, 7.7, 8.8, 9.9, 10.10 }; // And a double array
public static void main(String args[]) {
System.out.println("Ints \t Reals");
for (int k = 0; k < intArr.length; k++)
System.out.println( intArr[k] + " \t " + realArr[k]);
} // main() Program Output
} // PrintArrays Ints Reals
0 1.1
0 2.2
… in order to 0 3.3
0 4.4
refer to them in Uninitialized int
0 5.5
0 6.6
static main() array has
0 7.7
0 8.8
0 9.9
default values 370
0 10.1
of 0.
Example: Store the First 100
Squares
public class Squares {
static final int ARRSIZE = 100; // The array's size
static int intArr[] = new int[ARRSIZE]; // Create an int array
public static void main(String args[]) {
for (int k = 0; k < intArr.length; k++) // Initialize the
array
intArr[k] = (k+1) * (k+1);
System.out.print("The first 100 squares are"); // Print a
heading
for (int k = 0; k < intArr.length; k++)
{ // Print the array
if (k % 10 == 0)
System.out.println(" "); // 10 elements per row
System.out.print( intArr[k] + " ");
} // for Program Output
} // main() The first 100 squares are
1 4 9 16 25 36 49 64 81 100
} // Squares 121 144 169 196 225 256 289 324 361 400
441 484 529 576 625 676 729 784 841 900
961 1024 1089 1156 1225 1296 1369 1444 1521 1600
1681 1764 1849 1936 2025 2116 2209 2304 2401 2500
2601 2704 2809 2916 3025 3136 3249 3364 3481 3600
371
3721 3844 3969 4096 4225 4356 4489 4624 4761 4900
5041 5184 5329 5476 5625 5776 5929 6084 6241 6400
6561 6724 6889 7056 7225 7396 7569 7744 7921 8100
Exercise 1 (Question 1)
Modify program ArrayDemo and save as ArrayDemo1
■ Initialize the elements in one initialization statement
class ArrayDemo {
public static void main(String[] args) {
int[] anArray; // declares an array of integers
anArray = new int[10]; // allocates memory for 10 integers
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // etc.
anArray[3] = 400;
anArray[4] = 500;
anArray[5] = 600;
anArray[6] = 700;
anArray[7] = 800;
anArray[8] = 900;
anArray[9] = 1000;
double[] myList = {5.6, 4.5, 3.3, 13.2, 4, 34.33,
34, 45.45, 99.993, 11.3};
Exercise 1 (Question 1) cont.
1. Use traditional for loop to print all the values
Lecture 13
Based on Slides of Dr. Norazah Yusof
380
Passing Array Elements to a
Method
n When a single element of an array is passed
to a method it is handled like any other
variable.
n See example: PassElements.java
8-381
Example 1
1. public class PassElements {
2. public static void main (String[] args) {
3. int[] numbers = {5, 10, 15, 20, 25, 30, 35, 40};
4. for (int i=0; i<numbers.length; i++) {
5. showValue(numbers[i]);
6. }
7. System.out.println();
8. }
9.
10. public static void showValue(int num) {
11. System.out.print((num+2) + " ");
12. }
13.}
382
Passing Arrays as Arguments to
Methods
n More often you will want to write methods to
process array data by passing the entire
array, not just one element at a time.
n An array can be passed as an argument to a
method.
n To pass an array, you pass the value in the
variable that references the array.
n See example: PassArray.java
8-383
Example 2
1.import java.util.*;
2.public class PassArray {
3. public static void main (String[] args) {
4. final int SIZE = 4;
5. int[] numbers = new int[SIZE];
6. getValues(numbers);
7. System.out.println("Here are the numbers.");
8. showArray(numbers);
9. System.out.println();
10. }
384
Example 2
12. public static void getValues(int[] arr) {
13. Scanner kb= new Scanner(System.in);
14. System.out.println("Enter a series of " + arr.length +
15. " numbers.");
16. for (int i=0; i<arr.length; i++) {
17. System.out.print("Enter number " + (i+1) + ":");
18. arr[i] = kb.nextInt();
19. }
20. }
21. public static void showArray(int[] arr) {
22. for (int i=0; i<arr.length; i++) {
23. System.out.print(arr[i] + " ");
24. }
25. }
26.} 385
Pass By Value
n Java uses pass by value to pass
parameters to a method.
n There are important differences
between passing a value of
variables of primitive data types and
passing arrays.
Pass By Value
n For a parameter of a primitive type value, the
actual value is passed. Changing the value of the
local parameter inside the method does not affect
the value of the variable outside the method.
n For a parameter of an array type, the value of the
parameter contains a reference to an array; this
reference is passed to the method. Any changes
to the array that occur inside the method body
will affect the original array that was passed as
the argument.
Lab 5 – Exercise 1 – Question 1(i)
public class Lab7Ex1_1i {
public static void main(String[] args) {
int x = 1; // x represents an int value
int[] y = new int[10]; // y represents an array of int values
m(x, y); // Invoke m with arguments x and y
System.out.println("x is " + x);
System.out.println("y[0] is " + y[0]);
}
public static void m(int number, int[] numbers) {
number = 1001; // Assign a new value to number
numbers[0] = 5555; // Assign a new value to numbers[0]
}
}
x is 1
y[0] is 5555
388
Heap
389
Call Stack and Heap
n When invoking m(x, y), the values of x and y are passed to number and
numbers. Since y contains the reference value to the array, numbers now
contains the same reference value to the same array.
n The JVM stores the array in an area of memory, called heap, which is
used for dynamic memory allocation where blocks of memory are
allocated and freed in an arbitrary order.
390
Passing Arrays as Arguments
Lab 5 – Exercise 1 – Question 1(ii)
public class Lab5a {
public static void main(String[] args) {
int[] a = {1,2}; // a represents an array of int values
System.out.println("Before invoking swap");
System.out.println("aray is {" + a[0] + ", " + a[1] + "}");
swap(a[0],a[1]);
System.out.println("After invoking swap");
System.out.println("aray is {" + a[0] + ", " + a[1] + "}");
System.out.println("Before invoking swapFirstTwoInArray");
System.out.println("aray is {" + a[0] + ", " + a[1] + "}");
swapFirstTwoInArray(a);
System.out.println("After invoking swap");
System.out.println("aray is {" + a[0] + ", " + a[1] + "}");
} 392
Passing Arrays as Arguments
Lab 5 – Exercise 1 – Question 1(ii)
public static void swap(int n1, int n2) {
int temp = n1;
n1 = n2;
n2 = temp;
}
public static void
swapFirstTwoInArray(int[] array) {
int temp = array[0];
array[0] = array[1];
array[1] = temp;
}
} 393
Example, cont.
394
Returning an Array Reference
Lab 5 – Exercise 1 – Question 1(iii)
n A method can return a reference to an array.
n The return type of the method must be declared as
an array of the right type.
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
n The reverse() method is a public static method
that returns an array of int.
8-395
n Create a new class
n Create a main method
n Create an array with size 5
n Print the values of the array
n Call method reserve and pass the array
n Again, print the values of the array
396
Returning an Array from a Method
Lab 5 – Exercise 1 – Question 1(iii)
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
} list
result
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
397
Anonymous Array
The statement
printArray(new int[]{3, 1, 2, 6, 4, 2});
398
Variable-Length Argument Lists
printMax(21.8,32.2,13.0,45.2,25.8,36.5);
printMax(new double[]{1,4,5,2});
}
public static void printMax(double ... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
double result = numbers[0];
for (int i=1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
400
}
}
Array of Objects
Lecture 14
Based on Slides of Dr. Norazah Yusof
401
Array of Objects
n We can create an array of object.
n By combining the advantage of array,
and objects, we can build program more
clean and better logical organization
402
Array of Objects
n Assume we need to store collection of 50
students, for example, we need to use
several different arrays (one for names, one
for address, one for matrix number and so
forth.) which is very cumbersome and prone
to error
n The better way is by creating an array of
students object. This will result a more
concise and easier-to-understand code.
403
Array of objects declaration
n Declaration of array: 2 ways
n Way one: involve 2 steps:
1) Step 1: Creation of array of type class
(to hold objects of that class type).
n Syntax:
ClassName [] ArrayName = new
ClassName[ArraySize];
n Example:
Employee emp[] = new Employee[5];
404
Array of objects declaration
2) Step 2: Creation of object in each
/ particular index of the array.
n Syntax:
ArrayName[index]=new ClassName();
n Example:
emp[0] = new Employee(101,12000);
emp[1] = new Employee(102,25000);
:
emp[4] = new Employee(105,38000);
405
Array of objects declaration and
Initialization
n Second Way: Initializer list.
n Creation of array of type class and initialize
it using the constructor of the class.
n Syntax:
ClassName [] ArrayName ={new ClassName(1,1),
new ClassName(1,0)};
n Example:
Rectangle[] rect1 ={new Rectangle(4,2), new
Rectangle(3,3), new Rectangle(6,7)};
406
Two Dimensional Array
Lecture 15
Based on Slides of Dr. Norazah Yusof
409
Two-dimensional Arrays
int[][] labMarks = { 14 13 11 9 5 0
{14, 13, 11, 9, 5}, 17 18 15 13 11 1 row
{17, 18, 15, 13, 11},
labMarks 12 11 17 20 14 2 s
{12, 11, 17, 20, 14}
} 0 1 2 3 4
columns
array of three rows and five columns
labMarks[2][3]
or
// Combine declaration and creation in one statement
dataType[][] refVar = new dataType[5][5];
// Alternative syntax
dataType refVar[][] = new dataType[5][5];
411
Declaring Variables of Two-dimensional
Arrays and Creating Two-dimensional
Arrays
Example:
int[][] matrix = new int[5][5];
or
int matrix[][] = new int[5][5];
Accessing Two-Dimensional Array
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 100);
412
Two-dimensional Array Illustration
matrix.length? 5 array.length? 4
matrix[0].length? 5 array[0].length? 3
413
Declaring, Creating, and Initializing Using
Shorthand Notations
You can also use an array initializer to declare, create and
initialize a two-dimensional array. For example,
int[][] array = {
int[][] array = new int[4][3];
{1, 2, 3}, array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, Same as array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};
414
Lengths of Two-dimensional
Arrays
int[][] x = new int[3][4];
415
Lengths of Two-dimensional
Arrays, cont.
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
416
Processing Two-Dimensional Arrays
n Declare a two-dimensional array named matrix of
type integer with 3 rows and 4 columns:
int[][] matrix = new int[3][4];
n Some processing examples:
1. Input arrays with values read from the keyboard.
2. Printing arrays.
3. Summing all elements.
4. Summing elements by column
5. Finding which row has the largest sum.
418
Accessing Two-Dimensional Array
Elements
n Programs that process two-dimensional arrays can
do so with nested loops. Number of rows, not
n To fill the matrix array: the largest subscript
for (int row = 0; row < matrix.length; row++)
{ Number of columns, not
the largest subscript
for (int col = 0; col < matrix[row].length; col++)
{
System.out.print("Enter a value: ");
matrix[row][col] = keyboard.nextInt();
}
} keyboard references
8-419
a Scanner object
Accessing Two-Dimensional Array
Elements
n To print out the matrix array:
for (int row = 0; row < matrix.length;
row++)
{
for (int col = 0; col <
matrix[row].length; col++)
{
System.out.println(matrix[row][col]);
}
}
8-420
Summing The Elements of a Two-
Dimensional Array
int[][] numbers = { { 1, 2, 3, 4 },
{5, 6, 7, 8},
{9, 10, 11, 12} };
int total;
total = 0;
for (int row = 0; row < numbers.length; row++)
{
for (int col = 0; col < numbers[row].length;
col++)
total += numbers[row][col];
}
System.out.println("The total is " + total);
8-421
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
{3, 4, 5}, matrix[0].length is 5
matrix[1].length is 4
{4, 5},
matrix[2].length is 3
{5} matrix[3].length is 2
}; matrix[4].length is 1
422
Ragged Arrays, cont.
423
More Than Two Dimensions
n Java does not limit the number of dimensions that
an array may be.
n More than three dimensions is hard to visualize,
but can be useful in some programming problems.
8-424
Using the Arrays Class
n Arrays class
n Contains many useful methods for
manipulating arrays
n static methods
n Use with class name
n Without instantiating Arrays object
n binarySearch() method
n Convenient way to search through sorted lists of
values of various data types
n List must be in order
Java Programming, Fourth 425
Edition
Useful Methods of the Arrays
Class