OOP Overall Reviewer

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 131

import java.io.

*;

// Creates an ADDRESBOOK that contains 100 AddressBookEntries

public class AddressBook


{
//index of the last entry
private int top = 0;

//constant number that indicates the maximum


//number of entries in the address book
private static final int MAXENTRIES = 100;

//array of Address Book Entries


private AddressBookEntry[] list;

// The main method


public static void main(String[] args){

BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));


AddressBook addBook = new AddressBook();
String act = "";

while(true){
//displays the options
System.out.println("\n[A] Add entry");
System.out.println("[D] Delete entry");
System.out.println("[V] View all entries");
System.out.println("[U] Update entry");
System.out.println("[Q] Quit");
System.out.print("Enter desired action: ");

try{
act = keyIn.readLine(); //gets the choice
}catch(Exception e){System.out.println("Error");}

//checks for the appropriate action for his choice


if(act.equals("A")||act.equals("a"))
addBook.addEntry();
else if(act.equals("D")||act.equals("d"))
addBook.delEntry();
else if(act.equals("V")||act.equals("v"))
addBook.viewEntries();
else if(act.equals("U")||act.equals("u"))
addBook.updateEntry();
else if(act.equals("Q")||act.equals("q"))
System.exit(0);
else
System.out.println("Unknown command");
}

/**
* creates the AddressBook
*/
public AddressBook(){
list = new AddressBookEntry[MAXENTRIES];
}
/**
* method for adding an AddressBookEntry to the Adressbook
*/
public void addEntry(){

BufferedReader keyIn = new BufferedReader(new InputStreamReader(System.in));


String name = "";
String add = "";
int tel = 0;
String email = "";

if(top == MAXENTRIES){
System.out.println("Address Book is full");
return;
}

//asks the user for the data of the address book


try{
System.out.print("Name: ");
name = keyIn.readLine();
System.out.print("Address: ");
add = keyIn.readLine();
System.out.print("Telephone number: ");
tel = Integer.parseInt(keyIn.readLine());
System.out.print("Email Adress: ");
email = keyIn.readLine();
}catch(Exception e){
System.out.println(e);
System.exit(0);
}

AddressBookEntry entry = new AddressBookEntry(name, add, tel, email);


list[top] = entry;
top++;
}

/**
* method that deletes an AddressBookEntry from the Adressbook
* with the index
*/
public void delEntry(){

BufferedReader keyIn = new BufferedReader(new InputStreamReader


(System.in));
int index = 0;

//checks if the address book is empty


if(top == 0){
System.out.println("Address Book is empty");
return;
}

//asks for the entry which is to be deleted


try{
//shows the current entries on the record book
viewEntries();

System.out.print("\nEnter entry number: ");


index = Integer.parseInt(keyIn.readLine())-1;
}catch(Exception e){}
//checks if the index is with in bounds
if(index < 0 || index >= top){
System.out.println("Index Out Of Bounds");
return;
}else{
for( int i=index; i<top; i++ ){
list[i] = list[i+1];
}
list[top] = null;
top--;
}
}

/**
* method that prints all the entries in the AddressBook
*/
public void viewEntries(){

for(int index = 0; index < top; index++){


System.out.println((index+1)+" Name:"+list[index].getName());
System.out.println("Address:"+list[index].getAddress());
System.out.println("Telephone Number:"+list[index].getTelNumber());
System.out.println("Email Address:"+list[index].getEmailAdd());
}
}

/**
* method that updates an entry
*/
public void updateEntry(){

BufferedReader keyIn = new BufferedReader(new InputStreamReader


(System.in));
int index = 0;
String name = "";
String add = "";
int tel = 0;
String email = "";

//asks for the entries data


try{
System.out.print("Entry number: ");
index = Integer.parseInt(keyIn.readLine())-1;
System.out.print("Name: ");
name = keyIn.readLine();
System.out.print("Address: ");
add = keyIn.readLine();
System.out.print("Telephone number: ");
tel = Integer.parseInt(keyIn.readLine());
System.out.print("Email Adress: ");
email = keyIn.readLine();
}catch(Exception e){
System.out.println(e);
System.exit(0);
}

//updates the entry


AddressBookEntry entry = new AddressBookEntry
(name, add, tel, email);
list[index] = entry;
}
}
/**
* An address book class that record a persons
* name, address, telephone number, and email address
*/
public class AddressBookEntry
{

private String name;


private String add;
private int tel;
private String email;

/**
* default constructor
*/
public AddressBookEntry(){
name = "";
add = "";
tel = 0;
email = "";
}

/**
* Creates an AddressBookEntry object with the given name,
* address, telephone number and email address
*/
public AddressBookEntry(String name, String add,
int tel, String email){
this.name = name;
this.add = add;
this.tel = tel;
this.email = email;
}

/**
* returns the variable name
*/
public String getName(){
return name;
}

/**
* changes the variable name
*/
public void setName(String name){
this.name = name;
}

/**
* returns the variable address
*/
public String getAddress(){
return add
}
/**
* changes the variable address
*/
public void setAddress(String add){
this.add = add;
}

/**
* returns the variable tel
*/
public int getTelNumber(){
return tel;
}

/**
* changes the variable tel
*/
public void setTelNumber(int tel){
this.tel = tel;
}

/**
* returns the variable email
*/
public String getEmailAddress(){
return email;
}

/**
* changes the variable email
*/
public void setEmailAddress(String email){
this.email = email;
}
}
import java.awt.*;
import java.awt.event.*;

class TicTacToe extends Frame {


String turn = "O"; //value is either "O" or "X"
Panel board;
TicTacToeButton button[][];
Label playerTurn;
ButtonHandler bH = new ButtonHandler();
int usedCells = 0; //number of cells in use

TicTacToe(String title) {
super(title);
board = new Panel();
button = new TicTacToeButton[3][];
playerTurn = new Label("Player One's Turn");
}

void launchGame() {
board.setLayout(new GridLayout(3,3));
/* initialize buttons */
for (int i = 0, count = 0; i < 3; i++) {
button[i] = new TicTacToeButton[3];
for (int j = 0; j < 3; j++, count++) {
button[i][j] = new TicTacToeButton();
/* inialize button values to 0,1, 2,...,8 */
button[i][j].value = (new Integer(count)).toString();
board.add(button[i][j]);
/* add listeners to the buttons */
button[i][j].addActionListener(bH);
}
}
add(board);
add(playerTurn, BorderLayout.SOUTH);
/* add listeners for closing the frame */
addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent event ) {
System.exit( 0 );
}
} );
/* display */
pack();
setVisible(true);
}

class ButtonHandler implements ActionListener {


void changeButtonLabel(TicTacToeButton b) {
b.setLabel(turn);
b.value = turn;
/* remove listener */
b.removeActionListener(bH);
usedCells++;
}

//continued on next page


public void actionPerformed(ActionEvent ae) {
boolean win = false;
boolean draw = false;
int player = 0;
TicTacToeButton b = (TicTacToeButton) ae.getSource();
/* change content of button to O or X */
changeButtonLabel(b);
/* check for a win */
/* horizontal */
for (int i = 0; i < 3; i++) {
if ((button[i][0].value).equals(button[i][1].value) &&
(button[i][0].value).equals(button[i][2].value)) {
win = true;
}
}
/* vertical */
for (int i = 0; i < 3; i++) {
if ((button[0][i].value).equals(button[1][i].value) &&
(button[0][i].value).equals(button[2][i].value)) {
win = true;
}
}
/* diagonal */
if ((button[0][0].value).equals(button[1][1].value) &&
(button[0][0].value).equals(button[2][2].value)) {
win = true;
} else if ((button[0][2].value).equals(button[1][1].value) &&
(button[0][2].value).equals(button[2][0].value)) {
win = true;
}
/* check for a draw */
if (!win) {
if (usedCells==9) {
draw = true;
}
}
/* Change message */
String message = "";

//continued on next page


if (win) {
if (turn.equals("O")) {
player = 1;
} else {
player = 2;
}
message += "Player " + player + " wins!";
/* remove all listeners */
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
button[i][j].removeActionListener(bH);
}
}
} else if (draw) {
message += "It's a draw!";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
button[i][j].removeActionListener(bH);
}
}
} else {
/* change turn */
if (turn.equals("O")) {
turn = new String("X");
player = 2;
message += "Player Two's Turn.";
} else {
turn = new String("O");
player = 1;
message += "Player One's Turn.";
}
}
playerTurn.setText(message);
}
}

class TicTacToeButton extends Button {


String value;
}

public static void main(String args[]) {


TicTacToe game = new TicTacToe("Tic-Tac-Toe");
game.launchGame();
}
}
Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 7: User Defined Classes

Module No. 7
MODULE TITLE
USER-DEFINED CLASSES

MODULE OVERVIEW

Now that we've studied on how to use existing classes from the Java class library, we will now be studying
on how to write our own classes. For this section, in order to easily understand how to create classes, we will
make a sample class wherein we will add more data and functionality as we go along the way.

We will create a class that contains information of a Student and operations needed for a certain student
record.

Things to take note of for the syntax defined in this section and for the other sections:

* - means that there may be 0 or more occurrences of the line


where it was applied to.
<description> - indicates that you have to substitute an actual value for this
part instead of typing it as it is.
[] - indicates that this part is optional

LEARNING OBJECTIVES

At the end of the lesson, the student should be able to:


• Create their own classes
• Declare attributes and methods for their classes
• Use the this reference to access instance data
• Create and call overloaded methods
• Import and create packages
• Use access modifiers to control access to class members

LEARNING CONTENTS

User-Defined Classes
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Defining Your Own Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Declaring Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Instance Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Class Variables and Static Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Declaring Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Accessor Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Mutator Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Multiple Return Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Sample Source Code for StudentRecord Class . . . . . . . . . . . . . . . . . . . 10
The this Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Overloading Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Declaring Constructor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Default Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Overloading Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Using Constructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
The this() Constructor Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Importing Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Creating Your Own Packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

PANGASINAN STATE UNIVERSITY 5


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 7: User Defined Classes

Setting the CLASSPATH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17


Access Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
default access (also called package accessibility). . . . . . . . . . . . . . . . . 18
public access. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
protected access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
private access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

LEARNING POINTS

• Overloading involves writing multiple methods with the same name but different parameter lists.
Methods that have identical parameter lists are illegal, even if they have different return types.

• When you overload methods, you risk creating an ambiguous situation—one in which the compiler
cannot determine which method to use.

• When you write your own constructors, they can receive parameters. Such parameters often are used
to initialize data fields for an object. After you write a constructor for a class, you no longer receive the
automatically provided default constructor. If a class’s only constructor requires an argument, you must
provide an argument for every object of the class that you create. You can overload constructors just as
you can other methods.

• Within nonstatic methods, data fields for the correct object are accessed because a this reference is
implicitly passed to nonstatic methods. Static methods do not have a this reference because they have
no object associated with them; static methods are also called class methods.

• Static class fields and methods are shared by every instantiation of a class. When a field in a class is
final, it cannot change after it is assigned its initial value.

LEARNING ACTIVITIES

Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
True or False . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Address Book Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
AddressBook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

REFERENCES

1. Programming Language. From Wikipedia at


http://en.wikipedia.org/wiki/Programming_language

2. Programming Language. From Webopedia at


http://www.webopedia.com/TERM/p/programming_language.html

3. Programming Language. From Answers.com at


http://www.answers.com/topic/programming-language

4. High-Level Programming Language. From Wikipedia at


http://en.wikipedia.org/wiki/High-level_programming_language

5. Defining Flowchart Symbols. Available at http://www.pattonpatton.


com/basic_flow_chart_symbols.htm

6. Integrated Development Environment. From Webopedia at


http://www.webopedia.com/TERM/I/integrated_development_environment.html

7. Variables and Expressions. Available at


http://www.geocities.com/SiliconValley/Park/3230/java/javl1002.html

PANGASINAN STATE UNIVERSITY 6


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 7: User Defined Classes

8. Writing Abstract Classes and Methods. Available at


http://java.sun.com/docs/books/tutorial/java/javaOO/abstract.html

9. Defining an Interface. Available at


http://java.sun.com/docs/books/tutorial/java/interpack/interfaceDef.html

20.Inheritance and Polymorphism. Available at


http://home.cogeco.ca/~ve3ll/jatutor7.htm

21.The Essence of OOP using Java, Runtime Polymorphism through Inheritance.


Available at http://www.developer.com/tech/article.php/983081

22.Gary B. Shelly, Thomas J. Cashman, Joy L. Starks. Java Programming Complete Concepts
and Techniques. Course Technology Thomson Learning. 2001.

23.Stephen J. Chapman. Java for Engineers and Scientists 2nd Edition. Pearson Prentice Hall. 2004

24.Deitel & Deitel. Java How to Program 5th Edition.

25.Sun Java Programming Student Guide SL-275. Sun Microsystems. February 2001.

26.Does Java pass by reference or pass by value? Why can't you swap in Java? Available at
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

27.Java Branching Statements. Available at


http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html.

28.Encapsulation. Available at http://home.cogeco.ca/~ve3ll/jatutor4.htm.

29. Joyce Farrell (2019), Java Programming 9th ed, Ceangage Learning

PANGASINAN STATE UNIVERSITY 7


Object-Oriented Programming

Lesson No. 10

GUI EVENT HANDLING

What is the lesson all about?

In this lesson, you will learn how to handle events triggered when the user interacts with
your Graphical User Interface application. After completing this module, you'll be able to
develop GUI applications that responds to user interaction.

What do you expect from the lesson?

After completing this lesson, you should be able to:


• Explain the delegation event model components
• Understand how the delegation event model works
• Create GUI applications that interact with the user
• Discuss benefits of adapter classes
• Discuss advantages of using inner and anonymous classes

What are the contents of the lesson?

The Delegation Event Model


The Delegation event model describes how your program can respond to user interaction.
To understand the model, let us first study its three important components.

1. Event Source
The event source refers to the GUI component that generates the event. For example, if
the user presses a button, the event source in this case is the button.

juliomcervantes 179
Object-Oriented Programming

2. Event Listener/Handler
The event listener receives news of events and processes user's interaction. When a
button is pressed, the listener may handle this by displaying an information useful to the
user.

3. Event Object
When an event occurs (i.e., when the user interacts with a GUI component), an event
object is created. The object contains all the necessary information about the event that
has occurred. The information includes the type of event that has occurred, say, the
mouse was clicked. There are several event classes for the different categories of user
action. An event object has a data type of one of these classes.

Here now is the delegation event model.

Figure 1. Delegation Event Model

Initially, a listener should be registered with a source so that it can receive information about
events that occur at the source. Only registered listeners can receive notifications of events.
Once registered, a listener simply waits until an event occurs.

When something happens at the event source, an event object describing the event is
created. The event is then fired by the source to the registered listeners.

juliomcervantes 180
Object-Oriented Programming

Once the listener receives an event object (i.e., a notification) from the source, it goes to
work. It deciphers the notification and processes the event that occurred.

Registration of Listeners
The event source registers a listener through the add<Type>Listener methods.

void add<Type>Listener(<Type>Listener listenerObj)

<Type> depends on the type of event source. It can be Key, Mouse, Focus, Component,
Action and others.

Several listeners can register with one event source to receive event notifications.

A registered listener can also be unregistered using the remove<Type>Listener methods.

void remove<Type>Listener(<Type>Listener listenerObj)

Event Classes
An event object has an event class as its reference data type. At the root of event class
heirarchy is the EventObject class, which is found in the java.util package. An immediate
subclass of the EventObject class is the AWTEvent class. The AWTEvent class is defined in
java.awt package. It is the root of all AWT-based events. Here are some of the AWT event
classes.

Event Class Description


ComponentEvent Extends AWTEvent. Instantiated when a component is moved,
resized, made visible or hidden.
InputEvent Extends ComponentEvent. The abstract root event class for all
component-level input event classes.
ActionEvent Extends AWTEvent. Instantiated when a button is pressed, a list item
is double-clicked, or a menu item is selected.
ItemEvent Extends AWTEvent. Instantiated when an item is selected or
deselected by the user, such as in a list or a checkbox.
KeyEvent Extends InputEvent. Instantiated when a key is pressed, released or
typed.
MouseEvent Extends InputEvent. Instantiated when a mouse button is pressed,
released, or clicked (pressed and released), or when a mouse cursor
enteres or exits a visible part of a component.

juliomcervantes 181
Object-Oriented Programming

Event Class Description


TextEvent Extends AWTEvent. Instantiated when the value of a text field or a
text area is changed.
WindowEvent Extends ComponentEvent. Instantiated when a Window object is
opened, closed, activated, deactivated, iconified, deiconified, or when
focus is transferred into or out of the window.

Table 1. Event classes

Take note that all AWTEvent subclasses follow this naming convention:

<Type>Event

Event Listeners

Event listeners are just classes that implement the <Type>Listener interfaces. The following
table shows some of the listener interfaces commonly used.

Event Listeners Description


ActionListener Receives action events.
MouseListener Receives mouse events.
MouseMotionListener Receives mouse motion events, which include dragging and
moving the mouse.
WindowListener Receives window events.

Table 2. Event Listeners

ActionListener Method
The ActionListener interface contains only one method.

ActionListener Method
public void actionPerformed(ActionEvent e)
Contains the handler for the ActionEvent e that occurred.

Table 3. The ActionListener method

juliomcervantes 182
Object-Oriented Programming

MouseListener Methods

These are the MouseListener methods that should be overriden by the implementing class.

MouseListener Methods
public void mouseClicked(MouseEvent e)
Contains the handler for the event when the mouse is clicked (i.e., pressed and
released).
public void mouseEntered(MouseEvent e)
Contains the code for handling the case wherein the mouse enters a component.
public void mouseExited(MouseEvent e)
Contains the code for handling the case wherein the mouse exits a component.
public void mousePressed(MouseEvent e)
Invoked when the mouse button is pressed on a component.
public void mouseReleased(MouseEvent e)
Invoked when the mouse button is released on a component.

Table 3. The MouseListener methods

MouseMotionListener Methods
The MouseMotionListener has two methods to be implemented.

MouseListener Methods
public void mouseDragged(MouseEvent e)
Contains the code for handling the case wherein the mouse button is pressed on a
component and dragged. Called several times as the mouse is dragged.
public void mouseMoved(MouseEvent e)
Contains the code for handling the case wherein the mouse cursor is moved onto a
component, without the mouse button being pressed. Called multiple times as the
mouse is moved.

Table 4. The MouseMotionListener methods

WindowListener Methods
These are the methods of the WindowListener interface.

WindowListener Methods
public void windowOpened(WindowEvent e)
Contains the code for handling the case when the Window object is opened (i.e., made
visible for the first time).

juliomcervantes 183
Object-Oriented Programming

WindowListener Methods
public void windowClosing(WindowEvent e)
Contains the code for handling the case when the user attempts to close Window object
from the object's system menu.
public void windowClosed(WindowEvent e)
Contains the code for handling the case when the Window object was closed after
calling dispose (i.e., release of resources used by the source) on the object.
public void windowActivated(WindowEvent e)
Invoked when a Window object is the active window (i.e., the window in use).
public void windowDeactivated(WindowEvent e)
Invoked when a Window object is no longer the active window.
public void windowIconified(WindowEvent e)
Called when a Window object is minimized.
public void windowDeiconified(WindowEvent e)
Called when a Window object reverts from a minimized to a normal state.

Table 5. The WindowListener methods

Guidelines for Creating Applications Handling GUI Events

These are the steps you need to remember when creating a GUI application with event
handling.

1. Create a class that describes and displays the appearance of your GUI application.
2. Create a class that implements the appropriate listener interface. This class may refer to
the same class as in the first step.
3. In the implementing class, override ALL methods of the appropriate listener interface.
Describe in each method how you would like the event to be handled. You may give
empty implementations for methods you don't want to handle.
4. Register the listener object, the instantiation of the listener class in step 2, with the
source component using the add<Type>Listener method.

Mouse Events Example

import java.awt.*;
import java.awt.event.*;

public class MouseEventsDemo extends Frame implements


MouseListener, MouseMotionListener
{
TextField tf;
public MouseEventsDemo(String title){

juliomcervantes 184
Object-Oriented Programming

super(title);
tf = new TextField(60);
addMouseListener(this);
}
public void launchFrame() {
/* Add components to the frame */
add(tf, BorderLayout.SOUTH);
setSize(300,300);
setVisible(true);
}
public void mouseClicked(MouseEvent me) {
String msg = "Mouse clicked.";
tf.setText(msg);
}
public void mouseEntered(MouseEvent me) {
String msg = "Mouse entered component.";
tf.setText(msg);
}
public void mouseExited(MouseEvent me) {
String msg = "Mouse exited component.";
tf.setText(msg);
}
public void mousePressed(MouseEvent me) {
String msg = "Mouse pressed.";
tf.setText(msg);
}
public void mouseReleased(MouseEvent me) {
String msg = "Mouse released.";
tf.setText(msg);
}
public void mouseDragged(MouseEvent me) {
String msg = "Mouse dragged at " + me.getX() + "," + me.getY();
tf.setText(msg);
}
public void mouseMoved(MouseEvent me) {
String msg = "Mouse moved at " + me.getX() + "," + me.getY();
tf.setText(msg);
}
public static void main(String args[]) {
MouseEventsDemo med = new MouseEventsDemo("Mouse Events Demo");
med.launchFrame();
}
}

juliomcervantes 185
Object-Oriented Programming

Figure 1. Output of MouseEventsDemo program

Close Window Example

import java.awt.*;
import java.awt.event.*;

class CloseFrame extends Frame implements WindowListener {


Label label;

CloseFrame(String title) {
super(title);
label = new Label("Close the frame.");
this.addWindowListener(this);
}

void launchFrame() {
setSize(300,300);
setVisible(true);
}

public void windowActivated(WindowEvent e) {


}
public void windowClosed(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
setVisible(false);
System.exit(0);
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}

juliomcervantes 186
Object-Oriented Programming

public void windowIconified(WindowEvent e) {


}
public void windowOpened(WindowEvent e) {
}

public static void main(String args[]) {


CloseFrame cf = new CloseFrame("Close Window Example");
cf.launchFrame();
}
}

Figure 2. Output of CloseFrame program

Adapter Classes

Implementing all methods of an interface takes a lot of work. More often than not, you are
interested in implementing some methods of the interface only. Fortunately, Java provides
us with adapter classes that implement all methods of each listener interface with more
than one method. The implementations of the methods are all empty.

Close Window Example

import java.awt.*;
import java.awt.event.*;

class CloseFrame extends Frame{


Label label;
CFListener w = new CFListener(this);

CloseFrame(String title) {
super(title);

juliomcervantes 187
Object-Oriented Programming

label = new Label("Close the frame.");


this.addWindowListener(w);
}

void launchFrame() {
setSize(300,300);
setVisible(true);
}

public static void main(String args[]) {


CloseFrame cf = new CloseFrame("Close Window Example");
cf.launchFrame();
}
}

class CFListener extends WindowAdapter{


CloseFrame ref;
CFListener( CloseFrame ref ){
this.ref = ref;
}

public void windowClosing(WindowEvent e) {


ref.dispose();
System.exit(1);
}
}

Figure 3. Output of CloseFrame program

juliomcervantes 188
Object-Oriented Programming

Inner Classes and Anonymous Inner Classes

This section gives you a review of a concept you've already learned in your first
programming course. Inner classes and anonymous inner classes are very useful in GUI event
handling.

Inner Classes
Here is a brief refresher on inner classes. An inner class, as its name implies, is a class
declared within another class. The use of inner classes would help you simplify your
programs, especially in event handling as shown in the succeeding example.

Close Window Example

import java.awt.*;
import java.awt.event.*;

class CloseFrame extends Frame{


Label label;

CloseFrame(String title) {
super(title);
label = new Label("Close the frame.");
this.addWindowListener(new CFListener());
}

void launchFrame() {
setSize(300,300);
setVisible(true);
}

class CFListener extends WindowAdapter {


public void windowClosing(WindowEvent e) {
dispose();
System.exit(1);
}
}

public static void main(String args[]) {


CloseFrame cf = new CloseFrame("Close Window Example");
cf.launchFrame();
}
}

Anonymous Inner Classes

Now, anonymous inner classes are unnamed inner classes. Use of anonymous inner classes
would further simplify your codes. Here is a modification of the example in the preceding
section.

juliomcervantes 189
Object-Oriented Programming

Close Window Example

import java.awt.*;
import java.awt.event.*;

class CloseFrame extends Frame{


Label label;

CloseFrame(String title) {
super(title);
label = new Label("Close the frame.");
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
dispose();
System.exit(1);
}
});
}

void launchFrame() {
setSize(300,300);
setVisible(true);
}

public static void main(String args[]) {


CloseFrame cf = new CloseFrame("Close Window Example");
cf.launchFrame();
}
}

Option Dialog Example


import javax.swing.*;

public class OptionsDialogTest{

public static void main(String[] args) {

JTextField name = new JTextField();


JTextField initials = new JTextField(6);
JTextField age = new JTextField(3);
JTextArea interests = new JTextArea(10,10);
interests.setLineWrap(true);
interests.setWrapStyleWord(true);

JScrollPane jsp = new JScrollPane(


interests,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );

String s0 = "Please enter your last name";


String s1 = "Please enter your initials";

juliomcervantes 190
Object-Oriented Programming

String s2 = "Please enter your age\n(in years)";


String s3 = "Please enter your main interests\n(maximum 500 words)";

JOptionPane.showOptionDialog(
null,
new Object[] {s0,name,s1,initials,s2,age,s3,jsp},
"Personal Info",
JOptionPane.OK_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
null,
null
);

System.out.println("name = " + name.getText());


System.out.println("initials = " + initials.getText());
System.out.println("age = " + age.getText());
System.out.println("interests = " + interests.getText());

System.exit(0);

}
}

Figure 4. Output of OptionDialog program

juliomcervantes 191
Object-Oriented Programming

Lesson No. 9

ABSTRACT WINDOWING TOOLKIT AND SWING

What is the lesson all about?

In this lesson, we will be discussing about graphical user interface (GUI). Without learning
about GUI Application Program Interfaces (APIs), you would still be able to create quite a
descent range of different programs. However, your applications are very likely to be bland
and unappealing to the users. Having a good GUI affects the usage of your application. This
results in ease of use and enjoyment of use for the users of your program. Java provides
tools like Abstract Windowing Toolkit (AWT) and Swing to develop interactive GUI
applications.

What do you expect from the lesson?

After completing this lesson, you should be able to:


 Understand similarities and differences between AWT and Swing
 Differentiate between components and containers
 Design GUI applications using AWT
 Design GUI applications using Swing
 Describe how flow layout, border layout and grid layout position GUI components
 Create complex layouts in designing GUI appllications

What are the contents of the lesson?

The Java Foundation Classes (JFCs), which is an important part of the Java SDK, refers to a
collection of APIs that simplifies the development Java GUI applications. It primarily consists
of five APIs including AWT and Swing. The three other APIs are Java2D, Accessibility, and
Drag and Drop. All these APIs assist developers in designing and implementing visually-
enhanced applications.

juliomcervantes 160
Object-Oriented Programming

Both AWT and Swing provides GUI components that can be used in creating Java
applications and applets. You will learn about applets in a latter section. Unlike some AWT
components that use native code, Swing is written entirely using the Java programming
language. As a result, Swing provides a platform-independent implementation ensuring that
applications deployed across different platforms have the same appearance. AWT, however,
does ensure that the look and feel of an application run on two different machines be
comparable. The Swing API is built around a number of APIs that implement various parts of
the AWT. As a result, AWT components can still be used with Swing components.

AWT GUI Components

Fundamental Window Classes


In developing GUI applications, the GUI components such as buttons or text fields are placed
in containers. These are the list of important container classes provided in the AWT.

AWT Class Description

Component An abstract class for objects that can be displayed on the console and
interact with the user. The root of all other AWT classes.
Container An abstract subclass of the Component class. A component that can contain
other components.
Panel Extends the Container class. A frame or window without the titlebar, the
menubar nor the border. Superclass of the Applet class.
Window Also extends Container class. A top-level window, which means that it
cannot be contained in any other object. Has no borders and no menubar.
Frame Extends the Window class. A window with a title, menubar, border, and
resizing corners. Has four constructors, two of which have the following
signatures:
Frame()
Frame(String title)

Table 1. AWT Container classes

To set the size of the window, the overloaded setSize method is used.
void setSize(int width, int height)

Resizes this component to the width and height provided as parameters.

void setSize(Dimension d)

Resizes this component to d.width and d.height based on the Dimension d specified.

juliomcervantes 161
Object-Oriented Programming

A window by default is not visible unless you set its visibility to true. Here is the syntax for
the setVisible method.

void setVisible(boolean b)

In designing GUI applications, Frame objects are usually used. Here's an example of how to
create such an application.

import java.awt.*;

public class SampleFrame extends Frame {


public static void main(String args[]) {
SampleFrame sf = new SampleFrame();
sf.setSize(300, 300); //Try removing this line
sf.setVisible(true); //Try removing this line
}
}

Note that the close button of the frame doesn't work yet because no event handling
mechanism has been added to the program yet. You'll learn about event handling in the next
module.

Graphics
Several graphics method are found in the Graphics class. Here is the list of some of these
methods.

drawLine() drawPolyline() setColor()


fillRect() drawPolygon() getFont()
drawRect() fillPolygon() setFont()
clearRect() getColor() drawString()
Table 2. Some methods of class Graphics

Related to this class is the Color class, which has three constructors.

Constructor Format Description


Color(int r, int g, int b) Integer value is from 0 to 255.
Color(float r, float g, float b) Float value is from 0.0 to 1.0.
Color(int rgbValue) Value range from 0 to 224-1 (black to white).
Red: bits 16-23
Green: bits 8-15
Blue: bits 0-7
Table 2b: Color constructors

juliomcervantes 162
Object-Oriented Programming

Here is a sample program that uses some of the methods in the Graphics class.

import java.awt.*;

public class GraphicPanel extends Panel {


GraphicPanel() {
setBackground(Color.black);//constant in Color class
}
public void paint(Graphics g) {
g.setColor(new Color(0,255,0)); //green
g.setFont(new Font("Helvetica",Font.PLAIN,16));
g.drawString("Hello GUI World!", 30, 100);
g.setColor(new Color(1.0f,0,0)); //red
g.fillRect(30, 100, 150, 10);
}
public static void main(String args[]) {
Frame f = new Frame("Testing Graphics Panel");
GraphicPanel gp = new GraphicPanel();
f.add(gp);
f.setSize(500, 300);
f.setVisible(true);
}
}

For a panel to become visible, it should be placed inside a visible window like a frame.

Figure 1. Output of sample code above

juliomcervantes 163
Object-Oriented Programming

More AWT Components

Here is a list of AWT controls. Controls are components such as buttons or text fields that
allow the user to interact with a GUI application. These are all subclasses of the Component
class.

Label Button Choice


TextField Checkbox List
TextArea CheckboxGroup Scrollbar

Table 3. AWT Components

The following program creates a frame with controls contained in it.

import java.awt.*;

class FrameWControls extends Frame


{
public static void main(String args[])
{
FrameWControls fwc = new FrameWControls();
fwc.setLayout(new FlowLayout());
fwc.setSize(600, 600);
fwc.add(new Button("Test Me!"));
fwc.add(new Label("Name"));
fwc.add(new TextField());
CheckboxGroup cbg = new CheckboxGroup();
fwc.add(new Checkbox("chk1", cbg, true));
fwc.add(new Checkbox("chk2", cbg, false));
fwc.add(new Checkbox("chk3", cbg, false));
List list = new List(3, false);
list.add("ABS-CBN");
list.add("GMA");
list.add("TV5");
fwc.add(list);
Choice chooser = new Choice();
chooser.add("Avril");
chooser.add("Monica");
chooser.add("Britney");
fwc.add(chooser);
fwc.add(new Scrollbar());
fwc.setVisible(true);
}
}

juliomcervantes 164
Object-Oriented Programming

Shown below is a sample output.

Figure 2. Output of sample code above

Layout Managers

The position and size of the components within each container is determined by the layout
manager. The layout managers governs the layout of the components in the container.
These are some of the layout managers included in Java.

1. FlowLayout
2. BorderLayout
3. GridLayout
4. GridBagLayout
5. CardLayout

The layout manager can be set using the setLayout method of the Container class. The
method has the following signature.
void setLayout(LayoutManager mgr)

If you prefer not to use any layout manager at all, you pass null as an argument to this
method. But then, you would have to position the elements manually with the use of the
setBounds method of the Component class.
public void setBounds(int x, int y, int width, int height)

The method controls the position based on the arguments x and y, and the size based on the
specified width and height. This would be quite difficult and tedious to program if you have
several Component objects within the Container object. You'll have to call this method for
each component.

In this section, you'll learn about the first three layout managers.

juliomcervantes 165
Object-Oriented Programming

The FlowLayout Manager


The FlowLayout is the default manager for the Panel class and its subclasses, including the
Applet class. It positions the components in a left to right and top to bottom manner,
starting at the upper-lefthand corner. Imagine how you type using a particular word editor.
This is how the FlowLayout manager works.

It has three constructors which are as listed below.

FlowLayout Constructors
FlowLayout()
Creates a new FlowLayout object with the center alignment and 5-unit horizontal and
vertical gap applied to the components by default.
FlowLayout(int align)
Creates a new FlowLayout object with the specified alignment and the default 5-unit
horizontal and vertical gap applied to the components.
FlowLayout(int align, int hgap, int vgap)
Creates a new FlowLayout object with the first argument as the alignment applied and the
hgap-unit horizontal and vgap-unit vertical gap applied to the components.
Table 4. FlowLayout constructors

The gap refers to the spacing between the components and is measured in pixels. The
alignment argument should be one of the following:
1. FlowLayout.LEFT
2. FlowLayout.CENTER
3. FlowLayout.RIGHT

What is the expected output of the following program?

import java.awt.*;

class FlowLayoutDemo extends Frame {


public static void main(String args[]) {
FlowLayoutDemo fld = new FlowLayoutDemo();
fld.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 10));
fld.add(new Button("ONE"));
fld.add(new Button("TWO"));
fld.add(new Button("THREE"));
fld.setSize(100, 100);
fld.setVisible(true);
}
}

juliomcervantes 166
Object-Oriented Programming

Shown below is a sample output.

Figure 3. Output of sample code in Windows

The BorderLayout Manager


The BorderLayout divides the Container into five parts- north, south, east, west and the
center. Each components is added to a specific region. The north and south regions stretch
horizontally whereas the east and west regions adjust vertically. The center region, on the
other hand, adjusts in both horizontally and vertically. This layout is the default for Window
objects, including objects of Window's subclasses Frame and Dialog type.

BorderLayout Constructors
BorderLayout()
Creates a new BorderLayout object with no spacing applied among the different
components.
BorderLayout(int hgap, int vgap)
Creates a new BorderLayout object with hgap-unit horizontal and vgap-unit spacing
applied among the different components.
Table 5. BorderLayout constructors

Like in the FlowLayout manager, the parameters hgap and vgap here also refers to the
spacing between the components within the container.

To add a component to a specified region, use the add method and pass two arguments: the
component to add and the region where the component is to be positioned. Note that only
one component can be placed in one region. Adding more than one component to a
particular container results in displaying only the last component added. The following list
gives the valid regions are predefined fields in the BorderLayout class.

1. BorderLayout.NORTH
2. BorderLayout.SOUTH
3. BorderLayout.EAST
4. BorderLayout.WEST
5. BorderLayout.CENTER

juliomcervantes 167
Object-Oriented Programming

Here is a sample program demonstrating how the BorderLayout works.

import java.awt.*;

class BorderLayoutDemo extends Frame {


public static void main(String args[]) {
BorderLayoutDemo bld = new BorderLayoutDemo();
bld.setLayout(new BorderLayout(10, 10)); //may remove
bld.add(new Button("NORTH"), BorderLayout.NORTH);
bld.add(new Button("SOUTH"), BorderLayout.SOUTH);
bld.add(new Button("EAST"), BorderLayout.EAST);
bld.add(new Button("WEST"), BorderLayout.WEST);
bld.add(new Button("CENTER"), BorderLayout.CENTER);
bld.setSize(200, 200);
bld.setVisible(true);
}
}

Here is a sample output of this program. The second figure shows the effect of resizing the
frame.

Figure 4. Output of sample code

The GridLayout Manager


With the GridLayout manager, components are also positioned from left to right and top to
bottom as in the FlowLayout manager. In addition to this, the GridLayout manager divides
the container into a number of rows and columns. All these regions are equally sized. It
always ignores the component's preferred size.

The following is the available constructors for the GridLayout class.

juliomcervantes 168
Object-Oriented Programming

GridLayout Constructors
GridLayout()
Creates a new GridLayout object with a single row and a single column by default.
GridLayout(int rows, int cols)
Creates a new GridLayout object with the specified number of rows and columns.
GridLayout(int rows, int cols, int hgap, int vgap)
Creates a new GridLayout object with the specified number of rows and columns. hgap-
unit horizontal and vgap-unit vertical spacings are applied to the components.
Table 6. GridLayout constructors

Try out this program.

import java.awt.*;

class GridLayoutDemo extends Frame {


public static void main(String args[]) {
GridLayoutDemo gld = new GridLayoutDemo();
gld.setLayout(new GridLayout(2, 3, 4, 4));
gld.add(new Button("ONE"));
gld.add(new Button("TWO"));
gld.add(new Button("THREE"));
gld.add(new Button("FOUR"));
gld.add(new Button("FIVE"));
gld.setSize(200, 200);
gld.setVisible(true);
}
}

This is the output of the program. Observe the effect of resizing the frame.

Figure 5. Output of sample code

juliomcervantes 169
Object-Oriented Programming

Panels and Complex Layouts


To create more complex layouts, you can combine the different layout managers with the
use of panels. Remember that a Panel is a Container and a Component at the same time. You
can insert Components into the Panel and then add the Panel to a specified region in the
Container.

Observe the technique used in the following example.

import java.awt.*;

class ComplexLayout extends Frame {


public static void main(String args[]) {
ComplexLayout cl = new ComplexLayout();
Panel panelNorth = new Panel();
Panel panelCenter = new Panel();
Panel panelSouth = new Panel();
/* North Panel */
//Panels use FlowLayout by default
panelNorth.add(new Button("ONE"));
panelNorth.add(new Button("TWO"));
panelNorth.add(new Button("THREE"));
/* Center Panel */
panelCenter.setLayout(new GridLayout(4,4));
panelCenter.add(new TextField("1st"));
panelCenter.add(new TextField("2nd"));
panelCenter.add(new TextField("3rd"));
panelCenter.add(new TextField("4th"));
/* South Panel */
panelSouth.setLayout(new BorderLayout());
panelSouth.add(new Checkbox("Choose me!"), BorderLayout.CENTER);
panelSouth.add(new Checkbox("I'm here!"), BorderLayout.EAST);
panelSouth.add(new Checkbox("Pick me!"), BorderLayout.WEST);
/* Adding the Panels to the Frame container */
//Frames use BorderLayout by default
cl.add(panelNorth, BorderLayout.NORTH);
cl.add(panelCenter, BorderLayout.CENTER);
cl.add(panelSouth, BorderLayout.SOUTH);
cl.setSize(300,300);
cl.setVisible(true);
}
}

juliomcervantes 170
Object-Oriented Programming

Here is the output of the program.

Figure 6. Output of sample code

Swing GUI Components


Like the AWT package, the Swing package provides classes for creating GUI applications. The
package is found in javax.swing. The main difference between these two is that Swing
components are written entirely using Java whereas the latter is not. As a result, GUI
programs written using classes from the Swing package have the same look and feel even
when executed on different platforms. Moreover, Swing provides more interesting
components such as the color chooser and the option pane.

The names of the Swing GUI components are almost similar to that of the AWT GUI
components. An obvious difference is in the naming conventions of the components.
Basically, the name of Swing components are just the name of AWT components but with an
additional prefix of J. For example, one component in AWT is the Button class. The
corresponding component for this in the Swing package is the JButton class. Provided below
is the list of some of the Swing GUI components.

Swing Component Description


JComponent The root class for all Swing components, excluding top-level
containers.
JButton A "push" button. Corresponds to the Button class in the AWT package.
JCheckBox An item that can be selected or deselected by the user. Corresponds to
the Checkbox class in the AWT package.

juliomcervantes 171
Object-Oriented Programming

Swing Component Description


JFileChooser Allows user to select a file. Corresponds to the FileChooser class in the
AWT package.
JTextField Allows for editing of a single-line text. Corresponds to TextField
class in the AWT package.
JFrame Extends and corresponds to the Frame class in the AWT package
but the two are slightly incompatible in terms of adding components
to this container. Need to get the current content pane before
adding a component.
JPanel Extends JComponent. A simple container class but not top-level.
Corresponds to Panel class in the AWT package.
JApplet Extends and corresponds to the Applet class in the AWT package.
Also slightly incompatible with the Applet class in terms of adding
components to this container.
JOptionPane Extends JComponent. Provides an easy way of displaying pop-up
dialog box.
JDialog Extends and corresponds to the Dialog class in the AWT package.
Usually used to inform the user of something or prompt the user for
an input.
JColorChooser Extends JComponent. Allow the user to select a color.

Table 7. Some Swing components

For the complete list of Swing components, please refer to the API documentation.

Setting Up Top-Level Containers


As mentioned, the top-level containers like JFrame and JApplet in Swing are slightly
incompatible with those in AWT. This is in terms of adding components to the container.
Instead of directly adding a component to the container as in AWT containers, you have to
first get the content pane of the container. To do this, you'll have to use the getContentPane
method of the container.

A JFrame Example

import javax.swing.*;
import java.awt.*;

class SwingDemo {
JFrame frame;
JPanel panel;
JTextField textField;
JButton button;
Container contentPane;

juliomcervantes 172
Object-Oriented Programming

void launchFrame() {
/* initialization */
frame = new JFrame("My First Swing Application");
panel = new JPanel();
textField = new JTextField("Default text");
button = new JButton("Click me!");
contentPane = frame.getContentPane();
/* add components to panel– uses FlowLayout by default */
panel.add(textField);
panel.add(button);
/* add components to contentPane– uses BorderLayout */
contentPane.add(panel, BorderLayout.CENTER);
frame.pack();
//causes size of frame to be based on the components
frame.setVisible(true);
}
public static void main(String args[]) {
SwingDemo sd = new SwingDemo();
sd.launchFrame();
}
}

Note that the java.awt package is still imported because the layout managers in use are
defined in this package. Also, giving a title to the frame and packing the components within
the frame is applicable for AWT frames too.

Coding Guidelines:
Observe the coding style applied in this example as opposed to the examples for AWT. The
components are declared as fields, a launchFrame method is defined, and initialization and
addition of components are all done in the launchFrame method. We no longer just extend
the Frame class. The advantage of using this style would become apparent when we get to
event handling.

Here is a sample output.

Figure 7. Output of sample code

juliomcervantes 173
Object-Oriented Programming

A JOptionPane Example

import javax.swing.*;

class JOptionPaneDemo {
JOptionPane optionPane;
void launchFrame() {
optionPane = new JOptionPane();
String name = optionPane.showInputDialog("Hi,what's your name?");
optionPane.showMessageDialog(null,
"Nice to meet you, " + name + ".", "Greeting...",
optionPane.PLAIN_MESSAGE);
System.exit(0);
}
public static void main(String args[]) {
new JOptionPaneDemo().launchFrame();
}
}

See how easy it is ask input from the user.


Here is the sample output for the given program.

Figure 8. Output of sample code

juliomcervantes 174
Object-Oriented Programming

Lesson No. 8

INHERITANCE, POLYMORPHISM
AND INTERFACES

What is the lesson all about?

In this lesson, we will be discussing the different types of inheritance and on how a class
can inherit the properties of an existing class. A class that does this is called a subclass
and its parent class is called the superclass. We will also be discussing a special property
of Java wherein it can automatically apply the proper methods to each object regardless
of what subclass the object came from. This property is known as polymorphism. Finally,
we are going to discuss about interfaces that helps reduce programming effort.

What do you expect from the lesson?

At the end of the lesson, the student should be able to:

• Learn about the concept of inheritance


• Define super classes and subclasses
• Override methods of superclasses
• Create final methods and final classes

What are the contents of the lesson?

Inheritance
Inheritance in object-oriented programming is very similar to the way we inherit
characteristics from our parents. Characteristics in object-oriented programming terms are
attributes and behaviors of a class—that is, the data and methods of a class.

Biological inheritance creates a hierarchical classification that enables you to trace your
heritage to generations of relatives who have come before you. The same is true in object-

juliomcervantes 139
Object-Oriented Programming

oriented programming. A hierarchical relationship develops as classes inherit from other


classes within a program. You can trace this relationship to determine the origins of a class.
Inheritance is a cornerstone of object-oriented programming because it enables objects to
inherit attributes and behaviors from other objects, thereby reducing the amount of new
code that must be designed, written, and tested each time a new program is developed.

The Class Hierarchy


The hierarchical relationship between classes is sometimes referred to as a parent-child
relationship. In a parent-child relationship, the child inherits all attributes and behaviors of
the parent, and it uses the parent’s access specifier to control how those inherited items are
available to other classes or functions.

In C++, the parent is referred to as a base class, and the child is called a derived class. In Java,
the parent is the super class, and the child is the subclass. Regardless of the terms, the
relationship and functionality of a parent class and child class are the same.

Defining a parent-child relationship is intuitive in many situations. For example, it is easy to


see how a student is the parent of a graduate student because a graduate student has the
same attributes and behaviors of a student, and then some. However, sometimes this
relationship is illusive because the relationship isn’t clear—and maybe it doesn’t exist at all.

Programmers use the “is a” test to determine if a relationship exists between classes. The “is
a” test determines if the child “is a” parent. For example, a graduate student “is a” student. If
an “is a” relationship makes sense, then a parent-child relationship exists and the child can
inherit from the parent. If an “is a” relationship doesn’t make sense, then a parent-child
relationship doesn’t exist and the child cannot inherit from the parent, as in the case of an
automobile and airplane. An automobile “is a(n)” airplane? This is nonsense, so you shouldn’t
attempt to create such a relationship.

Types of Inheritance
You have three ways to implement inheritance in a program: simple inheritance, multiple
inheritance, and level inheritance. Each enables a class to access attributes and behaviors of
another class using slightly different techniques.

1. Simple
Simple inheritance occurs when there is one parent-child relationship. That is, one child
inherits from one parent. Simple inheritance is shown in Figure 1. Two classes are represented
in this diagram. These are the Student class and the GradStudent class. The Student
class is the parent in this relationship and is inherited by the GradStudent class, which is
the child.

juliomcervantes 140
Object-Oriented Programming

Student
ID
First name
Last Name
Graduation
Write()
Display()

Inheritance
GradStudent
Under grad major
Under grad school
Year graduated
Write()
Display()
Figure 1: Simple inheritance consists of one parent-child relationship. Here, the Student
class is the parent and the GradStudent class is the child.

Inheritance occurs from the parent to the child. A parent class cannot access attributes and
behavior of a child class. In Figure 1, the Student class cannot call the Write() and
Display() members of the GradStudent class. However, the GradStudent class can
call the Student class’s versions of these members.

2. Multiple
Multiple inheritance occurs when the relationship involves multiple parents and a child. In
other words, the child inherits from more than one parent. This is shown in Figure 2. In this
example, the GradStudent class inherits from both the Person class and the Student class. The
Person class and the Student class are both parents to the GradStudent class, which is the
child in this relationship.

Student
Person
ID
Weight
First name
Height
Last Name
Sex
Graduation
Walk()
Write()
Sit()
Display()

Inheritance
GradStudent
Under grad major
Under grad school
Year graduated
Write()
Display()

Figure 2: Multiple inheritance occurs when one class inherits from two other classes.

juliomcervantes 141
Object-Oriented Programming

The GradStudent class inherits the characteristics of a person from the Person class.
These are the weight, height, and sex attributes and the Walk() and Sit() methods. You
might be wondering how a graduate student walks and sits inside a program. It is difficult to
image how this is done. Although we use them in this lesson for illustrative purposes, these
behaviors could be programmed into a virtual reality application that shows an animated
graduate student walking across campus to a class.

You must keep several factors in mind when implementing multiple inheritance:

• Each class that is inherited must pass the “is a” test. In Figure 2, the graduate student
must be a student and a person in order to inherit from both parents. If the graduate
student fails this test, it cannot inherit from the corresponding parent.
• Parent classes are independent of each other. That is, the Student class has no
knowledge of the Person class, and vice versa. The Student class cannot access
attributes and behaviors of the Person class because only the GradStudent class
inherits from the Person class. Likewise, the Person class does not inherit from the
Student class.
• Inheritance occurs in one direction from the parent to the child, which is identical to
simple inheritance.
• Any number of parent classes can be inherited by a child class as long as they pass the
“is a” test.

3. Level Inheritance
Level inheritance happens when a child inherits from a parent and then becomes a parent
itself to a child. This might sound a little confusing, but it becomes clear by looking at Figure
3, which rearranges the Person class, Student class, and GradStudent class into a level
inheritance.
Person
Weight
Height
Sex
Walk()
Sit()
Inheritance
Student
ID
First name
Last Name
Graduation
Write()
Display()

Inheritance
GradStudent
Under grad major
Under grad school
Year graduated
Write()
Display()
Figure 3: Level inheritance occurs when each class inherits one other class as shown here.

juliomcervantes 142
Object-Oriented Programming

The Person class is a parent class that is inherited by the Student class. The Student
class is a child class in the Person class–Student class relationship. However, another
parent-child relationship exists when the GradStudent class inherits the Student class.
In this relationship, the Student class is the parent class, and the GradStudent class is
the child class. This means that the Student class has a duel role in inheritance. It is both a
child and a parent.

Each parent-child relationship is considered a level. That is, the Person class–Student
class relationship is the first level, and the Student class– GradStudent class is the
second level. You can have as many levels as required by your program; however, many
programmers stop at three levels because it becomes a bit unwieldy to manage beyond three
levels.

In level inheritance, the final child class, which is the GradStudent class in the previous
example, inherits attributes and behaviors for all classes in the level chain. Here’s how this
works: The Student class inherits attributes and behaviors from the Person class. Once
inherited, these attributes and behaviors are considered members of the Student class, just
as if they were defined in the Student class. When the GradStudent class inherits from
the Student class, the GradStudent class has access to the Student class’s attributes
and behavior that now include those inherited from the Person class. As you’ll remember,
only attributes and behaviors designated as public or protected are inherited.

Although the last child class (that is, the GradStudent class) doesn’t directly inherit from
the Person class, the Person class still must pass the “is a” test. That is, a graduate student
“is a” person.

There is an important difference between multiple inheritance and level inheritance. In


multiple inheritance, parent classes are independent of each other. In level inheritance, a
parent class that is also a child class (that is, the Student class) can access other parent
classes within the leveling chain.

Defining Superclasses and Subclasses

To derive a class, we use the extends keyword. In order to illustrate this, let's create a
sample parent class. Suppose we have a parent class called Person.

public class Person


{
protected String name;
protected String address;

/**
* Default constructor
*/
public Person(){
System.out.println(“Inside Person:Constructor”);
name = "";

juliomcervantes 143
Object-Oriented Programming

address = "";
}

/**
* Constructor with 2 parameters
*/
public Person( String name, String address ){
this.name = name;
this.address = address;
}

/**
* Accessor methods
*/
public String getName(){
return name;
}

public String getAddress(){


return address;
}

public void setName( String name ){


this.name = name;
}

public void setAddress( String add ){


this.address = add;
}

Notice that, the attributes name and address are declared as protected. The reason we did
this is that, we want these attributes to be accessible by the subclasses of the superclass. If
we declare this as private, the subclasses won't be able to use them. Take note that all the
properties of a superclass that are declared as public, protected and default can be accessed
by its subclasses.

Now, we want to create another class named Student. Since a student is also a person,
we decide to just extend the class Person, so that we can inherit all the properties and
methods of the existing class Person. To do this, we write,

public class Student extends Person


{
public Student(){
System.out.println(“Inside Student:Constructor”);
//some code here
}

// some code here


}

When a Student object is instantiated, the default constructor of its superclass is invoked
implicitly to do the necessary initializations. After that, the statements inside the subclass are

juliomcervantes 144
Object-Oriented Programming

executed. To illustrate this, consider the following code,

public static void main( String[] args ){


Student anna = new Student();
}

In the code, we create an object of class Student. The output of the program is,

Inside Person:Constructor
Inside Student:Constructor

The program flow is shown below.

Figure 1: Program Flow

juliomcervantes 145
Object-Oriented Programming

The super keyword


A subclass can also explicitly call a constructor of its immediate superclass. This is done by
using the super constructor call. A super constructor call in the constructor of a subclass will
result in the execution of relevant constructor from the superclass, based on the arguments
passed.

For example, given our previous example classes Person and Student, we show an example
of a super constructor call. Given the following code for Student,

public Student(){
super( "SomeName", "SomeAddress" );
System.out.println("Inside Student:Constructor");

This code calls the second constructor of its immediate superclass (which is Person) and
executes it. Another sample code shown below,

public Student(){
super();
System.out.println("Inside Student:Constructor");

This code calls the default constructor of its immediate superclass (which is Person) and
executes it.

There are a few things to remember when using the super constructor call:

1. The super() call MUST OCCUR THE FIRST STATEMENT IN A CONSTRUCTOR.


2. The super() call can only be used in a constructor definition.
3. This implies that the this() construct and the super() calls CANNOT BOTH OCCUR IN THE
SAME CONSTRUCTOR.

Another use of super is to refer to members of the superclass (just like the this reference ).
For example,

public Student()
{
super.name = “somename”;
super.address = “some address”;
}

juliomcervantes 146
Object-Oriented Programming

Overriding Methods
If for some reason a derived class needs to have a different implementation of a certain
method from that of the superclass, overriding methods could prove to be very useful. A
subclass can override a method defined in its superclass by providing a new implementation
for that method.

Suppose we have the following implementation for the getName method in the Person
superclass,

public class Person


{
:
:
public String getName(){
System.out.println("Parent: getName");
return name;
}
:
}

To override, the getName method in the subclass Student, we write,

public class Student extends Person


{
:
:
public String getName(){
System.out.println("Student: getName");
return name;
}
:
}

So, when we invoke the getName method of an object of class Student, the overridden
method would be called, and the output would be,

Student: getName

juliomcervantes 147
Object-Oriented Programming

Final Methods and Final Classes


In Java, it is also possible to declare classes that can no longer be subclassed. These classes
are called final classes. To declare a class to be final, we just add the final keyword in the class
declaration. For example, if we want the class Person to be declared final, we write,

public final class Person


{
//some code here
}

Many of the classes in the Java API are declared final to ensure that their behavior cannot be
overridden. Examples of these classes are Integer, Double and String.

It is also possible in Java to create methods that cannot be overridden. These methods are
what we call final methods. To declare a method to be final, we just add the final keyword in
the method declaration. For example, if we want the getName method in class Person to be
declared final, we write,

public final String getName(){


return name;
}
Static methods are automatically final. This means that you cannot override them.

Polymorphism

Now, given the parent class Person and the subclass Student of our previous example, we add
another subclass of Person which is Employee. Below is the class hierarchy for that,

Person

Student Employee

Figure 2: Hierarchy for Person class and it's classes

In Java, we can create a reference that is of type superclass to an object of its subclass. For
example,

public static main( String[] args )


{
Person ref;

Student studentObject = new Student();


Employee employeeObject = new Employee();

ref = studentObject; //Person ref points to a


// Student object

juliomcervantes 148
Object-Oriented Programming

//some code here


}

Now suppose we have a getName method in our superclass Person, and we override this
method in both the subclasses Student and Employee,

public class Person


{
public String getName(){
System.out.println(“Person Name:” + name);
return name;
}
}

public class Student extends Person


{
public String getName(){
System.out.println(“Student Name:” + name);
return name;
}
}

public class Employee extends Person


{
public String getName(){
System.out.println(“Employee Name:” + name);
return name;
}
}

Going back to our main method, when we try to call the getName method of the reference
Person ref, the getName method of the Student object will be called. Now, if we assign ref to
an Employee object, the getName method of Employee will be called.

public static main( String[] args )


{
Person ref;

Student studentObject = new Student();


Employee employeeObject = new Employee();

ref = studentObject; //Person reference points to a


// Student object
String temp = ref.getName(); //getName of Student
//class is called
System.out.println( temp );

ref = employeeObject; //Person reference points to an


// Employee object

String temp = ref.getName(); //getName of Employee

juliomcervantes 149
Object-Oriented Programming

//class is called
System.out.println( temp );
}

This ability of our reference to change behavior according to what object it is holding is called
polymorphism. Polymorphism allows multiple objects of different subclasses to be treated as
objects of a single superclass, while automatically selecting the proper methods to apply to a
particular object based on the subclass it belongs to.

Another example that exhibits the property of polymorphism is when we try to pass a
reference to methods. Suppose we have a static method printInformation that takes in a
Person object as reference, we can actually pass a reference of type Employee and type
Student to this method as long as it is a subclass of the class Person.

public static main( String[] args )


{
Student studentObject = new Student();
Employee employeeObject = new Employee();

printInformation( studentObject );

printInformation( employeeObject );
}

public static printInformation( Person p ){


. . . .
}

Abstract Classes

Now suppose we want to create a superclass wherein it has certain methods in it that contains
some implementation, and some methods wherein we just want to be overridden by its
subclasses.

For example, we want to create a superclass named LivingThing. This class has certain
methods like breath, eat, sleep and walk. However, there are some methods in this superclass
wherein we cannot generalize the behavior. Take for example, the walk method. Not all living
things walk the same way. Take the humans for instance, we humans walk on two legs, while
other living things like dogs walk on four legs. However, there are many characteristics that
living things have in common, that is why we want to create a general superclass for this.

Figure 4: Abstract class

juliomcervantes 150
Object-Oriented Programming

In order to do this, we can create a superclass that has some methods with implementations
and others which do not. This kind of class is called an abstract class.

An abstract class is a class that cannot be instantiated. It often appears at the top of an object-
oriented programming class hierarchy, defining the broad types of actions possible with
objects of all subclasses of the class.

Those methods in the abstract classes that do not have implementation are called abstract
methods. To create an abstract method, just write the method declaration without the body
and use the abstract keyword. For example,

public abstract void someMethod();

Now, let's create an example abstract class.

public abstract class LivingThing


{
public void breath(){
System.out.println("Living Thing breathing...");
}

public void eat(){


System.out.println("Living Thing eating...");
}

/**
* abstract method walk
* We want this method to be overridden by subclasses of
* LivingThing
*/
public abstract void walk();
}

When a class extends the LivingThing abstract class, it is required to override the abstract
method walk(), or else, that subclass will also become an abstract class, and therefore cannot
be instantiated. For example,

public class Human extends LivingThing


{
public void walk(){
System.out.println("Human walks...");
}
}

If the class Human does not override the walk method, we would encounter the following
error message,

Human.java:1: Human is not abstract and does not override


abstract method walk() in LivingThing
public class Human extends LivingThing
^
1 error

juliomcervantes 151
Object-Oriented Programming

Coding Guidelines:

Use abstract classes to define broad types of behaviors at the top of an object-oriented
programming class hierarchy, and use its subclasses to provide implementation details of
the abstract class.

Interfaces

An interface is a special kind of block containing method signatures (and possibly constants)
only. Interfaces define the signatures of a set of methods without the body.

Interfaces define a standard and public way of specifying the behavior of classes. They allow
classes, regardless of their location in the class hierarchy, to implement common behaviors.
Note that interfaces exhibit polymorphism as well, since program may call an interface
method and the proper version of that method will be executed depending on the type of
object passed to the interface method call.

Why do we use Interfaces?


We need to use interfaces if we want unrelated classes to implement similar methods. Thru
interfaces, we can actually capture similarities among unrelated classes without artificially
forcing a class relationship.

Let's take as an example a class Line which contains methods that computes the length of the
line and compares a Line object to objects of the same class. Now, suppose we have another
class MyInteger which contains methods that compares a MyInteger object to objects of the
same class. As we can see here, both of the classes have some similar methods which
compares them from other objects of the same type, but they are not related whatsoever. In
order to enforce a way to make sure that these two classes implement some methods with
similar signatures, we can use an interface for this. We can create an interface class, let's say
interface Relation which has some comparison method declarations. Our interface Relation
can be declared as,

public interface Relation


{
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}

Another reason for using an object's programming interface is to reveal an object's


programming interface without revealing its class. As we can see later on the section Interface
vs. Classes, we can actually use an interface as data type.

Finally, we need to use interfaces to model multiple inheritance which allows a class to have
more than one superclass. Multiple inheritance is not present in Java, but present in other
object-oriented languages like C++.

juliomcervantes 152
Object-Oriented Programming

Interface vs. Abstract Class


The following are the main differences between an interface and an abstract class: interface
methods have no body, an interface can only define constants and an interface have no direct
inherited relationship with any particular class, they are defined independently.

Interface vs. Class


One common characteristic of an interface and class is that they are both types. This means
that an interface can be used in places where a class can be used. For example, given a class
Person and an interface PersonInterface, the following declarations are valid:

PersonInterface pi = new Person();


Person pc = new Person();

However, you cannot create an instance from an interface. An example of this is:

PersonInterface pi = new PersonInterface(); //COMPILE


//ERROR!!!

Another common characteristic is that both interface and class can define methods. However,
an interface does not have an implementation code while the class have one.

Creating Interfaces
To create an interface, we write,

public interface [InterfaceName]


{
//some methods without the body
}

As an example, let's create an interface that defines relationships between two objects
according to the “natural order” of the objects .

public interface Relation


{
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}

Now, to use the interface, we use the implements keyword. For example,

/**
* This class defines a line segment
*/
public class Line implements Relation
{
private double x1;
private double x2;
private double y1;

juliomcervantes 153
Object-Oriented Programming

private double y2;

public Line(double x1, double x2, double y1, double y2){


this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}

public double getLength(){


double length = Math.sqrt((x2-x1)*(x2-x1) +
(y2-y1)* (y2-y1));
return length;
}

public boolean isGreater( Object a, Object b){


double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen > bLen);
}

public boolean isLess( Object a, Object b){


double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen < bLen);

public boolean isEqual( Object a, Object b){


double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen == bLen);
}
}

When your class tries to implement an interface, always make sure that you implement all
the methods of that interface, or else, you would encounter this error,
Line.java:4: Line is not abstract and does not override
abstract method isGreater(java.lang.Object,java.lang.Object) in
Relation
public class Line implements Relation
^
1 error

Coding Guidelines:

Use interfaces to create the same standard method definitions in may different classes.
Once a set of standard method definition is created, you can write a single method to
manipulate all of the classes that implement the interface.

juliomcervantes 154
Object-Oriented Programming

Relationship of an Interface to a Class


As we have seen in the previous section, a class can implement an interface as long as it
provides the implementation code for all the methods defined in the interface.

Another thing to note about the relationship of interfaces to classes is that, a class can only
EXTEND ONE super class, but it can IMPLEMENT MANY interfaces. An example of a class that
implements many interfaces is,

public class Person implements PersonInterface,


LivingThing,
WhateverInterface {

//some code here


}

Another example of a class that extends one super class and implements an interface is,

public class ComputerScienceStudent extends Student


implements PersonInterface,
LivingThing {

//some code here


}

Take note that an interface is not part of the class inheritance hierarchy. Unrelated classes
can implement the same interface.

Inheritance among Interfaces


Interfaces are not part of the class hierarchy. However, interfaces can have inheritance
relationship among themselves. For example, suppose we have two interfaces
StudentInterface and PersonInterface. If StudentInterface extends PersonInterface, it will
inherit all of the method declarations in PersonInterface.

public interface PersonInterface {


. . .
}

public interface StudentInterface extends PersonInterface


{
. . .
}

juliomcervantes 155
J.E.D.I.

Introduction to
Java Programming
Student’s Manual

Author
Florence Tiu Balagtas

Team
Joyce Avestro
Florence Balagtas
Rommel Feria
Reginald Hutcherson
Rebecca Ong
John Paul Petines
Sang Shin
Raghavan Srinivas
Matthew Thompson

Introduction to Java Programming 1


J.E.D.I.

Table of Contents

User-Defined Classes
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Defining Your Own Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Declaring Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Instance Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Class Variables and Static Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Declaring Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Accessor Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Mutator Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Multiple Return Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Static Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Sample Source Code for StudentRecord Class . . . . . . . . . . . . . . . . . . . . . . 10
The this Reference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Overloading Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Declaring Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Default Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Overloading Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Using Constructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
The this() Constructor Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Importing Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Creating Your Own Packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Setting the CLASSPATH. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Access Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
default access (also called package accessibility). . . . . . . . . . . . . . . . . . . . 18
public access. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
protected access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
private access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
True or False. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Address Book Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
AddressBook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

Introduction to Java Programming 2


J.E.D.I.

User-Defined Classes
Objectives

Now that we've studied on how to use existing classes from the Java class library, we will now
be studying on how to write our own classes. For this section, in order to easily understand
how to create classes, we will make a sample class wherein we will add more data and
functionality as we go along the way.

We will create a class that contains information of a Student and operations needed for a
certain student record.

Things to take note of for the syntax defined in this section and for the other sections:

* - means that there may be 0 or more occurrences of the line


where it was applied to.
<description> - indicates that you have to substitute an actual value for this
part instead of typing it as it is.
[] - indicates that this part is optional

At the end of the lesson, the student should be able to:


• Create their own classes
• Declare attributes and methods for their classes
• Use the this reference to access instance data
• Create and call overloaded methods
• Import and create packages
• Use access modifiers to control access to class members

Defining your own classes

Before writing your class, think first on where you will be using your class and how your class
will be used. Think of an appropriate name for the class, and list all the information or
properties that you want your class to contain. Also list down the methods that you will be
using for your class.

To define a class, we write,

<modifier> class <name> {


<attributeDeclaration>*
<constructorDeclaration>*
<methodDeclaration>*
}

where
<modifier> is an access modifier, which may be combined with other types of modifier.

Coding Guidelines:

Remember that for a top-level class, the only valid access modifiers are public and package
(i.e., if no access modifier prefixes the class keyword).

Introduction to Java Programming 3


J.E.D.I.

In this section, we will be creating a class that will contain a student record. Since we've
already identified the purpose of our class, we can now name it. An appropriate name for our
class would be StudentRecord.

Now, to define our class we write,

public class StudentRecord


{
//we'll add more code here later
}

where,
public - means that our class is accessible to other classes outside the package
class - this is the keyword used to create a class in Java
StudentRecord - a unique identifier that describes our class

Coding Guidelines:

1. Think of an appropriate name for your class. Don't just call your class XYZ or any random
names you can think of.
2. Class names should start with a CAPITAL letter.
3. The filename of your class should have the SAME NAME as your class name.

Declaring Attributes

To declare a certain attribute for our class, we write,

<modifier> <type> <name> [= <default_value>];

Now, let us write down the list of attributes that a student record can contain. For each
information, also list what data types would be appropriate to use. For example, you don't
want to have a data type int for a student's name, or a String for a student's grade.

The following are some sample information we want to add to the student record.

name - String
address - String
age - int
math grade - double
english grade - double
science grade - double
average grade - double

You can add more information if you want to, it's all really up to you. But for this
example, we will be using these information.

Instance Variables

Now that we have a list of all the attributes we want to add to our class, let us now add
them to our code. Since we want these attributes to be unique for each object (or for each
student), we should declare them as instance variables.

Introduction to Java Programming 4


J.E.D.I.

For example,

public class StudentRecord


{
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
//we'll add more code here later
}

where,
private here means that the variables are only accessible within the class. Other objects
cannot access these variables directly. We will cover more about accessibility later.

Coding Guidelines:

1. Declare all your instance variables on the top of the class declaration.
2. Declare one variable for each line.
3. Instance variables, like any other variables should start with a SMALL letter.
4. Use an appropriate data type for each variable you declare.
5. Declare instance variables as private so that only class methods can access them directly.

Class Variables or Static Variables

Aside from instance variables, we can also declare class variables or variables that belong to
the class as a whole. The value of these variables are the same for all the objects of the same
class. Now suppose, we want to know the total number of student records we have for the
whole class, we can declare one static variable that will hold this
value. Let us call this as studentCount.

To declare a static variable,

public class StudentRecord


{
//instance variables we have declared
private static int studentCount;
//we'll add more code here later
}

we use the keyword static to indicate that a variable is a static variable.

Introduction to Java Programming 5


J.E.D.I.

So far, our whole code now looks like this.

public class StudentRecord


{
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
private static int studentCount;
//we'll add more code here later
}

Declaring Methods
Before we discuss what methods we want our class to have, let us first take a look at the
general syntax for declaring methods.

To declare methods we write,

<modifier> <returnType> <name>(<parameter>*) {


<statement>*
}

where,
<modifier> can carry a number of different modifiers
<returnType> can be any data type (including void)
<name> can be any valid identifier
<parameter> ::= <parameter_type> <parameter_name>[,]

Accessor methods

In order to implement encapsulation, that is, we don't want any objects to just access our
data anytime, we declare the fields or attributes of our classes as private. However, there are
times wherein we want other objects to access private data. In order to do this, we create
accessor methods.

Accessor methods are used to read values from class variables (instance/static). An
accessor method usually starts with a get<NameOfInstanceVariable>. It also returns a
value.

For our example, we want an accessor method that can read the name, address, English
grade, math grade and science grade of the student.

Introduction to Java Programming 6


J.E.D.I.

Now let's take a look at one implementation of an accessor method,

public class StudentRecord


{
private String name;
::
public String getName(){
return name;
}
}

where,
public - means that the method can be called from objects outside the class
String - is the return type of the method. This means that the method should
return a value of type String
getName - the name of the method
() - this means that our method does not have any parameters

The statement,
return name;

in our program signifies that it will return the value of the instance variable name to the calling
method. Take note that the return type of the method should have the same data type as the
data in the return statement. You usually encounter the following error if the two does not
have the same data type,

StudentRecord.java:14: incompatible types


Found : int
required: java.lang.String
return age;
^
1 error

Another example of an accessor method is the getAverage method,

public class StudentRecord


{
private String name;
::
public double getAverage(){
double result = 0;
result = ( mathGrade+englishGrade+scienceGrade )/3;
return result;
}
}

The getAverage method computes the average of the 3 grades and returns the result.

Introduction to Java Programming 7


J.E.D.I.

Mutator Methods

Now, what if we want other objects to alter our data? What we do is we provide methods that
can write or change values of our class variables (instance/static). We call these methods,
mutator methods. A mutator method is usually written as
set<NameOfInstanceVariable>.

Now let's take a look at one implementation of a mutator method,

public class StudentRecord


{
private String name;
::
public void setName( String temp ){
name = temp;
}
}

where,
public - means that the method can be called from objects outside the class
void - imeans that the method does not return any value
setName - the name of the method
(String temp) - parameter that will be used inside our method

The statement,

name = temp;

assigns the value of temp to name and thus changes the data inside the instance variable
name.

Take note that mutator methods don't return values. However, it contains some program
argument or arguments that will be used inside the method.

Multiple Return statements

You can have multiple return statements for a method as long as they are not on the same
block. You can also use constants to return values instead of variables.

For example, consider the method,

public String getNumberInWords( int num ){


String defaultNum = "zero";
if( num == 1 ){
return "one"; //return a constant
}
else if( num == 2){
return "two"; //return a constant
}
//return a variable
return defaultNum;
}

Introduction to Java Programming 8


J.E.D.I.

Static methods

For the static variable studentCount, we can create a static method to access its value.

public class StudentRecord


{
private static int studentCount;
public static int getStudentCount(){
return studentCount;
}
}

where,
public - means that the method can be called from objects outside the class
static - means that the method is static and should be called by
typing,[ClassName].[methodName]. For example, in this case, we call the
method StudentRecord.getStudentCount()
int - is the return type of the method. This means that the method should return
a value of type int
getStudentCount - the name of the method
() - this means that our method does not have any parameters

For now, getStudentCount will always return the value zero since we haven't done anything
yet in our program in order to set its value. We will try to change the value of studentCount
later on when we discuss constructors.

Coding Guidelines:

1. Method names should start with a SMALL letter.


2. Method names should be verbs
3. Always provide documentation before the declaration of the method. You can use javadocs
style for this. Please see example.

Introduction to Java Programming 9


J.E.D.I.

Sample Source Code for StudentRecord class

Here is the code for our StudentRecord class,

public class StudentRecord


{
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;

private static int studentCount;

/**
* Returns the name of the student
*/
public String getName(){
return name;
}

/**
* Changes the name of the student
*/
public void setName( String temp ){
name = temp;
}

// other code here ....


/**
* Computes the average of the english, math and science
* grades
*/
public double getAverage(){
double result = 0;
result = ( mathGrade+englishGrade+scienceGrade )/3;
return result;
}

/**
* returns the number of instances of StudentRecords
*/
public static int getStudentCount(){
return studentCount;
}
}

Introduction to Java Programming 10


J.E.D.I.

Now, here's a sample code of a class that uses our StudentRecord class.

public class StudentRecordExample


{
public static void main( String[] args ){

//create three objects for Student record


StudentRecord annaRecord = new StudentRecord();
StudentRecord beahRecord = new StudentRecord();
StudentRecord crisRecord = new StudentRecord();

//set the name of the students


annaRecord.setName("Anna");
beahRecord.setName("Beah");
crisRecord.setName("Cris");

//print anna's name


System.out.println( annaRecord.getName() );

//print number of students


System.out.println("Count="+StudentRecord.getStudentCount());
}
}

The output of this program is,

Anna
Student Count = 0

The this reference

The this reference is used to access the instance variables shadowed by the parameters. To
understand this better, let's take for example the setAge method. Suppose we have the
following declaration for setAge.

public void setAge( int age ){


age = age; //WRONG!!!
}

The parameter name in this declaration is age, which has the same name as the instance
variable age. Since the parameter age is the closest declaration to the method, the value of
the parameter age will be used. So in the statement,

age = age;

we are just assigning the value of the parameter age to itself! This is not what we want to
happen in our code. In order to correct this mistake, we use the this reference. To use the
this reference, we type,

this.<nameOfTheInstanceVariable>

Introduction to Java Programming 11


J.E.D.I.

So for example, we can now rewrite our code to,

public void setAge( int age ){


this.age = age;
}

This method will then assign the value of the parameter age to the instance variable of the
object StudentRecord.

NOTE: You can only use the this reference for instance variables and NOT static
or class variables

Overloading Methods

In our classes, we want to sometimes create methods that has the same names but function
differently depending on the parameters that are passed to them. This capability is possible
in Java, and it is called Method Overloading.

Method overloading allows a method with the same name but different parameters, to have
different implementations and return values of different types. Rather than invent new names
all the time, method overloading can be used when the same operation has different
implementations.

For example, in our StudentRecord class we want to have a method that prints information
about the student. However, we want the print method to print things differently depending
on the parameters we pass to it. For example, when we pass a String, we want the print
method to print out the name, address and age of the student. When we pass 3 double values,
we want the method to print the student's name and grades.

We have the following overloaded methods inside our StudentRecord class,

public void print( String temp ){


System.out.println("Name:" + name);
System.out.println("Address:" + address);
System.out.println("Age:" + age);
}

public void print(double eGrade, double mGrade, double sGrade){


System.out.println("Name:" + name);
System.out.println("Math Grade:" + mGrade);
System.out.println("English Grade:" + eGrade);
System.out.println("Science Grade:" + sGrade);
}

Introduction to Java Programming 12


J.E.D.I.

When we try to call this in the following main method,

public static void main( String[] args )


{
StudentRecord annaRecord = new StudentRecord();
annaRecord.setName("Anna");
annaRecord.setAddress("Philippines");
annaRecord.setAge(15);
annaRecord.setMathGrade(80);
annaRecord.setEnglishGrade(95.5);
annaRecord.setScienceGrade(100);
//overloaded methods
annaRecord.print( annaRecord.getName() );
annaRecord.print( annaRecord.getEnglishGrade(),
annaRecord.getMathGrade(),
annaRecord.getScienceGrade());
}

we will have the output for the first call to print,

Name:Anna
Address:Philippines
Age:15

we will have the output for the second call to print,

Name:Anna
Math Grade:80.0
English Grade:95.5
Science Grade:100.0

Always remember that overloaded methods have the following properties,


– the same name
– different parameters
– return types can be different or the same

Declaring Constructors

We have discussed before the concept of constructors. Constructors are important in


instantiating an object. It is a method where all the initializations are placed.

The following are the properties of a constructor:


1. Constructors have the same name as the class
2. A constructor is just like an ordinary method, however only the following information
can be placed in the header of the constructor, scope or accessibility identifier (like
public...), constructor's name and parameters if it has any.
3. Constructors does not have any return value
4. You cannot call a constructor directly, it can only be called by using the new
5. operator during class instantiation.

To declare a constructor, we write,


<modifier> <className> (<parameter>*) {
<statement>*
}

Introduction to Java Programming 13


J.E.D.I.

Default Constructor

Every class has a default constructor. The default constructor is the constructor without
any parameters. If the class does not specify any constructors, then an implicit default
constructor is created.

For example, in our StudentRecord class, the default constructor would look like this,

public StudentRecord()
{
//some code here
}

Overloading Constructors

As we have mentioned, constructors can also be overloaded, for example, we have here four
overloaded constructors,

public StudentRecord(){
//some initialization code here
}

public StudentRecord(String temp){


this.name = temp;
}

public StudentRecord(String name, String address){


this.name = name;
this.address = address;
}

public StudentRecord(double mGrade, double eGrade, double sGrade){


mathGrade = mGrade;
englishGrade = eGrade;
scienceGrade = sGrade;
}

Using Constructors

To use these constructors, we have the following code,

public static void main( String[] args )


{
//create three objects for Student record
StudentRecord annaRecord=new StudentRecord("Anna");
StudentRecord beahRecord=new StudentRecord("Beah","Philippines");
StudentRecord crisRecord=new
StudentRecord(80,90,100);
//some code here
}

Now, before we move on, let us go back to the static variable studentCount we have declared
a while ago. The purpose of the studentCount is to count the number of objects that are
instantiated with the class StudentRecord. So, what we want to do here is, everytime an
object of class StudentRecord is instantiated, we increment the value of studentCount. A

Introduction to Java Programming 14


J.E.D.I.

good location to modify and increment the value of studentCount is in the constructors,
because it is always called everytime an object is instantiated. For example,

public StudentRecord(){
//some initialization code here
studentCount++; //add a student
}

public StudentRecord(String temp){


this.name = temp;
studentCount++; //add a student
}

public StudentRecord(String name, String address){


this.name = name;
this.address = address;
studentCount++; //add a student
}

public StudentRecord(double mGrade, double eGrade, double sGrade){


mathGrade = mGrade;
englishGrade = eGrade;
scienceGrade = sGrade;
studentCount++; //add a student
}

The this() Constructor Call

Constructor calls can be chained, meaning, you can call another constructor from inside
another constructor. We use the this() call for this. For example, given the following code,

1: public StudentRecord(){
2: this("some string");
3:
4: }
5:
6: public StudentRecord(String temp){
7: this.name = temp;
8: }
9:
10: public static void main( String[] args )
11: {
12:
13: StudentRecord annaRecord = new StudentRecord();
14: }

Given the code above, when the statement at line 13 is called, it will call the default
constructor line 1. When statement in line 2 is executed, it will then call the constructor that
has a String parameter (in line 6).

There are a few things to remember when using the this constructor call:

1. When using the this constructor call, IT MUST OCCUR AS THE FIRST STATEMENT in a
constructor
2. It can ONLY BE USED IN A CONSTRUCTOR DEFINITION. The this call can then be
followed by any other relevant statements.

Introduction to Java Programming 15


J.E.D.I.

Packages

Packages are Java’s means of grouping related classes and interfaces together in a single unit
(interfaces will be discussed later). This powerful feature provides for a convenient mechanism
for managing a large group of classes and interfaces while avoiding potential naming conflicts.

Importing Packages

To be able to use classes outside of the package you are currently working in, you need to
import the package of those classes. By default, all your Java programs import the java.lang.*
package, that is why you can use classes like String and Integers inside the program even
though you haven't imported any packages.

The syntax for importing packages is as follows,

import <nameOfPackage>;

For example, if you want to use the class Color inside package awt, you have to type the
following,

import java.awt.Color;
import java.awt.*;

The first statement imports the specific class Color while the other imports all of the classes
in the java.awt package.

Another way to import classes from other packages is through explicit package referencing.
This is done by using the package name to declare an object of a class.

java.awt.Color color;

Creating your own packages

To create our own package, we write,

package <packageName>;

Suppose we want to create a package where we will place our StudentRecord class, together
with other related classes. We will call our package, schoolClasses.

The first thing you have to do is create a folder named schoolClasses. Copy all the classes
that you want to belong to this package inside this folder. After copying, add the following
code at the top of the class file. For example,

package schoolClasses;
public class StudentRecord
{
private String name;
private String address;
private int age;
:

Packages can also be nested. In this case, the Java interpreter expects the directory structure
containing the executable classes to match the package hierarchy.
Introduction to Java Programming 16
J.E.D.I.

Setting the CLASSPATH


Now, suppose we place the package schoolClasses under the C:\ directory. We need to set
the classpath to point to that directory so that when we try to run it, the JVM will be able to
see where our classes are stored.

Before we discuss how to set the classpath, let us take a look at an example on what will
happen if we don't set the classpath.

Suppose we compile and then run the StudentRecord class we wrote in the last section,
C:\schoolClasses>javac StudentRecord.java

C:\schoolClasses>java StudentRecord
Exception in thread "main" java.lang.NoClassDefFoundError:
StudentRecord (wrong name: schoolClasses/StudentRecord)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)

We encounter a NoClassDefFoundError which means that Java did not know where to look
for your class. The reason for this is that your class StudentRecord now belongs to a package
named studentClasses. If we want to run our class, we jave to tell Java about its full class
name which is schoolClasses.StudentRecord. We also have to tell JVM where to look for
our packages, which in this case is in location C:\. To do this, we must set the classpath.

To set the classpath in Windows, we type this at the command prompt,


C:\schoolClasses> set classpath=C:\

where C:\ is the directory in which we have placed the packages. After setting the classpath,
we can now run our program anywhere by typing,

C:\schoolClasses> java schoolClasses.StudentRecord

For Unix base systems, suppose we have our classes in the directory
/usr/local/myClasses, we write,
export classpath=/usr/local/myClasses

Take note that you can set the classpath anywhere. You can also set more than one classpath,
we just have to separate them by ;(for windows) and : (for Unix based systems). For example,
set classpath=C:\myClasses;D:\;E:\MyPrograms\Java

and for Unix based systems,


export classpath=/usr/local/java:/usr/myClasses

Introduction to Java Programming 17


J.E.D.I.

Access Modifiers

When creating our classes and defining the properties and methods in our class, we want to
implement some kind of restriction to access these data. For example, if you want a certain
attribute to be changed only by the methods inside the class, you may want to hide this from
other objects using your class. In Java, we have what we call access modifiers in order to
implement this.

There are four different types of member access modifiers in Java: public, private, protected
and default. The first three access modifiers are explicitly written in the code to indicate the
access type, for the fourth one which is default, no keyword is used.

default access (also called package accessibility)

This specifies that only classes in the same package can have access to the class' variables
and methods. There are no actual keyword for the default modifier; it is applied in the absence
of an access modifier. For example,

public class StudentRecord


{
//default access to instance variable
int name;

//default access to method


String getName(){
return name;
}
}

In this example, the instance variable name and the method getName() can be accessed from
other objects, as long as the object belongs to the same package where the class
StudentRecord belongs to.

public access

This specifies that class members are accessible to anyone, both inside and outside the class.
Any object that interacts with the class can have access to the public members of the class.
For example,

public class StudentRecord


{
//default access to instance variable
public int name;

//default access to method


public String getName(){
return name;
}
}

In this example, the instance variable name and the method getName() can be accessed
from other objects.

Introduction to Java Programming 18


J.E.D.I.

protected access

This specifies that the class members are accessible only to methods in that class and the
subclasses of the class. For example,

public class StudentRecord


{
//default access to instance variable
protected int name;

//default access to method


protected String getName(){
return name;
}
}

In this example, the instance variable name and the method getName() can be accessed only
from methods inside the class and from subclasses of StudentRecord. We will discuss about
subclasses on the next chapter.

private access

This specifies that the class members are only accessible by the class they are defined in. For
example,

public class StudentRecord


{
//default access to instance variable
private int name;

//default access to method


private String getName(){
return name;
}
}

In this example, the instance variable name and the method getName() can be accessed only
from methods inside the class.

Coding Guidelines:

The instance variables of a class should normally be declared private, and the class will just
provide accessor and mutator methods to these variables.

Introduction to Java Programming 19


J.E.D.I.

Name: ___________________________________________________________________

Year & Section: _____________________________ Date: _______________________

True or False. Write your answer in the space provided.

_______ 1. Modifiers are used to alter the behavior of the class.

_______ 2. If a member of a class is a private method, it cannot (directly) access any


member of the class.

_______ 3. Members of a class are usually classified into three categories: public, private,
and static.

_______ 4. If a member of a class is public, you cannot access it outside the class.

_______ 5. The methods of a class must be public.

_______ 6. A constructor has the same name as the class.

_______ 7. A class can have only two constructors.

_______ 8. If the object is created in the definition of a method of the class, then the object
can access both the public and private members of the class.

_______ 9. The modifier static in the heading of a method specifies that the method must
be invoked by using the name of the class.

_______ 10. A mutator method of a class changes the values of the data members of the
class.

_______ 11. Every object has access to a reference to itself.

_______ 12. In Java, the reference this is used to refer to only the methods, not the
instance variables of a class.

_______ 13. The default constructor executes when an object is instantiated and initialized
using an existing object.

_______ 14. An accessor method of a class first accesses the values of the data members of
the class and then changes the values of the data members.

_______ 15. A constructor has no type and is therefore a void method.

Introduction to Java Programming 20


J.E.D.I.

Name: ___________________________________________________________________

Year & Section: _____________________________ Date: _______________________

1. Address Book Entry


Your task is to create a class that contains an address book entry. The following table
describes the information that an adressbook entry has.

Attributes/Properties Description
Name Name of the person in the addressbook
Address Address of the person
BirthDate Birthday of the person
Telephone Number Telephone number of the person
Email Address Person's Email address

Table 1: Attributes and Attributes Descriptions


For the methods, create the following:

1. Provide the necessary accessor and mutator methods for all the attributes.
2. Constructors

2. AddressBook

Create a class address book that can contain 100 entries of AddressBookEntry objects (use
the class you created in the first exercise). You should provide the following methods for the
address book.

1. Add entry
2. Delete entry
3. View all entries
4. Update an entry

Introduction to Java Programming 21


J.E.D.I.

References
1. Programming Language. From Wikipedia at
http://en.wikipedia.org/wiki/Programming_language

2. Programming Language. From Webopedia at


http://www.webopedia.com/TERM/p/programming_language.html

3. Programming Language. From Answers.com at


http://www.answers.com/topic/programming-language

4. High-Level Programming Language. From Wikipedia at


http://en.wikipedia.org/wiki/High-level_programming_language

5. Defining Flowchart Symbols. Available at http://www.pattonpatton.


com/basic_flow_chart_symbols.htm

6. Integrated Development Environment. From Webopedia at


http://www.webopedia.com/TERM/I/integrated_development_environment.html

7. Variables and Expressions. Available at


http://www.geocities.com/SiliconValley/Park/3230/java/javl1002.html

8. Writing Abstract Classes and Methods. Available at


http://java.sun.com/docs/books/tutorial/java/javaOO/abstract.html

9. Defining an Interface. Available at


http://java.sun.com/docs/books/tutorial/java/interpack/interfaceDef.html

20.Inheritance and Polymorphism. Available at


http://home.cogeco.ca/~ve3ll/jatutor7.htm

21.The Essence of OOP using Java, Runtime Polymorphism through Inheritance.


Available at http://www.developer.com/tech/article.php/983081

22.Gary B. Shelly, Thomas J. Cashman, Joy L. Starks. Java Programming Complete Concepts
and Techniques. Course Technology Thomson Learning. 2001.

23.Stephen J. Chapman. Java for Engineers and Scientists 2nd Edition. Pearson Prentice Hall. 2004

24.Deitel & Deitel. Java How to Program 5th Edition.

25.Sun Java Programming Student Guide SL-275. Sun Microsystems. February 2001.

26.Does Java pass by reference or pass by value? Why can't you swap in Java? Available at
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

27.Java Branching Statements. Available at


http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html.

28.Encapsulation. Available at http://home.cogeco.ca/~ve3ll/jatutor4.htm.

Introduction to Java Programming 22


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

Module No. 6
MODULE TITLE
OBJECTS AND CLASSES

MODULE OVERVIEW

In this section, we will introduce some basic concepts of object-oriented programming. Later on, we will
discuss the concept of classes and objects, and how to use these classes and their members. Comparison,
conversion and casting of objects will also be covered. For now, we will focus on using classes that are
already defined in the Java class library, we will discuss later on how to create your own classes.

LEARNING OBJECTIVES

At the end of the lesson, the student should be able to:

 Explain object-oriented programming and some of its concepts


 Differentiate between classes and objects
 Differentiate between instance variables/methods and class(static) variables/methods
 Explain what methods are and how to call and pass parameters to methods
 Identify the scope of a variable
 Cast primitive data types and objects
 Compare objects and determine the class of an objects

LEARNING CONTENTS

Introduction to Object-Oriented Programming

Object-Oriented programming or OOP revolves around the concept of objects as the basic elements of your
programs. Comparing this to the physical world, we can find many objects around us, such as cars, lion,
people and so on. These objects are characterized by their properties (or attributes) and behaviors. For
example, a car object has the properties, type of transmission (manual or automatic), manufacturer and color.
Its behaviors are turning, braking and accelerating. Similarly, we can define different properties and behavior
of a lion. Please refer to the table below for the examples.

Object Properties Behavior


Type of transmission Turning
Car Manufacturer Braking
Color Accelerating
Weight Roaring
Lion Color Sleeping
Tamed or Wild Hunting

With these descriptions, the objects in the physical world can easily be modeled as software objects using the

PANGASINAN STATE UNIVERSITY 5


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

properties as data and the behaviors as methods. These data and methods could even be used in
programming games or interactive software to simulate the real-world objects! An example would be a car
software object in a racing game or a lion software object in an educational interactive software zoo for kids.

Classes and Objects


In the software world, an object is a software component whose structure is similar to objects in the real world.
Each object is composed of a set of data (properties/attributes) which are variables describing the essential
characteristics of the object, and it also consists of a set of methods (behavior) that describes how an object
behaves. Thus, an object is a software bundle of variables and related methods. The variables and methods
in a Java object are formally known as instance variables and instance methods to distinguish them from class
variables and class methods, which will be discussed later. The class is the fundamental structure in
object-oriented programming. It can be thought of as a template, a prototype or a blueprint of an object. It
consists of two types of members which are called fields (properties or attributes) and methods. Fields specify
the data types defined by the class, while methods specify the operations. An object is an instance of the class.
To differentiate between classes and objects, let us discuss an example. What we have here is a Car Class
which can be used to define several Car Objects. In the table shown below, Car A and Car B are objects of the
Car class. The class has fields plate number, color, manufacturer, and current speed which are filled-up with
corresponding values in objects Car A and Car B. The Car has also some methods Accelerate, Turn and
Brake.

Car Class Object Car A Object Car B


Plate Number ABC111 XYZ123
Instance Color Blue Red
Variables Manufacturer Mitsubishi Toyota
Current Speed 50 km/h 100km/h
Accelerate Method
Instance
Turn Method
Methods
Brake Method

When instantiated, each object gets a fresh set of state variables. However, the method implementations are
shared among objects of the same class. Classes provide the benefit of reusability. Software programmers
can use a class over and over again to create many objects.

Encapsulation
Encapsulation is the method of hiding certain elements of the implementation of a certain class. By placing a
boundary around the properties and methods of our objects, we can prevent our programs from having side
effects wherein programs have their variables changed in unexpected ways. We can prevent access to our
object's data by declaring them declaring them in a certain way such that we can control access to them. We

PANGASINAN STATE UNIVERSITY 6


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

will learn more about how Java implements encapsulation as we discuss more about classes.

Class Variables and Methods


In addition to the instance variables, it is also possible to define class variables, which are variables that
belong to the whole class. This means that it has the same value for all the objects in the same class. They are
also called static member variables. To clearly describe class variables, let's go back to our Car class
example. Suppose that our Car class has one class variable called Count. If we change the value of Count to
2, all of the objects of the Car class will have the value 2 for their Count variable.

Car Class Object Car A Object Car B


Plate Number ABC111 XYZ123
Instance Color Blue Red
Variables Manufacturer Mitsubishi Toyota
Current Speed 50 km/h 100km/h
Class
Count = 2
Variable
Accelerate Method
Instance
Turn Method
Methods
Brake Method

Class Instantiation
To create an object or an instance of a class, we use the new operator. For example, if you want to create an
instance of the class String, we write the following code,

String str2 = new String(“Hello world!”);

or also equivalent to,

String str2 = "Hello";

The new operator allocates a memory for that object and returns a reference of that memory location to you.
When you create an object, you actually invoke the class' constructor. The constructor is a method where you
place all the initializations, it has the same name as the class.

Methods
What are Methods and Why Use Methods?
In the examples we discussed before, we only have one method, and that is the main() method. In Java, we
can define many methods which we can call from different methods. A method is a separate piece of code that
can be called by a main program or any other method to perform some specific function. The following are
characteristics of methods:
 It can return one or no values

PANGASINAN STATE UNIVERSITY 7


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

 It may accept as many parameters it needs or no parameter at all. Parameters are also called function
arguments.
 After the method has finished execution, it goes back to the method that called it. Now, why do we
need to create methods? Why don't we just place all the code inside one big method? The heart of
effective problem solving is in problem decomposition. We can do this in Java by creating methods to
solve a specific part of the problem. Taking a problem and breaking it into small, manageable pieces
is critical to writing large programs.

Calling Instance Methods and Passing Variables


Now, to illustrate how to call methods, let's use the String class as an example. You can use the Java API
documentation to see all the available methods in the String class. Later on, we will create our own methods,
but for now, let us use what is available.

To call an instance method, we write the following,

nameOfObject.nameOfMethod( parameters );

Let's take two sample methods found in the class String,

Method declaration Definition


public char charAt (int index) Returns the character at the specified index. An
index ranges from 0 to length() - 1. The first
character of the sequence is at index 0, the next at
index 1, and so on, as for array indexing.
public boolean equalsIgnoreCase (String Compares this String to another String, ignoring
anotherString) case considerations. Two strings are considered
equal ignoring case if they are of the same length,
and corresponding characters in the two strings are
equal ignoring case.

Using the methods,

String str1 = "Hello";

char x = str2.charAt(0);
//will return the character H
//and store it to variable x

String str2 = "hello";

//this will return a boolean value true


boolean result = str1.equalsIgnoreCase( str1 );

Passing Variables in Methods


In our examples, we already tried passing variables to methods. However, we haven't differentiated between
the different types of variable passing in Java. There are two types of passing data to methods, the first one is
pass-by-value and then, pass-by-reference.

Pass-by-value
When a pass-by-value occurs, the method makes a copy of the value of the variable passed to the method.
The method cannot accidentally modify the original argument even if it modifies the parameters during
calculations. For example,

PANGASINAN STATE UNIVERSITY 8


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

public class TestPassByValue {


public static void main (String [ ] args) {
int i = 10;
//print the value of i
System.out.println( i );

//call method test


//and pass i to method test
test ( i );

//print the value of i. i not changed


System.out.println ( i );
}

public static void test ( int j ) {


//change value of parameter j
j = 33;
}
}

In the given example, we called the method test and passed the value of i as parameter. The value of i is
copied to the variable of the method j. Since j is the variable changed in the test method, it will not affect the
variable value if i in main since it is a different copy of the variable.
By default, all primitive data types when passed to a method are pass-by-value.

Pass-by-reference
When a pass-by-reference occurs, the reference to an object is passed to the calling method. This means that,
the method makes a copy of the reference of the variable passed to the method. However, unlike in
pass-by-value, the method can modify the actual object that the reference is pointing to, since, although
different references are used in the methods, the location of the data they are pointing to is the same.
For example,
public class TestPassByReference {

public static void main (String [] args ) {


//create an array of integers
int [ ] ages = {10, 11, 12 };

//print array values


for ( int i=0; i<ages.length; i++) {
System.out.println( ages[ i ] );
}

//call test and pass reference to array


test ( ages );

//print array values again


for ( int i = 0; i < ages.length; i++ ) {

PANGASINAN STATE UNIVERSITY 9


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

System.out.println ( ages[ i ] );
}
}
public static void test ( int [ ] arr ) {
//change values of array
for ( int i = 0; i <arr.length; i++ ) {
arr [ i ] = i + 50;
}
}
}

10 11 12

main method test method

ages arr

Reference to array of integers Reference to array of integers

Calling Static Methods


Static methods are methods that can be invoked without instantiating a class (means without invoking the new
keyword). Static methods belongs to the class as a whole and not to a certain instance (or object) of a class.
Static methods are distinguished from instance methods in a class definition by the keyword static.

To call a static method, just type, Classname.staticMethodName(params);

Examples of static methods, we've used so far in our examples are,

//prints data to screen


System.out.println(“Hello world”);

//converts the String 10, to an integer


int i = Integer.parseInt(“10”);

//Returns a String representation of the integer argument as an


//unsigned integer base 16
String hexEquivalent = Integer.toHexString( 10 );

Scope of a variable
In addition to a variable's data type and name, a variable has scope. The scope determines where in the
program the variable is accessible. The scope also determines the lifetime of a variable or how long the
variable can exist in memory. The scope is determined by where the variable declaration is placed in the

PANGASINAN STATE UNIVERSITY 10


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

program. To simplify things, just think of the scope as anything between the curly braces {...}. The outer curly
braces is called the outer blocks, and the inner curly braces is called inner blocks. If you declare variables in
the outer block, they are visible (i.e. usable) by the program lines inside the inner blocks. However, if you
declare variables in the inner block, you cannot expect the outer block to see it. A variable's scope is inside the
block where it is declared, starting from the point where it is declared, and in the inner blocks.
For example, given the following code snippet

public class ScopeExample {

// name is accessible anywhere within the class


private String name;

public static void main( String [ ] args ) {

//number1 and number2 are accessible anywhere within the main method
int number1 = 0;
int number2= 0;

// i is accessible within the for loop


for( int i=0; i < 10; i++ ) {
System.out.println( i );
}
}
}

Coding Guideline: Avoid having variables of the same name declared inside one method to avoid
confusion

Casting, Converting and Comparing Objects


In this section, we are going to learn how to do typecasting. Typecasting or casting is the process of
converting a data of a certain data type to another data type. We will also learn how to convert primitive data
types to objects and vice versa. And finally, we are going to learn how to compare objects.

Casting, Converting and Comparing Objects


In this section, we are going to learn how to do typecasting. Typecasting or casting is the process of
converting a data of a certain data type to another data type. We will also learn how to convert primitive data
types to objects and vice versa. And finally, we are going to learn how to compare objects.
For example,

char valChar = 'A'; int valInt = valChar; System.out.print( valInt ); //explicit cast: output 65

When we convert a data that has a large type to a smaller type, we must use an explicit cast. Explicit casts
take the following form:

PANGASINAN STATE UNIVERSITY 11


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

(dataType)value

where,

dataType, is the name of the data type you're converting to value, is an expression that results in the
value of the source type.

For example,

double valDouble = 10.12;


int valInt = (int)valDouble; //convert valDouble to int type

double x = 10.2;
int y = 2;

int result = (int)(x/y); //typecast result of operation to int

Casting Objects
Instances of classes also can be cast into instances of other classes, with one restriction: The source and
destination classes must be related by inheritance; one class must be a subclass of the other. We'll cover
more about inheritance later. Analogous to converting a primitive value to a larger type, some objects might
not need to be cast explicitly. In particular, because a subclass contains all the same information as its
superclass, you can use an instance of a subclass anywhere a superclass is expected. For example, consider
a method that takes two arguments, one of type Object and another of type Window. You can pass an
instance of any class for the Object argument because all Java classes are subclasses of Object. For the
Window argument, you can pass in its subclasses, such as Dialog, FileDialog, and Frame. This is true
anywhere in a program, not just inside method calls. If you had a variable defined as class Window, you could
assign objects of that class or any of its subclasses to that variable without casting.

Object

Window

Dialog File Dialog Frame

This is true in the reverse, and you can use a superclass when a subclass is expected. There is a catch,

PANGASINAN STATE UNIVERSITY 12


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

however: Because subclasses contain more behavior than their superclasses, there's a loss in precision
involved. Those superclass objects might not have all the behavior needed to act in place of a subclass object.
For example, if you have an operation that calls methods in objects of the class Integer, using an object of
class Number won't include many methods specified in Integer. Errors occur if you try to call methods that the
destination object doesn't have. To use superclass objects where subclass objects are expected, you must
cast them explicitly. You won't lose any information in the cast, but you gain all the methods and variables that
the subclass defines. To cast an object to another class, you use the same operation as for primitive types:

To cast,

(classname)object

where,

classname, is the name of the destination class


object, is a reference to the source object.

Note: that casting creates a reference to the old object of the type classname; the old object continues to exist
as it did before.

Employee

Vice President Janitor

The following example casts an instance of the class VicePresident to an instance of the class Employee;
VicePresident is a subclass of Employee with more information, which here defines that the VicePresident
has executive washroom privileges,

Employee emp = new Employee();


VicePresident veep = new VicePresident();
emp = veep; // no cast needed for upward use
veep = (VicePresident)emp; // must cast explicitlyCasting

Converting Primitive Types to Objects and Vice Versa


One thing you can't do under any circumstance is cast from an object to a primitive data type, or vice versa.
Primitive types and objects are very different things in Java, and you can't automatically cast between the two
or use them interchangeably. As an alternative, the java.lang package includes classes that correspond to
each primitive data type: Float, Boolean, Byte, and so on. Most of these classes have the same names as the
data types, except that the class names begin with a capital letter (Short instead of short, Double instead of
double, and the like). Also, two classes have names that differ from the corresponding data type: Character is
used for char variables and Integer for int variables. (Called Wrapper Classes

PANGASINAN STATE UNIVERSITY 13


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

Java treats the data types and their class versions very differently, and a program won't compile successfully
if you use one when the other is expected. Using the classes that correspond to each primitive type, you can
create an object that holds the same value.

Examples:

//The following statement creates an instance of the Integer


// class with the integer value 7801 (primitive -> Object)
Integer dataCount = new Integer(7801);

//The following statement converts an Integer object to


// its primitive data type int. The result is an int with //value 7801
int newCount = dataCount.intValue();

// A common translation you need in programs


// is converting a String to a numeric type, such as an int
// Object->primitive
String pennsylvania = "65000";
int penn = Integer.parseInt(pennsylvania);

CAUTION: The Void class represents nothing in Java, so there's no reason it would be used when translating
between primitive values and objects. It's a placeholder for the void keyword, which is used in method
definitions to indicate that the method does not return a value.

Comparing Objects
In our previous discussions, we learned about operators for comparing values—equal, not equal, less than,
and so on. Most of these operators work only on primitive types, not on objects. If you try to use other values
as operands, the Java compiler produces errors.
The exceptions to this rule are the operators for equality: == (equal) and != (not equal). When applied to
objects, these operators don't do what you might first expect. Instead of checking whether one object has the
same value as the other object, they determine whether both sides of the operator refer to the same object.
To compare instances of a class and have meaningful results, you must implement special methods in your
class and call those methods. A good example of this is the String class.
It is possible to have two different String objects that contain the same values. If you were to employ the ==
operator to compare these objects, however, they would be considered unequal. Although their contents
match, they are not the same object.
To see whether two String objects have matching values, a method of the class called equals() is used. The
method tests each character in the string and returns true if the two strings have the same values.

The following code illustrates this,

class EqualsTest {
public static void main(String[] arguments) {
String str1, str2;
str1 = "Free the bound periodicals.";
str2 = str1;
System.out.println("String1: " + str1);

PANGASINAN STATE UNIVERSITY 14


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

System.out.println("String2: " + str2);


System.out.println("Same object? " + (str1 == str2));
str2 = new String(str1);
System.out.println("String1: " + str1);
System.out.println("String2: " + str2);
System.out.println("Same object? " + (str1 == str2));
System.out.println("Same value? " + str1.equals(str2));
}
}

This program's output is as follows,

OUTPUT:

String1: Free the bound periodicals.


String2: Free the bound periodicals.
Same object? true
String1: Free the bound periodicals.
String2: Free the bound periodicals.
Same object? false
Same value? True

Now let's discuss the code.

String str1, str2;


str1 = "Free the bound periodicals.";

str1

Free the bound periodicals.

str2

The first part of this program declares two variables (str1 and str2), assigns the literal "Free the bound
periodicals." to str1, and then assigns that value to str2. As you learned earlier, str1 and str2 now point to the
same object, and the equality test proves that.

str2 = new String(str1);

In the second part of this program, you create a new String object with the same value as str1 and assign str2
to that new String object. Now you have two different string objects in str1 and str2, both with the same value.
Testing them to see whether they're the same object by using the == operator returns the expected answer:
false—they are not the same object in memory. Testing them using the equals() method also returns the
expected answer: true— they have the same values.

NOTE: Why can't you just use another literal when you change str2, rather than using new? String literals are
optimized in Java; if you create a string using a literal and then use another literal with the same characters,
Java knows enough to give you the first String object back. Both strings are the same objects; you have to go
out of your way to create two separate objects.

PANGASINAN STATE UNIVERSITY 15


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

Determining the Class of an Object


Want to find out what an object's class is? Here's the way to do it for an object assigned to the variable key:

1. The getClass() method returns a Class object (where Class is itself a class) that has a method called
getName(). In turn, getName() returns a string representing the name of the class.

For Example,

String name = key.getClass().getName();

2. The instanceOf operator


The instanceOf has two operands: a reference to an object on the left and a class name on the right.
The expression returns true or false based on whether the object is an instance of the named class or
any of that class's subclasses

For Example,

boolean ex1 = "Texas" instanceof String;


// true Object pt = new Point(10, 10);
boolean ex2 = pt instanceof String; // false

LEARNING POINTS

 Writing object-oriented programs involves creating classes, creating objects from those classes, and
creating applications that use those objects. Object-oriented programming languages support
encapsulation, inheritance, and polymorphism.

 A method is an encapsulated series of statements that carry out a task. Any method can call, or invoke,
another. You place a method within a class outside of any other methods.

 Objects are concrete instances of classes. Objects gain their attributes from their classes, and all objects
have predictable attributes because they are members of certain classes. In addition to their attributes,
objects have methods associated with them, and every object that is an instance of a class is assumed to
possess the same methods.

 A variable’s scope is the portion of a program within which it can be referenced. A block is the code
between a pair of curly braces. Within a method, you can declare a variable with the same name multiple
times, as long as each declaration is in its own nonoverlapping block. If you declare a variable within a
class and use the same variable name within a method of the class, the variable used inside the method
takes precedence over (or overrides, or masks) the first variable

LEARNING ACTIVITIES

Exercises

Defining Terms.
In your own words, define the following terms.

1. Class

2. Object

PANGASINAN STATE UNIVERSITY 16


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

3. Instantiate

4. Instance Variable

5. Instance Method

6. Class Variables or static member variables

7. Constructor

8. Encapsulation

9. Typecasting

10. Polymorphism

Skills Workout:
Java Scavenger Hunt

Java Scavenger Hunt Pipoy is a newbie in the Java programming language. He just heard that there are
already ready-to-use APIs in Java that one could use in their programs, and he's eager to try them out.
The problem is, Pipoy does not have a copy of the Java Documentation, and he also doesn't have an
internet access, so there's no way for him to view the Java APIs.

Your task is to help Pipoy look for the APIs (Application Programming Interface). You should state the
class where the method belongs, the method declaration and a sample usage of the said method.

For example, if Pipoy wants to know the method that converts a String to integer, your answer should be:

Class: Integer
Method Declaration: public static int parseInt( String value )
Sample Usage:
String strValue = "100";
int value = Integer.parseInt( strValue );

Make sure that the snippet of code you write in your sample usage compiles and outputs the correct
answer, so as not to confuse Pipoy. (Hint: All methods are in the java.lang package). In cases where
you can find more methods that can accomplish the task, give only one.

Now let's start the search!

1. Look for a method that checks if a certain String ends with a certain suffix. For example, if the given
string is "Hello", the method should return true the suffix given is "lo", and false if the given suffix is
"alp".
2. Look for the method that determines the character representation for a specific digit in the specified
radix. For example, if the input digit is 15, and the radix is 16, the method would return the character F,
since F is the hexadecimal representation for the number 15 (base 10).

3. Look for the method that terminates the currently running Java Virtual Machine

PANGASINAN STATE UNIVERSITY 17


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

4. Look for the method that gets the floor of a double value. For example, if I input a 3.13, the method
should return the value 3.

5. Look for the method that determines if a certain character is a digit. For example, if input '3', it
returns the value true.

REFERENCES

1. Programming Language. From Wikipedia at


http://en.wikipedia.org/wiki/Programming_language

2. Programming Language. From Webopedia at


http://www.webopedia.com/TERM/p/programming_language.html

3. Programming Language. From Answers.com at


http://www.answers.com/topic/programming-language

4. High-Level Programming Language. From Wikipedia at


http://en.wikipedia.org/wiki/High-level_programming_language

5. Defining Flowchart Symbols. Available at http://www.pattonpatton.


com/basic_flow_chart_symbols.htm

6. Integrated Development Environment. From Webopedia at


http://www.webopedia.com/TERM/I/integrated_development_environment.html

7. Variables and Expressions. Available at


http://www.geocities.com/SiliconValley/Park/3230/java/javl1002.html

8. Writing Abstract Classes and Methods. Available at


http://java.sun.com/docs/books/tutorial/java/javaOO/abstract.html

9. Defining an Interface. Available at


http://java.sun.com/docs/books/tutorial/java/interpack/interfaceDef.html

20.Inheritance and Polymorphism. Available at


http://home.cogeco.ca/~ve3ll/jatutor7.htm

21.The Essence of OOP using Java, Runtime Polymorphism through Inheritance.


Available at http://www.developer.com/tech/article.php/983081

22.Gary B. Shelly, Thomas J. Cashman, Joy L. Starks. Java Programming Complete Concepts
and Techniques. Course Technology Thomson Learning. 2001.

23.Stephen J. Chapman. Java for Engineers and Scientists 2nd Edition. Pearson Prentice Hall. 2004

24.Deitel & Deitel. Java How to Program 5th Edition.

25.Sun Java Programming Student Guide SL-275. Sun Microsystems. February 2001.

26.Does Java pass by reference or pass by value? Why can't you swap in Java? Available at
http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

27.Java Branching Statements. Available at


http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html.

PANGASINAN STATE UNIVERSITY 18


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 6: Objects and Classes

28.Encapsulation. Available at http://home.cogeco.ca/~ve3ll/jatutor4.htm.

29. Joyce Farrell (2019), Java Programming 9th ed, Ceangage Learning

PANGASINAN STATE UNIVERSITY 19


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 5: Java Arrays

Module No. 5
MODULE TITLE
JAVA ARRAYS

MODULE OVERVIEW

In this section, we will be discussing about Java Arrays. First, we are going to define what arrays
are, and then we are going to discuss on how to declare and use them.

LEARNING OBJECTIVES

At the end of the lesson, the student should be able to:


 Declare and create arrays
 Access array elements
 Determine the number of elements in an array
 Declare and create multidimensional arrays

LEARNING CONTENTS

Introduction to arrays
In the previous lessons, we have discussed on how to declare different variables using the primitive data
types. In declaring variables, we often use a unique identifier or name and a datatype. In order to use the
variable, we call it by its identifier name.

For example, we have here three variables of type int with different identifiers for each variable.
int number1;
int number2;
int number3;

number1 = 1;
number2 = 2;
number3 = 3;

As you can see, it seems like a tedious task in order to just initialize and use the variables
especially if they are used for the same purpose. In Java and other programming languages, there
is one capability wherein we can use one variable to store a list of data and manipulate them
more efficiently. This type of variable is called an array.

Figure 1: Example of an Integer Array

PANGASINAN STATE UNIVERSITY 1


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 5: Java Arrays

An array stores multiple data items of the same datatype, in a contiguous block of memory,
divided into a number of slots. Think of an array as a stretched variable – a location that still has
one identifier name, but can hold more than one value.

Declaring Arrays

Arrays must be declared like all variables. When declaring an array, you list the data type,
followed by a set of square brackets[], followed by the identifier name. For example,

int []ages;

or you can place the brackets after the identifier. For example,

int ages[];

After declaring, we must create the array and specify its length with a constructor statement. This
process in Java is called instantiation (the Java word for creates). In order to instantiate an object,
we need to use a constructor for this. We will cover more about instantiating objects and
constructors later. Take note, that the size of an array cannot be changed once you've initialized it.
For example,

//declaration
int ages[];
//instantiate object
ages = new int[100];

or, can also be written as,

//declare and instantiate


object
int ages[] = new int[100];

In the example, the declaration tells the Java Compiler


that the identifier ages will be used as the name of an
array containing integers, and to create or instantiate a
new array containing 100 elements.

Figure 2: Instantiating Arrays

Instead of using the new keyword to instantiate an array, you can also automatically declare,
construct and assign values at once.

PANGASINAN STATE UNIVERSITY 2


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 5: Java Arrays

Examples are
// creates an array of boolean variables with identifier results.
// This array contains 4 elements that are initialized
// to values {true, false, true, false}
boolean results[] ={ true, false, true, false };

//creates an array of 4 double variables initialized


//to the values {100, 90, 80, 75};
double []grades = {100, 90, 80, 75};

//creates an array of Strings with identifier days and


//initialized. This array contains 7 elements
String days[] = {“Mon”,“Tue”,“Wed”,“Thu”,“Fri”,“Sat”,“Sun”};

Accessing an array element

To access an array element, or a part of the array, you use a number called an index or a
subscript.

An index number or subscript is assigned to each member of the array, allowing the program and
the programmer to access individual values when necessary. Index numbers are always integers.
They begin with zero and progress sequentially by whole numbers to the end of the array. Take
note that the elements inside your array is from 0 to (sizeOfArray-1).

For example, given the array we declared a while ago, we have


//assigns 10 to the first element in the array
ages[0] = 10;
//prints the last element in the array
System.out.print(ages[99]);
Take note that once an array is declared and constructed, the stored value of each member of the
array will be initialized to zero for number data. However, reference data types such as Strings
are not initialized to blanks or an empty string “”. Therefore, you must populate the String arrays
explicitly.

The following is a sample code on how to print all the elements in the array. This uses a for loop,
so our code is shorter.

public class ArraySample{


public static void main( String[] args ){

int []ages = new int[100];


for( int i=1; i<100; i++ ){
System.out.print( ages[i] );
}
}
}

PANGASINAN STATE UNIVERSITY 3


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 5: Java Arrays

Array length

In order to get the number of elements in an array, you can use the length field of an array. The length
field of an array returns the size of the array. It can be used by writing,

arrayName.length

For example, given the previous example, we can re-write it as,

public class ArraySample


{
public static void main( String[] args ){

int[] ages = new int[100];


for( int i=0; i<ages.length; i++ ){
System.out.print( ages[i] );
}
}
}

Multidimensional Arrays

Multidimensional arrays are implemented as arrays of arrays. Multidimensional arrays are


declared by appending the appropriate number of bracket pairs after the array name. For
example,

// integer array 4 x 3 elements


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

GREEN RED BLUE


[0][0] [0][1] [0][2]
BROWN VIOLET ORANGE
[1][0] [1][1] [1][2]
BLACK YELLOW PINK
[2][0] [2][1] [2][2]
MAROON MAGENTA GRAY
[3][0] [3][1] [3][2]

// String array 4 rows x 2 columns


String[][] dogs = {{ "terry", "brown" },
{ "Kristin", "white" },
{ "toby", "gray"},
{ "fido", "black"}
};

To access an element in a multidimensional array is just the same as accessing the elements
in a one dimensional array. For example, to access the first element in the first row of the
array dogs, we write,

System.out.print( dogs[0][0] );

PANGASINAN STATE UNIVERSITY 4


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 5: Java Arrays

This will print the String "terry" on the screen.

Example Program

Create an array of Strings which are initialized to the 7 days of the week. For Example,

String days[] = {“Monday”, “Tuesday”….};

Using a while-loop, print all the contents of the array.

/* Uses an array string to save the days of the week


* then prints it on the screen.
*/

public class DaysOfTheWeek1

{
public static void main(String[] args){

//declares the String array of the days of the week

String[] days ={"Sunday","Monday","Tuesday","Wednesday",


"Thursday","Friday","Saturday"};

int counter = 0;

//while loop that prints the days of the week


while(counter < days.length){
System.out.println(days[counter]);
counter++;
}

}
}

LEARNING POINTS

 An array is a named list of data items that all have the same type. You declare an array
variable by inserting a pair of square brackets after the data type. To reserve memory space
for an array, you use the keyword new. You use a subscript contained within square brackets
to refer to one of an array’s variables, or elements. In Java, any array’s elements are
numbered beginning with zero.
 Array names represent computer memory addresses. When you declare an array name, no
computer memory address is assigned to it, and the array variable name has the value null.
When you use the keyword new or supply an initialization list, an array acquires an actual
memory address. When an initialization list is not provided, each data type has a default value
for its array elements.

REFERENCES

1. Farrel, Joyce, “Java Programming 9ed”, Course Technology, Cengage Learning

PANGASINAN STATE UNIVERSITY 5


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

Module No. 4
MODULE TITLE
REPETITION CONTROL STRUCTURES

MODULE OVERVIEW

In the previous lesson, we have given examples of programs, wherein statements are executed
that allows us to select and execute specific blocks of code while skipping other sections. In this
section, we will be discussing repetion control structures, which allows us to execute specific
blocks of code a number of times..

LEARNING OBJECTIVES

At the end of the lesson, the student should be able to:


 Learn about the loop structure
 Create programs using while loop structure
 Create programs using do...while loop structure
 Create programs using for loop structure

LEARNING CONTENTS

Repetition control structures are Java statements that allows us to execute specific blocks of code
a number of times. Within a looping strucure, a Boolean expression is evaluated. If it is true, a
block of statements called the loop body executes and the Boolean expression is evaluated again.
As long as the expression is true, the statements in the loop body continue to execute. When the
Boolean evaluation is false, the loops ends. One execution of any loop is called an iteration.

Loops have four sections


 Initialization
This step occurs prior to the loop. Variables that need to be initialized are given values
prior to the first time the loop test is evaluated.
 Loop test
The test determines whether the loop body will be executed. When the loop test is false,
the loop body is not executed. If the loop test is always true, an infinite loop results,
unless the loop is exited with a break or return statement.
 Loop body
The statements that are executed each time the loop test evaluates to true.
 Loop update
The statements that affect values in the loop test. These statements ensure that the loop
will eventually terminate. Values of variables in the loop test will be changed by the
update statements.

There are three types of repetition control structures, the while, do-while and for loops.

PANGASINAN STATE UNIVERSITY 5


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

while loop

The while loop is a statement or block of statements that is repeated as long as some condition is
satisfied.

The while statement has the form,

while(test_condition)
{
statement(s);
}

Interpretation: If test_condition is true, the loopBody is executed and the test_condition is


reevaluated and tested. As long as the test_condition is true the Loop Body is executed. As soon
as test_condition is false, the loop is terminated, and the statement after the loop is executed.

Example 1. Output the numbers between 1 and 10 using a while loop.

int num = 1;
while (num <= 10) {
System.out.print( num + " ");
num ++;
}
System.out.println();

The while repeats as long as the expression in the parenthesis evaluates to true and prints the following:

1 2 3 4 5 6 7 8 9 10

Example 2. Output the numbers from 10 to 1 using a while loop.

class WhileLoopExample {
public static void main(String args[]){
int i=10;
while(i>1){
System.out.println(i);
i--;
}
}
}

PANGASINAN STATE UNIVERSITY 6


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

do-while loop

The do-while loop is similar to the while-loop. The statements inside a do-while loop are executed
several times as long as the condition is satisfied.

The do-while statement has the form,

do
{
statement(s);
} while(test_condition);

Interpretation: The statements inside the do-while loop are first executed, and then the
test_condition part is evaluated. If this evaluates to true, the statements inside the do-while loop
are executed again.

The main difference between a while and do-while loop is that, the statements inside a do-while
loop are executed at least once.

Here are a few examples that uses the do-while loop:

Example 1:

int num = 1;
while ( num <= 10 ) {
System.out.print( num + " ");
num ++;
}
System.out.println();

The output for this code is: 1 2 3 4 5 6 7 8 9 10

PANGASINAN STATE UNIVERSITY 7


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

Example 2:
//infinite loop
do{
System.out.println(“hello”);
} while (true);

This example will result to an infinite loop, that prints hello on screen.

Example 3:
Create a program that prints your name a hundred times using do-while loop.

import java.io.*;

public class HundredNames2{


public static void main(String[] args){

Scanner reader = new Scanner(System.in));


String name = "";
int counter = 0;

//gets the users' name


try{
System.out.print("Enter name: ");
name = reader.nextLine();
}catch(Exception e){
System.out.println("Invalid input");
System.exit(0);
}

//do-while loop that prints the name one hundred times

do{
System.out.println(name);
counter++;
}while(counter < 100);
}
}

for loop

For loop in Java is an entry-controlled loop that allows a user to execute a block of a statement(s)
repeatedly with a known number of times on the basis of a specified condition.

PANGASINAN STATE UNIVERSITY 8


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

The for loop has the form,

for(initialization; test_condition ; StepExpression)


{
statement(s);
}

Interpretation: The initialization is done first. Then the test_condition is performed. If


the test_condition is true, execute the body of the loop. Then perform the StepExpression and do
the test again. As soon as the test_condition is false , control passes to the statement after
the for loop.

Example 1:

class ForLoopExample {
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}

The output of this program is:

The value of i is: 10


The value of i is: 9
The value of i is: 8
The value of i is: 7
The value of i is: 6
The value of i is: 5
The value of i is: 4
The value of i is: 3
The value of i is: 2

PANGASINAN STATE UNIVERSITY 9


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

Example 2
import javax.swing.JOptionPane;
public class SampleNestedLoop {
public static void main(String args[]) {

int x=5;

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


for (int n=5; n>=1; n--){
x=x+n;
}
}
JOptionPane.showMessageDialog(null,"Value of x = "+ x);
System.exit(0);
}
}

The output of this program is:

continue statement
The continue statement is mostly used inside loops. Whenever it is encountered inside a loop,
control directly jumps to the beginning of the loop for next iteration, skipping the execution of
statements inside loop’s body for the current iteration. This is particularly useful when you want
to continue the loop but do not want the rest of the statements(after continue statement) in loop
body to execute for that particular iteration.
Example
public class ExampleContinue {
public static void main(String args[]){
for (int j=0; j<=6; j++)
{
if (j==4)
{
continue;
}
System.out.print(j+" ");
}
}
}

Output:
0 1 2 3 5 6

PANGASINAN STATE UNIVERSITY 10


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

As you may have noticed the output, the value 4 is missing because when the value of variable j is
4, the program encountered a continue statement, which makes it to jump at the beginning
of for loop for next iteration, skipping the statements for current iteration.

break statement
Use the break statement to come out of the loop instantly. Whenever a break statement is
encountered inside a loop, the control directly comes out of loop and the loop gets terminated
for rest of the iterations. It is used along with if statement, whenever used inside loop so that the
loop gets terminated for a particular condition. The important point to note is that when a break
statement is used inside a nested loop, then only the inner loop gets terminated.

Example:

public class BreakExample1 {


public static void main(String args[]){
int num =1;
while(num<=50)
{
System.out.println("Value of num is: "+num);
if (num==5)
{
break;
}
num++;
}
System.out.println("Out of while-loop");
}
}

Output:

Value of num is: 1


Value of num is: 2
Value of num is: 3
Value of num is: 4
Value of num is: 5
Out of while-loop

LEARNING POINTS

 A loop is a structure that allows repeated execution of a block of statements. Within and
looping structure, a Boolean expression is evaluated, and if it true, a block of statements
called the loop body executes; then the Boolean expression is evaluated again.
 A for loop initializes, tests, and increments in one statement. There are three sections within
the parenthesis of a for loop that are separated by exactly two semicolons.
 You can use a while loop to execute a body of statements continually while some condition
continues to be true. To correctly execute a while loop, you should initialize a loop control
variable, test in while statement and then alter the loop control variable in the loop body.

PANGASINAN STATE UNIVERSITY 11


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

 The do-while loop test a Boolean expression after one repetition has taken place, at the
bottom of the loop.
 When the continue statement is encountered inside a loop, control directly jumps to the
beginning of the loop for next iteration, skipping the execution of statements inside loop’s
body for the current iteration.
 The break statement is to come out of the loop instantly. When a break statement is
encountered inside a loop, the control directly comes out of loop and the loop gets
terminated for rest of the iterations.

LEARNING ACTIVITIES

Show the Output. Display the output of each of the following programs.

1. Assign1.java

import javax.swing.JOptionPane;
public class Assign1{
public static void main(String args[])
{
int x=5;
for (int j=2; j<=4; j++){
for (int m=10; m>6; m--){
for (int c=1; c<=5; c++){
x=x+c;
}
}
}
JOptionPane.showMessageDialog(null,"Value of x = "+ x);
}
}

2. Assign2.java

import java.io.*;
public class Assign2 {
public static void main (String[] args){
int j = 1;
while ( j < 10 )
{
System.out.print( j + " " );
j = j + j%3;
}
System.exit(0);
}
}

PANGASINAN STATE UNIVERSITY 12


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 4: Repetition Control Structures

REFERENCES

1. Farrel, Joyce, “Java Programming 9ed”, Course Technology, Cengage Learning


2. Java Education & Development Initiative Electronic Teachers Guide”, University of the Philippines Java
Research and Development Center, UP-Diliman, Quezon City.
3. https://data-flair.training/blogs/loops-in-java/
4. https://beginnersbook.com

PANGASINAN STATE UNIVERSITY 13


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Module No. 3
MODULE TITLE
DECISION CONTROL STRUCTURES

MODULE OVERVIEW

In the previous lessons, we have given examples of sequential programs, wherein statements are
executed one after another in a fixed order. In this lesson, we will be discussing control structures,
which allows us to change the ordering of how the statements in our programs are executed.

LEARNING OBJECTIVES

At the end of the lesson, the student should be able to:


 Plan decision-making logic
 Make decisions with if and if...else structures
 Use multiple statements in an if and if...else structures
 Use the switch statement

LEARNING CONTENTS

Decision Control Structures

The decision control structure are Java statements that allows us to select and execute one set of
statements if a condition is true and another set of actions to be executed if a condition is false.

if statement
The if-statement specifies that a statement (or block of code) will be executed if and only if a
certain condition statement is true.
The if-statement has the form,
if(condition)
{
// Statements to execute if
// condition is true
}

where, condition is either a boolean expression or boolean variable.

PANGASINAN STATE UNIVERSITY 4


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Figure 1: Flowchart of If-Statement

For example, given the piece of code,


int grade = 75;
if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}

if-else statement

The if-else statement is used when we want to execute a certain statement if a condition is true,
and a different statement if the condition is false.
The if-else statement has the form,

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

PANGASINAN STATE UNIVERSITY 5


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Figure 2: Flowchart of If-Else Statement

For example, given the source code for the if-else statement,
public class IfElseDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}

Output:
i is smaller than 15

Example 2 – The following program determines an employee’s weekly wages. If the hours worked
exceed 40, then wages include overtime payment. Use Scanner class to get input from the user.

import java.util.Scanner;
public class WeeklyWages
{
public static void main(String[] args)
{
double rate;
double hoursWorked;
double regularPay;
double overtimePay;
double wages;
final int FULL_WEEK = 40;
final double OT_RATE = 1.5;

Scanner keyboard = new Scanner(System.in);

PANGASINAN STATE UNIVERSITY 6


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

System.out.print("How many hours did you work this week? ");


hoursWorked = keyboard.nextDouble();
System.out.println();
System.out.print("What is your regular pay rate? ");
rate = keyboard.nextDouble();

if(hoursWorked > FULL_WEEK)


{
regularPay = FULL_WEEK * rate;
overtimePay = (hoursWorked - FULL_WEEK)*OT_RATE *rate;
wages = regularPay + overtimePay;
}

else
{
regularPay = hoursWorked * rate;
overtimePay = 0.0;
wages = regularPay + overtimePay;
}

System.out.printf("Regular pay is $%.2f %n"+ regularPay +


"\n Overtime pay is $%.2f %n" + overtimePay +"\nTotal
wages is $%.2f %n"+ wages);

}
}

if-else if statement
The statement in the else-clause of an if-else block can be another if-else structures. This
cascading of structures allows us to make more complex selections.

The if-else if statement has the form,

if(condition_1) {
/*if condition_1 is true execute this*/
statement1(s);
}
else if(condition_2) {
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement2(s);
}
else if(condition_3) {
/* execute this if condition_1 & condition_2 are
* not met and condition_3 is met
*/
statement3(s);
}
.
.
.
else {

PANGASINAN STATE UNIVERSITY 7


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

/* if none of the condition is true


* then these statements gets executed
*/
statement(s);
}

Take note that you can have many else-if blocks after an if-statement. The else-block is optional
and can be omitted. In the example shown above, if condition_1 is true, then the program
executes statement1 and skips the other statements. If condition_2 is true, then the program
executes statement 2 and skips to the statements following statement3.

Figure 3: Flowchart of If-Else-If Statement

Sample program for if-else if-else statement

public class IfElseIfExample {

public static void main(String args[]){


int num=1234;
if(num <100 && num>=1) {
System.out.println("Its a two digit number");
}
else if(num <1000 && num>=100) {
System.out.println("Its a three digit number");
}
else if(num <10000 && num>=1000) {
System.out.println("Its a four digit number");
}
else if(num <100000 && num>=10000) {
System.out.println("Its a five digit number");
}
else {
System.out.println("number is not between 1 & 99999");
}

PANGASINAN STATE UNIVERSITY 8


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

}
}

Output of the program.


Its a four digit number

switch statement
Switch case statement is used when we have number of options (or choices) and we may need to
perform a different task for each choice.

The syntax of the switch statement is,


switch (switch_expression){
case selector1:
statement1;
break;
case selector2:
statement2;
break;
.
.
case selectorN:
statementN;
break;
default:
statementDefault;
}

where, switch_expression is an integer or character expression and, selector1,


selector2 and so on, are unique integer or character constants.

When a switch is encountered, Java first evaluates the switch_expression, and jumps to the
case whose value matches the selector of the expression. The program executes the
statements in order from that point on until a break statement is encountered, skipping then to
the first statement after the end of the switch structure.

If none of the cases are satisfied, the default block is executed. Take note however, that
the default part is optional. A switch statement can have no default block.

PANGASINAN STATE UNIVERSITY 9


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Figure 4: Flowchart of switch statement

Source code for switch statement


import java.util. * ;
public class SwitchStatement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("You have three options of programming language");
System.out.println("1. Java");
System.out.println("2. Python");
System.out.println("3. c#");
System.out.println("Enter your choice:");
int ch = sc.nextInt();
switch (ch) {
case 1:
System.out.println("Congrats you have chosen Java!");
break;
case 2:
System.out.println("Congrats you have chosen Python!");
break;
case 3:
System.out.println("Congrats you have chosen c#!");
break;
default:
System.out.println("Wrong input!");
break;
}
}

PANGASINAN STATE UNIVERSITY 10


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 3: Decision Control Structures

Output of the program:


You have three options of programming language
1. Java";
2. Python
3. c#
Enter your choice:
2
Congrats you have chosen Python!

LEARNING POINTS

 Making decision involves choosing between two alternative courses of action based on some
value within a program.
 The decision-control structures use Boolean expression. Selection structures can be one
alternative or if statement, two alternatives or the if-else statement, and three or more
alternatives or the if-else if …else statement.
 Decision control structure can be nested
 The decision control structure uses relational or logical operators.
 The switch statement test a single variable against a series of exact integer, character or string
values.

REFERENCES

1. Farrel, Joyce, “Java Programming 9ed”, Course Technology, Cengage Learning


2. Java Education & Development Initiative Electronic Teachers Guide”, University of the Philippines Java
Research and Development Center, UP-Diliman, Quezon City.
3. https://beginnersbook.com/2017/08/if-else-statement-in-java/
4. https://data-flair.training/blogs/decision-making-in-java/

PANGASINAN STATE UNIVERSITY 11


Study Guide in F M -AA -C IA-1 5 R ev. 0 03-Ju n e-2020

OOP 101 – Object-Oriented Programming Module 1: Java Programming Fundamentals

Module No. 1
M O D U L E T IT L E
JA V A P R O G R A M M IN G F U N D A M E N T A L S

M O D U L E O V E R V IE W

In this lesson, we will be discussing the basic parts of a Java program. We will start by trying to
explain the basic parts of the MyFirstJavaProgram.java program. We will also be discussing some
coding guidelines or code conventions along the way to help in effectively writing readable
programs.

L E A R N IN G O B JE C T IV E S

After finishing this lesson, the student should be able to:


1. Identify the basic parts of a Java program
2. Differentiate among Java literals, primitive data types, variable types, identifiers and
operators
3. Develop a simple valid Java program using the concepts learned in this chapter

L E A R N IN G C O N T E N T S

Let us look at a simple java code that will print the words Welcome to Java Programming!

public class MyFirstJavaProgram {

/* This is my first java program.


* This will print “Welcome to Java programming! as the output
*/

public static void main(String args[]) {

System.out.println("Welcome to Java Programming!");


}
}

The first line of the code,


public class MyFirstJavaProgram

indicates the name of the class which is MyFirstJavaProgram. In Java programming, all code
should be placed inside a class declaration by using the class keyword and the class uses an
access specifier public, which indicates that our class in accessible to other classes from other
packages. The next line which contains a curly brace { specifies the beginning of a block. The next
three lines indicates a Java comment which is used to document a part of a code and it is not part
of the program.
/* This is my first java program.
* This will print “Welcome to Java programming! as the output
*/

P A N G A S IN A N S T A T E U N IV E R S IT Y 1
Study Guide in F M -AA -C IA-1 5 R ev. 0 03-Ju n e-2020

OOP 101 – Object-Oriented Programming Module 1: Java Programming Fundamentals

The next line,


public static void main(String args[]) {

indicates the name of one method in MyFirstJavaProgram which is the main method. The
main method is the starting point of a java program.

The next line,


System.out.println("Welcome to Java Programming!");

prints the word "Welcome to Java Programming!" on the monitor screen.

The two closed curly braces is used to close the main method and class respectively.

To write your source code, save the file, compile, and run your first java program, perform the
following steps −
1. Open the notepad application and enter the code above.
2. Save the file in your folder as: MyFirstJavaProgram.java.
3. Open the command prompt window and go to the directory and folder where you saved the file.
Assuming the directory is D:\> and the folder is JavaPrograms

4. In setting the path of the java development kit, type path = C:\Program
Files\Java\jdk1.8.0_40\bin and press the enter key
ex. D:\JavaPrograms>path = C:\Program Files\Java\jdk1.8.0_40\bin

5. Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no
errors in your code, the command prompt will take you to the next line
ex. D:\JavaPrograms>javac MyFirstJavaProgram.java

6. To run your program, type ' java MyFirstJavaProgram '


ex. D:\JavaPrograms>java MyFirstJavaProgram

7. You will be able to see the word Welcome to Java programming! on the screen.

Java Comments
Comments are written for documentation purposes. The comments are not part of the program
and does not affect the flow of the program. Java supports the single-line and multi-line
comments similar to C and C++.

Statements and blocks


A statement is one or more lines of code terminated by a semicolon. An example of a single
statement is,
System.out.println("Welcome to Java Programming!");

A block is one or more statements bounded by an opening and closing curly braces that groups
the statements as one unit. An example of a block is,

P A N G A S IN A N S T A T E U N IV E R S IT Y 2
Study Guide in F M -AA -C IA-1 5 R ev. 0 03-Ju n e-2020

OOP 101 – Object-Oriented Programming Module 1: Java Programming Fundamentals

public static void main(String args[]) {


System.out.print("Welcome to Java ");
System.out.print("Programming!");
}

Identifiers
Identifiers are tokens that represent names of variables, methods, classes, etc. Examples of
identifiers are: Hello, main, System, out.
There are several points to remember about identifiers.
 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
 After the first character, identifiers can have any combination of characters and numbers.
 A keyword or reserved word cannot be used as an identifier.
 Java identifiers are case sensitive.

Keywords
Keywords or reserved words are words that have a specific purpose to the compiler and cannot
be used for other purposes in the program. Here is a list of the Java Keywords.

abstract assert boolean break

byte case catch char

class const continue default

do double else enum

extends final finally float

for goto if implements

import instanceof int interface

long native new package

private protected public return

short static strictfp super

switch synchronized this throw

throws transient try void

volatile while

P A N G A S IN A N S T A T E U N IV E R S IT Y 3
Study Guide in F M -AA -C IA-1 5 R ev. 0 03-Ju n e-2020

OOP 101 – Object-Oriented Programming Module 1: Java Programming Fundamentals

Java Literals
A literal in java refers to a fixed value that appears directly in a program. There are five types of
java literals and can be classified as integer literals, floating-point literals, character literals, string
literals and boolean literals.
Integer Literals

Integer literals come in different formats: decimal (base 10) the allowed digits are 0 to 9. For
example int x=12; hexadecimal (base 16) the allowed digits are 0 to 9 , a to f or A to F. For the
extra digits we can use both uppercase and lower case. This is one of few places where the Java
language is not case sensitive. Literal value should be prefixed with 0x or 0X. For example: int x=
0xC; and octal (base 8) the allowed digits are 0 to 7. Literal value should be prefixed with 0 (zero).
For example: int x= 014;

Floating-Point Literals

Floating point literals represent decimals with fractional parts. An example is 3.1416. Floating point literals
can be expressed in standard or scientific notations. For example, 583.45 is in standard notation, while
5.8345e2 is in scientific notation.

The default to the data type of floating point literals is double which is a 64-bit value.

Boolean Literals

The only possible values for the boolean literals are tru e and fa lse.

Character Literals

A char literal can be represented as single character within single quotes. For example char c=
'a';

String Literals

Any sequence of characters enclosed by double quotes ( " " ) is called string literal. An example of
a string literal is, “Welcome to Java Programming!”.

Primitive data types


The Java programming language defines eight primitive data types. The following are, boolean
(for logical), char (for textual), byte, short, int, long (integral), double and float (floating point).

Logical - boolean
The Boolean data type is used to store only two possible values: true .and false

boolean result = true;

The example shown above, declares a variable named result as boolean type and assigns it a
value of true.

P A N G A S IN A N S T A T E U N IV E R S IT Y 4
Study Guide in F M -AA -C IA-1 5 R ev. 0 03-Ju n e-2020

OOP 101 – Object-Oriented Programming Module 1: Java Programming Fundamentals

Textual – char
A character data type (char), represents a single Unicode character. It must have its literal
enclosed in single quotes(’ ’). For example, ‘a’ //The letter a and ‘\t’ //A tab

Integral – byte, short, int & long


Integer types can hold whole numbers. The size of the values that can be stored depends on the
integer type that we choose

Integer Length Name or Type Range of values that can be stored

8 bits byte −128 to 127

16 bits short −32768 to 32767

32 bits int −2,147,483,648 to 2,147,483,647

−9,223,372,036,854,775,808 to
64 bits long
9,223,372,036,854,755,807

Floating Point – float and double


Floating point data types are used to represent numbers with a fractional part and has double as
default data type.

Float Length Name or Type Range of values that can be stored


32 bits float 3.4e−038 to 3.4e+038
64 bits double 1.7e−308 to 1.7e+038

Variables

A variable is an item of data used to store state of objects. A variable has a data type and a name.
The data type indicates the type of value that the variable can hold. The variable name must
follow rules for identifiers.
To declare a variable is as follows,
<data type> <name> [=initial value];
Values enclosed in <> are required values, while those values enclosed in [] are optional.
In order to output the value of a certain variable, we can use the following commands,

System.out.println( value );
System.out.println( “The value of x=“ + x );

Reference Variables vs. Primitive Variables


We will now differentiate the two types of variables that Java programs have. These are reference
variables and primitive variables.

P A N G A S IN A N S T A T E U N IV E R S IT Y 5
Study Guide in F M -AA -C IA-1 5 R ev. 0 03-Ju n e-2020

OOP 101 – Object-Oriented Programming Module 1: Java Programming Fundamentals

Primitive variables are variables with primitive data types. They store data in the actual memory
location of where the variable is.
Reference variables are variables that stores the address in the memory location. It points to
another memory location of where the actual data is. When you declare a variable of a certain
class, you are actually declaring a reference variable to the object with that certain class.
As you can see, for the primitive variable num, the data is on the actual location of where the
variable is. For the reference variable name, the variable just holds the address of where the
actual data is.

Operators
Operators are used to perform operations on variables and values. Java divides the operators into
the different groups. There are arithmetic operators, relational operators, logical operators and
conditional operators. These operators follow a certain kind of precedence so that the compiler
will know which operator to evaluate first in case multiple operators are used in one statement.

Arithmetic operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

Relational operators
Relational or comparison operators compare two values and determines the relationship
between those values. The output of evaluation is the boolean values true or false.

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

P A N G A S IN A N S T A T E U N IV E R S IT Y 6
Study Guide in F M -AA -C IA-1 5 R ev. 0 03-Ju n e-2020

OOP 101 – Object-Oriented Programming Module 1: Java Programming Fundamentals

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Logical operators
Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result !(x < 5 && x < 10)
is true

Conditional Operator
The conditional operator ?: is a ternary operator. This means that it takes in three arguments that
together form a conditional expression and it is a sshorthnad for the if-then-else statemenmt.
The syntax of the conditional operator is,
variable = expression ? expression1 : expression2

Here's how it works.


 If expression is true, expression1 is assigned to the variable.
 If expression is false, expression2 is assigned to the variable.

L E A R N IN G P O IN T S

 In Java, the name of the class should be the name of the program file. Java is composed of
class header and a method or methods. Java programs may have 1 or more methods but
there is only one main method. Java program may also have no main method but can be
accessed or invoke by other java classes.
 Programmers uses comments to insert remark for a certain line or block of codes. Comments
are nonexecutable statements. Java provides three types of comments: line comments, block
comments and Javadoc comments.
 Identifiers are names supplied by programmers for classes, methods, constants, and variables.
 Java keywords are also known as reserved words. Keywords are particular words which acts
as a key to a code. These are predefined words by Java so it cannot be used as a variable or
object name.
 Primitive data types serve as the building blocks for more complex data types. Java’s eight
data types are: byte, short, int, long, float, double, char, Boolean.
 Variables are named memory locations in which program stores values. You need to declare
all variables first before you can use it in your program.

P A N G A S IN A N S T A T E U N IV E R S IT Y 7
Study Guide in F M -AA -C IA-1 5 R ev. 0 03-Ju n e-2020

OOP 101 – Object-Oriented Programming Module 1: Java Programming Fundamentals

 Operators are symbols used in an expression when evaluated it would results to a value. The
value could be a number and Boolean.
 In evaluating an expression, Java follows operator precedence, which mean the hierarchy of
operator to be evaluated first.

L E A R N IN G A C T IV IT IE S

SKILLS WORKOUT
1. Getting the average of three numbers

Write the java source code that outputs the average of three numbers. Let the values of
the three numbers be, 10, 20 and 45. The expected screen output is,
number 1 = 10
number 2 = 20
number 3 = 45
Average is = 25

2. Output greatest value

Given three numbers, write a program that outputs the number with the greatest value
among the three. Use the conditional ?: operator that we have studied so far (HINT: You will
need to use two sets of ?: to solve this). For example, given the numbers 10, 23 and 5, your
program should output,

number 1 = 10
number 2 = 23
number 3 = 5
The highest number is = 23

REFERENCES

1. Farrel, Joyce, “Java Programming 9ed”, Course Technology, Cengage Learning


2. Java Education & Development Initiative Electronic Teachers Guide”, University of the Philippines Java
Research and Development Center, UP-Diliman, Quezon City.

P A N G A S IN A N S T A T E U N IV E R S IT Y 8
Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 2: Getting Input from the Keyboard

Module No. 2
MODULE TITLE
GETTING INPUT FROM THE KEYBOARD

MODULE OVERVIEW

Now that we've studied some basic concepts in Java and we've written some simple programs, let's
make our programs more interactive by getting some input from the user. In this lesson, we'll be
discussing two methods of getting input, the first one is by using the Scanner class, and the other
one involves a graphical user interface by using JOptionPane.

LEARNING OBJECTIVES

At the end of the lesson, the student should be able to:


• Create an interactive Java program that gets input from the keyboard
• Use the Scanner class to read data from the keyboard using a console
• Use the JOptionPane class to get input from the keyboard using a graphical user interface

LEARNING CONTENTS

Using the Scanner Class to get input

To put data into variables from the standard input device, Java provides the class Scanner. Using
this class, first we create an input stream object and associate it with the standard input device.
The following statement accomplishes this:

Scanner inputDevice = new Scanner(System.in)

The portion of the statement to the left of the assignment operator, Scanner inputDevice,
declares an object of type Scanner with the programmer-chosen inputDevice.

The portion of the statement to the right of the assignment operator, new
Scanner(System.in), creates a Scanner object that is connected to the System.in
property. In other words, the created Scanner object is connected to the default input device.

Given the following code,

import java.util.Scanner;
public class GetUserInfo
{
public static void main( String[] args )
{
String name;
int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print(“Please enter your name “);

PANGASINAN STATE UNIVERSITY 3


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 2: Getting Input from the Keyboard

name = inputDevice.nextLine();
System.out.print(“Please enter your age “);
age = inputDevice.nextInt();
System.out.println(“Your name is “ + name +
“ and you are “ + age +“ years old.”);
}
}

The first statement,


import java.util.Scanner;

indicates that we want to import the class Scanner from the java.util package. This
statement imports the package necessary to use the Scanner class.

The statement,
Scanner inputDevice = new Scanner(System.in);

Declares a Scanner object named inputDevice.

The name = inputDevice.nextLine()statement uses the nextLine()method to


retrieve a line of text from the keyboard and store it in the name variable.

The age = inputDevice.nextInt()statement uses the nextInt()method to retrieve


an integer from the keyboard and store it in the age variable.

Using JOptionPane to get input


Another way to get input from the user is by using the JOptionPane class which is found in the
javax.swing package. JOptionPane makes it easy to pop up a standard dialog box that
prompts users for a value or informs them of something.

Given the following code,

import javax.swing.JOptionPane;
public class Welcome{

public static void main( String args[] ){


String name;
name=JOptionPane.showInputDialog("Enter your name");

JOptionPane.showMessageDialog( null, "Hello "+name +


"\nWelcome to Java Programming!" );

System.exit(0);
}
}

PANGASINAN STATE UNIVERSITY 4


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 2: Getting Input from the Keyboard

The first line,


import javax.swing.JOptionPane;
indicates that we want to import the class JOptionPane from the swing package inside the
external library javax.

The next line,


public class Welcome{

indicates the name of the class which is Welcome.

The statement,
name=JOptionPane.showInputDialog("Enter your name");

creates a JOptionPane input dialog, which will display a dialog box with a message, a textfield
with OK and Cancel button as shown in the figure 1. This returns a String which we will save in the
name variable.

The next statement,


JOptionPane.showMessageDialog( null, "Hello "+name +
"\nWelcome to Java Programming!" );

displays a dialog box which contains a message and an OK button as shown in figure 2.

The output of the above program is shown below,

Figure 1: Getting Input Using JOptionPane

Figure 2: Showing Message Using JOptionPane

PANGASINAN STATE UNIVERSITY 5


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 2: Getting Input from the Keyboard

LEARNING POINTS

• The Scanner class is used to get user input, and is found in the java.util package. To use the
Scanner class, create an object of the class and use any of the variable methods found in the
Scanner class documentation.
• The JOptionPane class is used to provide standard dialog boxes such as message dialog box,
confirm dialog box and input dialog box. These dialog boxes are used to display information or
get input from the user. The JOptionPane class inherits JComponent class.
LEARNING ACTIVITIES

Hands-on Activity
BufferedReader/Scanner version

1. Write a program that would input an integer number and then extract its one’s digit or right
most digit.

PANGASINAN STATE UNIVERSITY 6


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 2: Getting Input from the Keyboard

Scanner version

2. Write a program that would input four numbers for variables W, X, Y, and Z, respectively, and
exchange their values such that X goes into W, Y into X, Z into Y and W into Z.

PANGASINAN STATE UNIVERSITY 7


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 2: Getting Input from the Keyboard

JOptionPane version

1) Workers at a particular company were given a 17.75% salary increase. Moreover, the increase
was retroactive for 2 months, that is, effective 2 months ago. Write a program that takes the
employee’s old salary as input and then output the amount of retroactive pay (balance) due
the employee and his new salary as well.

PANGASINAN STATE UNIVERSITY 8


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 2: Getting Input from the Keyboard

JOptionPane version

2) XYZ’s Pizza Parlor charges 12% service charge and 7% sales tax on the gross bill of its customer.
Make a program that would input the gross bill of the customer and the amount given by the
customer to the waiter. Program must output the customer’s net bill and his change.

PANGASINAN STATE UNIVERSITY 9


Study Guide in FM-AA-CIA-15 Rev. 0 03-June-2020

OOP 101 – Object-Oriented Programming Module 2: Getting Input from the Keyboard

REFERENCES

1. Farrel, Joyce, “Java Programming 9ed”, Course Technology, Cengage Learning


2. Java Education & Development Initiative Electronic Teachers Guide”, University of the Philippines Java
Research and Development Center, UP-Diliman, Quezon City.

PANGASINAN STATE UNIVERSITY 10

You might also like