You are on page 1of 106

JAVA Programming

for Beginners

Jolitte Alinsog-Villaruz
Philippine Copyright 2019
by
Jolitte Alinsog-Villaruz
and
Aklan State University

All rights reserved. No part of this book


may be reproduced or copied in any
manner or by any means of information
retrieval without permission in writing
from the author.

Reviewer: Dennis Mercado Barrios II


Editor: Julie Ann Acebuque-Salido
CONTENTS
Preface v CHAPTER 5
Disclaimer vi Control Structures
Selection Statements 36
CHAPTER 1 Loop Statements 41
Introduction to Computer Programming Branching Statements 44
Introduction to Computer Programming 2 Reading Input from the Console 46
Levels of Programming Languages 2 Using the Scanner Class 42
Activity 4 Using the JOptionPane Class 47
Activity 49
CHAPTER 2
Installation and Setup CHAPTER 6
Types of Editor 6 Arrays
Installing the JDK 6 Single - Dimensional Array 52
Installing the TextPad Text Editor 9 Declaring Array Variables 52
Setting Parameters in TextPad 11 Creating Arrays 52
Enhanced for loop 53
CHAPTER 3 Processing Single-Dimensional Arrays 54
Java Basics Multidimensional Arrays 56
Java Milestones 14 Declaring Variables of Two-Dimensional Arrays 56
The Java Programming Language 14 Creating Two-Dimensional Arrays 56
Phases of a Java Program 15 Processing Two-Dimensional Arrays 58
A Simple Java Program 15 Activity 59
Types of Programming Errors 17
Java Language Keywords 18 CHAPTER 7
Identifiers 18 Methods
Literals 18 Defining a Method 62
Types of Variables in Java 21 Calling a Method 62
Primitive Data Types and Values 21 Overloaded Methods 64
Variables 23 Passing Variables in Methods 65
Activity 24 Calling Static Methods 67
Activity 68
CHAPTER 4
Operators CHAPTER 8
Operators 26 Classes and Objects
Assignment Operators 26 Defining Classes 70
Arithmetic Operators 27 Declaring Instance Variables 71
Numeric Type Conversion 28 Class Variables or Static Variables 71
Increment and Decrement Operators 29 Declaring Constructors 71
Relational Operators 30 Encapsulation 73
Logical Operators 31 Declaring Static Methods 74
Conditional Operators 32 Creating Objects 76
Operator Precedence 33 Accessing an Object's Data and Methods 77
Activity 34 The this Reference 78

iii
The this() Constructor Call 79
Access Modifiers 80
Activity 82

CHAPTER 9
Inheritance and Polymorphism
Inheritance 84
Defining Superclasses and Subclasses 84
Calling Superclass Constructors 86
Overriding Methods 87
Final Methods and Final Classes 88
Polymorphism 89
Activity 91

CHAPTER 10
Basic Exception Handling
Exception 94
Categories of Exceptions 94
Throwing Exceptions 97
The throw Keywords 97
The throws Keywords 98

iv
Preface

Java Programming for Beginners is intended for use as an instructional material for students who are taking
programming subject and are using Java. This can also serve as guide to teachers handling the said subject. Basic
programming concepts such as operators, control structures, methods and arrays are first introduced to prepare
students to learn object-oriented programming on the later chapters.

The best way to learn programming is by doing. For students, coding the sample programs provided in this book
will be of great help to learn the Java language. This book can be of help to those who are interested in exploring
the world of Java.

Jolitte Alinsog-Villaruz

v
Disclaimer

The information in this book is sourced from the Oracle website, various books, public websites, and other relevant
documented information. No claim of originality and therefore, credit is due to all the authors of those
information.

The author shall not be held responsible for any loss or damage accrued due to any information contained in this
book or due to any direct or indirect use of this information. This book may contain inaccuracies or errors on its
content and if you discover some errors, please contact the author at jvillaruz@asu.edu.ph.

vi
CHAPTER 1

Introduction to Computer
Programming
At the end of the lesson, you will be able to:
 Define basic programming terminologies
 Discuss why can Java programs run on many different types of computers
2 Introduction to Computer Programming

Complex as it is, a computer performs its tasks by stringing together large numbers of only very simple instructions.
A set of these instructions is called program. A program tells a computer what to do in order to come up with a
solution to a particular problem. To make use of these instructions, they have to be written in programming
languages. A programming language is a standardized communication technique for expressing instructions to a
computer. Each programming language has a unique syntax and semantics.

 A syntax determines the very strict rules of what is allowed in a program. It specifies the basic vocabulary
of the language and how these elements are combined to produce language expressions.

 Semantics refers to what the program do. It applies to how language expressions are converted to CPU
instructions in order to form a meaning.

A syntactically correct program is one that can be successfully compiled or interpreted and a semantically correct
program is one that does what it is intended to do. However, a program can be syntactically and semantically
correct but still be a pretty bad program. Using the language correctly is not the same as using it well.

 Pragmatics is the aspects of programming that refers to the writing style that will make it easy for people
to read and to understand the program. It follows conventions that is familiar to other programmers.

Levels of Programming Languages

1. Machine language is the computer’s native language. It is a set of built-in primitive instructions
written in binary code. Machine language is machine dependent.

2. Assembly language is referred to as low-level language. It uses a short descriptive word, known as a
mnemonic, to represent each of the machine-language instructions. Assembly language was
developed to make programming easier. But since the computer cannot execute assembly language,
an assembler is used to translate assembly-language programs into machine language. Assembly
language is designed for a specific family of processors.

3. High-level language is written in English-like codes and is easy learn and use. A program written in a
high-level language is called a source program or source code. They are platform independent.
Examples are Java, C, C++, Basic, and Fortran.

However, a source code cannot be run directly on any computer. It must be translated into machine
language for execution. The translation can be done using another programming tool called a compiler
or an interpreter.

 A compiler translates the entire source code all at once into a machine language file, and the
machine language file is then executed. Since machine language is machine dependent, it can
only run on one type of computer.

 An interpreter runs in a loop in which it repeatedly reads one instruction from the source code,
decides what is necessary to carry out that instruction, and then performs the appropriate
machine language command to do so. An interpreted machine language file meant for one
type of computer can be used on any computer.

Compiled programs are inherently faster than interpreted programs.

JAVA Programming for Beginners


Introduction to Computer Programming 3

Java is using both compiler and interpreter. Java programs are compiled into machine language for a virtual
computer (computer that doesn't actually exist) known as the Java virtual machine (JVM). The JVM is an
imaginary machine that is implemented by emulating software on a real machine. The JVM provides the hardware
platform specifications to which you compile all Java technology code.

The machine language for the JVM is called Java bytecode. The bytecode is independent of any particular
computer hardware, so any computer with a Java interpreter can execute the Java bytecode, no matter what type
of computer the program was compiled on. This is the reason why Java became famous, the same Java bytecode
can run on many different types of computers (variety of hardware platforms and operating systems).

Figure 1.1 Java bytecode can run on many different types of computers.

JAVA Programming for Beginners


4 Introduction to Computer Programming

Name: Year and Section: Date:

Activity
1. Why did Java become famous?

2. Enumerate at least 5 popular high-level programming languages and provide brief descriptions on each
language.

Language Description

JAVA Programming for Beginners


CHAPTER 2

Installation and Setup


At the end of the lesson, you will be able to:
 Install the Java Development Kit (JDK)
 Install the TextPad Text Editor
6 Installation and Setup

To write programs, you need a piece of software called an editor.

Types of Editor
 A source code editor is a program for editing text, like a word processor, but it has features which make
it easier to read and write computer programs. An advantage of using a plain source code editor is that
they are usually lightweight applications that are easy to learn and use, and can typically support many
programming languages.

For Windows, some popular source code editors are TextPad, SciTE, UltraEdit, or jEdit. Mac users might
want to look at TextMate, TextWrangler, or jEdit.

 Integrated Development Environments (IDEs) combines a source code editor with other tools for
software development. Most professional Java developers refer to use IDE, which make it easy for
programmers to find and correct errors, and to accomplish tasks through a graphical interface, instead of
the command line. Other popular IDEs for Java include Eclipse, NetBeans and IntelliJ IDEA.

In this book, you will be using TextPad text editor to develop and run your Java codes. TextPad is easy to use,
powerful and a general purpose source code editor. The codes in this book was tested using the free Java Standard
Edition Development Kit (JDK) 7.

Installing the JDK


1. To install the compiler, the JVM, and related files, go to
http://www.oracle.com/technetwork/java/javase/downloads/index.html

2. Click on one of the buttons to download the latest version of the Java SE JDK.
(to download Java SE JDK 7, go to
http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html)

JAVA Programming for Beginners


Installation and Setup 7

3. Accept the license agreement in the first list of files with title "Java SE Development Kit …" and then
download the appropriate software for your operating system.

JAVA Programming for Beginners


8 Installation and Setup

4. Install the JDK.

For further information, go to:

For Windows:
http://docs.oracle.com/javase/7/docs/webnotes/install/windows/jdk-installation-windows.html

For Linux:
https://docs.oracle.com/javase/8/docs/technotes/guides/install/linux_jdk.html

JAVA Programming for Beginners


Installation and Setup 9

Installing the TextPad Text Editor

1. A copy of TextPad for evaluation can be download from


http://www.textpad.com/download/index.html#downloads8

2. Select the version and click on 32 or 64-bit as appropriate to start your download.

3. After you have downloaded, extract the zipped file.

JAVA Programming for Beginners


10 Installation and Setup

4. Open the folder and run Setup.exe and follow the instructions.

5. Click Finish button.

6. Open TextPad and check if the Compile Java and Run Java Application is available under the Tools
menu. If not, you need to set the parameters manually.

JAVA Programming for Beginners


Installation and Setup 11

Setting Parameters in TextPad

1. Start TextPad.

2. Under the Configure menu, select Preferences.

3. In the pop-up menu, expand Tools.

4. In the sub-menu, select Compile Java.

5. In Parameters on the right pane, add "-classpath . " before $File, so that the content looks like
"-classpath . $File ". Be sure to put spaces as indicated.

6. Click Apply button.

7. Do the same for Run Java Application, in Parameters box looks like ""-classpath . $BaseName".

8. Click Apply and Ok buttons.

9. You are now ready to start working with your first Java program.

JAVA Programming for Beginners


12 Installation and Setup

This page is intentionally left blank

JAVA Programming for Beginners


CHAPTER 3

Java Basics
At the end of the lesson, you will be able to:
 Review the Java milestones
 Name the Java editions
 Identify the different phases of a Java program
 Write, compile and run a simple Java program
 Differentiate syntax, runtime and logic errors
 Create valid Java identifiers
 Differentiate the type of variables in Java
 Declare and initialize variables
 List all the primitive data types in Java, their literal values, and the process of creating and
initializing them
14 Java Basics

Java Milestones

1991  Sun Microsystems forms the Green Team Project, a small group of engineers led by James
Gosling. James Gosling began to work on the Oak programming language (later named Java).
1992  Sun’s Green Team Project introduces Star7, a PDA device that includes an animated touch
screen user interface and Duke, which acts as a smart agent to assist the user
 Star7 incorporates the Green OS, the Oak programming language, a toolkit, libraries, and
hardware
1995  Java makes its debut
 Oak programming language was renamed Java
1998  Visa launches the world’s first smartcard based on Java Card technology
1999  Sun announces a redefined architecture for the Java platform: Java 2 Platform, Standard
Edition (J2SE), Java 2 Platform, Enterprise Edition (J2EE), Java 2 Platform, Micro Edition
(J2ME)
2000  Apple co-founder and Chief Executive Steve Jobs announces that Apple would bundle Java 2
SE with every version of its new Mac OS X operating system
2003  Java’s new coffee cup logo debuts
2006  Sun releases Java Platform, Standard Edition (Java SE), Java Platform, Enterprise Edition (Java
EE), and Java Platform, Micro Edition (Java ME) to open source development under the GNU
General Public License
2007  Sun releases Duke, the Sun mascot, under the free BSD license
2009  Oracle acquired Sun Microsystems
2015  Java celebrates its 20th anniversary

THE JAVA PROGRAMMING LANGUAGE

As defined in the Oracle website, Java is a high-level language that is simple, object-oriented, distribute,
multithreaded, dynamic, architecture-neutral, portable, high-performance, robust and secure. It is versatile. Aside
from the fact that it can be used for Web programming, and to create applications for mobile devices, desktop
computers, and servers.

Java Editions
1. Java Platform, Enterprise Edition (Java EE)
Java Platform, Enterprise Edition (Java EE) is the industry standard for enterprise Java computing. It is used
in developing applications for heavy-duty server systems.

2. Java Platform, Standard Edition (Java SE)


Java SE is designed for developing applications for desktop and workstation devices.

3. Java Platform, Micro Edition (Java ME)


Java ME provides a robust, flexible environment for applications running on embedded systems and
mobile devices such as micro-controllers, sensors, gateways, mobile phones, personal digital assistants
(PDAs), TV set-top boxes, printers and more.

JAVA Programming for Beginners


Java Basics 15

Phases of a Java Program

Write Compile Run


NameOfClass.java NameOfClass.class program
Editor Compiler Interpreter
(Java bytecode) output

Figure 3.1 Phases of a Java program.

A Java program goes through three phases:


1. Write
2. Compile
3. Run/Execute

Looking over the phases in detail:


1. A Java program is written in a text editor and should be saved with a file name NameOfClass.java where
NameOfClass is the name of the Java class contained in the file. Take note that Java is case sensitive.

2. Compilation translates the Java program into Java bytecode with a .class extension. The Java Development
Kit (JDK) compiler is named javac.

3. Before the program can be executed, the program's .class file must be placed first in memory where
it is interpreted by the JVM.

A Simple Java Program

Program 3.1 HelloWorld.java

Note: The line numbers, 1 to 9, are for reference purposes only. These are not part of the program.

Lines 1 to 4 defines a comment. It is for human readers only and is ignored by the compiler. The use of comments
throughout a program improves its clarity.

JAVA Programming for Beginners


16 Java Basics

Table 3.1 Comments in Java


Character Description Example
// Line comment //This is a C++ style comment
/* */ Block comment or paragraph comment /* This is a C style comment */
/** */ Documentation comment or doc comment /** documentation */
The javadoc tool uses doc comments
when preparing automatically generated
documentation

Line 5 defines a class. A Java program must have at least one class. Classes have names. The name of the class
also serves as the name of the program. All programming in Java is done inside "classes."

Line 6 defines the main method. A class must contain a main method in order for it to run. The main method
is the entry point for a Java program and will subsequently invoke all the other methods that are defined in the
same class or even in other classes.

Rules to remember about main method:


 The method must be marked as a public method.
 The method must be marked as a static method.
 The modifiers public and static can be written in either order.
 The name of the method must be main.
 The return type of this method must be void.
 The method must accept a method argument of a String array or a variable argument of type
String.

Line 7 is a statement. It uses the System class from the core library to print the "Hello World!" message to
standard output. System.out.println() can be replaced with System.out.print(). The first one
appends a newline at the end of the data to output, while the latter doesn't. Every Java statement ends with a
semicolon known as a statement terminator.

The braces {} form a block that groups the program components. Each class has a block that groups the data and
methods. Each method has a block that groups the statements. It is possible for a block to contain no statements
at all; such a block is called an empty block. Block statements usually occur inside other statements, the purpose
of which, is to group together several statements into a unit. Blocks can be nested - one block can be placed within
another.

Syntax:
{
statement(s);
}

JAVA Programming for Beginners


Java Basics 17

Table 3.2 Pragmatics of Naming


Program Entity Style Guidelines Example
class Starts with a capital letter and the first letter of each SampleClassName
subsequent words must also be capitalized
method and variable Are in lowercase, but if consisting of several words, sampleMethodName
concatenate all of the words and capitalize the first sampleVariableName
letter of each word except the first
constants Capitalize every letter and use underscores in PI, KILOMETERS_PER_MILE
between every word

Table 3.3 Special Characters


Character Name Description
{} Opening and closing braces Denotes a block to enclose statements
() Opening and closing parenthesis Used with methods
[] Opening and closing brackets Indicates an array
" " Opening and closing double quotation marks Encloses a String
' ' Opening and closing single quotation marks Encloses a char
; Semicolon Marks the end of a statement

Types of Programming Errors

1. Syntax Errors
Syntax errors or compile errors occur when the compiler encounters code that violates Java’s language
rules. Mistyping a keyword, omitting the semicolon at the end of a statement, or using an opening brace
without a corresponding closing brace are common examples of syntax error.

2. Runtime Errors
Runtime errors are errors that cause a program to terminate abnormally. Run-time errors are errors that
will not display until you run or execute your program. Input mistakes typically cause runtime errors.
Another example is when the divisor is zero for integer divisions.

3. Logic Errors
Logic errors occur when a program does not perform the way it was intended to.

JAVA Programming for Beginners


18 Java Basics

Java Language Keywords or Reserved words are words that have specific meaning to the compiler and cannot be
used for other purposes in the program.

Java Language Keywords


abstract continue for new switch
assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const * float native super while
*
not used
**
added in 1.2
***
added in 1.4
****
added in 5.0

Identifiers are words given by programmers to name programming entities such as variables, constants, methods,
classes, and packages.

Rules to remember to correctly define valid identifiers:


 can use a letter (a-z, A-Z), an underscore (_), or a dollar($) sign
 can use a digit, but must not be the first character
 can be of any length
 cannot be true, false, or null
 must not be a reserved word
 are case-sensitive

Literals in Java are a sequence of characters (digits, letters, and other characters) that represent constant values
to be stored in variables. Java language specifies five major types of literals. Literals can be any number, text, or
other information that represents a value.

Types of Literals in Java


 Integer literals
 Floating-Point literals
 Boolean literals
 Character literals
 String literals

1. Integer Literals
 a decimal number by default
 is of type long, if it ends with the letter L or l
 use a leading 0 (zero) to denote an octal integer literal
 use a leading 0x or 0X (zero x) to denote a hexadecimal integer literal
 a prefix 0b indicates binary

JAVA Programming for Beginners


Java Basics 19

Flavors of Integer literal values: binary, decimal, octal, and hexadecimal


 Binary number system
 A base-2 system, which uses only 2 digits, 0 and 1
 Octal number system
 A base-8 system, which uses digits 0 through 7
 Decimal number system
 It is based on 10 digits, from 0 through 9
 Hexadecimal number system
 A base-16 system, which uses digits 0 through 9 and the letters A through F

For example,
//The number 12, in decimal
int decVal = 12;

//The number 12, in hexadecimal


int hexVal = 0xC;

//The number 12, in octal


int octVal = 014;
//The number 12, in binary
int binVal = 0b1100;

2. Floating-Point Literals
 a double type value by default
 is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally
end with the letter D or d
 can also be expressed using E or e (for scientific notation)

Use of Underscores in Numeric Literals


With Java version 7, underscores can be used as part of the literal values. Underscores helps group the
individual digits or letters of the literal values to make it more readable. The underscores have no effect
on the values.

The following codes are valid:

long decValue = 100_267_760_123L;


long octValue = 041_13;
long hexValue = 0x110_BA_75;
long binValue = 0b111_0000_10_11;

Rules to remember to the use of underscores in the numeric literal values:


 Underscores can be used only between digits
 Underscore can be right after the prefix 0, which is used to define an octal literal value
 It is not valid to start or end a literal value with an underscore
 It is not valid to place underscore after the prefixes 0b, 0B, 0x, and 0X, which are used to define
binary and hexadecimal literal values
 Underscore cannot be in positions where a String of digits is expected
 It is not valid to place underscore prior to an L, l, D, d, F, or f suffix
 It is not allowed to put underscore adjacent to a decimal point

JAVA Programming for Beginners


20 Java Basics

3. Boolean Literals
 have only two values, true or false

4. Character Literals
 It can store a single 16-bit Unicode character which allows the inclusion of symbols and special
characters from other languages, including Japanese, Korean, Chinese, Devanagari, French,
German, Spanish, others

Internally, Java stores char data as an unsigned integer value (positive integer). It is therefore
acceptable to assign a positive integer value to a char.

Escape Character is a special notation to represent special characters.

Table 4. Escape Characters


Escape
Name
Sequence
\t tab
\b backspace
\n linefeed
\r carriage return
\\ backslash
\" double quote
\' single quote

5. String Literals
 Represent multiple characters and are enclosed by double quotes such as "Hello world!"

JAVA Programming for Beginners


Java Basics 21

Types of Variables in Java

1. Primitive variables define one of the primitive data types. They store data in the actual memory location
of where the variable is.

2. Reference variables are variables that stores the address in memory location. It points to another
memory location of where the actual data is located.

For example, the two variables with data types int and String, will be stored in the memory as shown below

int x = 72;
String msg = "Hello world";

Memory Variable
Data
Address Name
1001 num 72

1207 msg Address(1500)

: :

1500 "Hello world"


The primitive variables store the actual values, whereas reference variables store the addresses of the objects it
refer to.

Primitive Data Types and Values

Primitive data types are the simplest data types in a programming language. In Java, they are predefined and is
named by a keyword. The names of the primitive types are quite descriptive of the values that they can store.

Primitive data types in Java:


 boolean
 byte
 short
 int
 long
 float
 double
 char

The primitive data types can be categorized as:


 Boolean
 Numeric : integer and floating-point
 Character

JAVA Programming for Beginners


22 Java Basics

Primitive Data Types

Boolean Numeric Character

Integers Floating-point

boolean byte short int long float double char

Figure 4.1 Categorization of primitive data types.

Boolean has only one data type: boolean

Numeric defines two subcategories: integer and floating point

 Integer includes both negative and positive whole numbers


 byte
 short
 int
 long

 Floating point
 float
 double

Table 4.1 Numeric Data Types


Data Type Range of Values Storage Size
byte –128 to 127, inclusive 8 bits
short –32,768 to 32,767, inclusive 16 bits
int –2,147,483,648 to 2,147,483,647, inclusive 32 bits
long –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, inclusive 64 bits
float +/–1.4E–45 to +/–3.4028235E+38, +/–infinity, +/–0, NaN 32 bits
double +/–4.9E–324 to +/–1.7976931348623157E+308, +/–infinity, +/–0, NaN 64 bits

Character defines only one data type: char

JAVA Programming for Beginners


Java Basics 23

Variables represents values that may be changed in the program.

Declaring and Initializing Variables

Declaring variables tells the compiler to allocate appropriate memory space for the variable based on its data
type.

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 the rules for identifiers.

Syntax: <data type><name> [= initial value];

Note: For the syntax defined in this chapter and for the other chapters,
* - 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

Program 3.2 VariablesDemo.java

JAVA Programming for Beginners


24 Java Basics

Name: Year and Section: Date:

Activity

1.
Give 5 examples of valid identifiers Give 5 examples of invalid identifiers

2. Create a class named <YourFirstName>. The program should output on the screen:

Hi, I am <YourFirstName> and this is my first programming activity in Java.


Java programming is fun!!!

3. Given the table,, declare the following variables with the corresponding data types and initialize values.
Output to the screen the variable names together with the values.

Data Type Variable Name Initial Value


int intValue 20
double doubleValue 12.50
boolean isITMajor true
char letter A
String msg This is a Java program.

Expected output:

JAVA Programming for Beginners


CHAPTER 4

Operators
At the end of the lesson, you will be able to:
 Use Java operators
 Develop Java programs that perform simple computations
 Evaluate numeric expressions
26 Operators

Operators are special symbols that perform specific operations on one, two, or three operands, and then return
a result.

Table 4.1 Operator Types


Operator Type Operators Usage
Assignment =, +=, -=, *=, /= Assign value to a variable
Arithmetic +, -, *, /, %, ++, -- Add, subtract, multiply, divide, modulus, increment
and decrement
Relational <, <=, >, >=, ==, != Compare primitives
Logical !, &&, || Apply NOT, AND, and OR logic
Conditional ?: if-then-else statement

Assignment Operators

 = is the most frequently used operator; it assigns the value on its right to the operand on its left
 +=, -=, *=, and /= operators are short forms of addition, subtraction, multiplication and division with
assignment
 += can be read as "first add and then assign"
 -= can be read as "first subtract and then assign"
 *= can be read as "first multiply and then assign"
 /= can be read as "first divide and then assign"

If these operators are applied to two operands, x and y, they can be represented as follows:
x += y is equal to x = x + y
x -= y is equal to x = x – y
x *= y is equal to x = x * y
x /= y is equal to x = x / y

JAVA Programming for Beginners


Operators 27

Arithmetic Operators

Table 4.2 Arithmetic Operators


Operator Purpose Usage Answer
+ Addition 7 + 2 9
- Subtraction 7 – 5 2
* Multiplication 10 * 50 250
/ Division 5.0 / 2.5 2.0
% Modulus (remainder in division) 10 % 3 1

Program 4.1 ArithmeticDemo.java

JAVA Programming for Beginners


28 Operators

Numeric Type Conversion

Type Casting is an operation that converts a value of one data type into a value of another data type. Java
automatically perform type casting on binary operation involving two operands of different types based on
the following rules:
 If one of the operands is double, the other is converted into double.
 Otherwise, if one of the operands is float, the other is converted into float.
 Otherwise, if one of the operands is long, the other is converted into long.
 Otherwise, both operands are converted into int.

The range of numeric types increases in this order:

range increases
byte, short, int, long, float, double

Things to remember about numeric type conversion:


 It is valid to assign a value to a numeric variable whose type supports a larger range of values; thus, it
is valid to assign a long value to a float variable.
 It is not valid, however, to assign a value to a variable of a type with smaller range unless you use type
casting.

It is not valid to do casting to boolean data type. A character can be used as an int because each character
has a corresponding numeric code that represents its position in the character set.

The syntax for casting a type is to specify the target type in parentheses, followed by the variable's name or
the value to be casted.

Example:

double x = 10.7;
int y = (int) x; //the fractional part in x is truncated; y has a value of 10

JAVA Programming for Beginners


Operators 29

Increment and Decrement Operators


 ++ and -- are unary operators; they work with a single operand
 are used to increment or decrement the value of a variable by 1
 can also be used in prefix and postfix notation

In prefix notation, the operator appears before its operand. In postfix notation, the operator appears after
its operand. When these operators are not part of an expression, the postfix and prefix notations behave in
exactly the same manner.

The placement of the unary operator in an expression with respect to its operand decides whether its value
will increment or decrement before the evaluation of the expression or after the evaluation of the expression.
The evaluation of an expression starts from left to right.

For example,
int x = 5;
x = x++ + x + x-- - x-- + ++x;
x = 5 + 6 + 6 – 5 + 5;
x = 17

Table 4.3 Increment and Decrement Operators


Operator Purpose Description Example (assume i = 10)
++var preIncrement Increment var by 1, and use the int j = ++i;
new var value in the statement // j is 11, i is 11
var++ postIncrement Increment var by 1, but use the int j = i++;
original var value in the statement // j is 10, i is 11
--var preDecrement Decrement var by 1, and use the int j = --i;
new var value in the statement // j is 9, i is 9
var-- postDecrement Decrement var by 1, and use the int j = i--;
original var value in the statement // j is 10, i is 9

Program 4.2 IncrementDecrementDemo.java

JAVA Programming for Beginners


30 Operators

Relational Operators
 are used to determine whether a primitive value is equal to, less than or greater than the other value

Table 4.4 Relational Operators


Operator Purpose Description (assume i = 1) Answer
< less than i < 0 false
<= less than or equal to i <= 0 false
> greater than i > 0 true
>= greater than or equal to i >= 0 true
== equal to i == 0 false
!= not equal to i != 0 true

Program 4.3 RelationalDemo.java

JAVA Programming for Beginners


Operators 31

Logical Operators
 are used to logically evaluate one or more expressions
 will yield a boolean value
 they exhibit "short-circuiting" behavior, which means that the second operand is evaluated only
if needed

Table 4.5 Truth Table of using Boolean Literal Values with Logical Operators
! (not) && (and) || (or)
!false = true false && false = false false || false = false
!true = false false && true = false false || true = true
true && false = false true || false = true
true && true = true true || true = true

Program 4.4 LogicalDemo.java

JAVA Programming for Beginners


32 Operators

Conditional Operators
 shorthand for an if-then-else statement
 also known as the ternary operator because it uses three operands
 used to evaluate boolean expressions

Syntax: booleanExpression ? valueIfTrue : valueIfFalse;

Program 4.5 ConditionalDemo.java

JAVA Programming for Beginners


Operators 33

Operator precedence defines the compiler's order of evaluation of operators so as to come up with an
unambiguous result.

Note: The operator on top has the highest precedence, and operators within the same group have the same precedence and
are evaluated from left to right.

Table 4.6 Operator Precedence


Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr !
multiplicative * / %
additive + -
relational < > <= >=
equality == !=
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %=

Parentheses are used to override the default operator precedence. If the expression defines multiple operators
use parentheses to evaluate in your desired order. The inner parentheses are evaluated prior to the outer ones.

For example, the given expression:

10 % 20 * 30 + 10 / 20

Is evaluated as,

(((10 % 20) * 30)) + (10 / 20)


((10 * 30)) + (0)
(300)

Note: Keep your expressions simple and use parenthesis to avoid confusion in evaluating mathematical operations.

JAVA Programming for Beginners


34 Operators

Name: Year and Section: Date:

Activity

1. Write a program that inputs three integers from the user and displays the sum, average, and product of the
numbers.

2. Write a program that determines and prints whether a given integer is odd or even. (Hint: Use ?: operator)

JAVA Programming for Beginners


CHAPTER 5

Control Statements
At the end of the lesson, you will be able to:
 Create and use control statements in a program
 Obtain input from the keyboard using the Scanner and JOptionPane classes
36 Control Statements

Ordinarily, the computer executes the instructions in the sequence in which they appear that is one after the
other. This flow of control can be modified using control statements. Control statements employ selection, loop,
and branching, enabling the program to conditionally execute particular blocks of code.

Selection statements allow the computer to decide between two or more different courses of action by testing
conditions that occur as the program is running.

Figure 5.1 Multiple flavors of the if statement.

As shown in Figure 5.1, condition1 and condition2 refer to a variable or an expression that must be
evaluated to a boolean value. In the figure, statement1, statement2, and statement3 refer to either a
single line of code or a code block.

JAVA Programming for Beginners


Operators and Control Statements 37

1. if statement executes the corresponding statement(s), if and only if the condition is true.

Syntax:

if (<booleanExpression>) {
<statement>*;
}

Program 5.1 IfDemo.java

Note: The booleanExpression used as a condition for theif statement can also include assignment operation.

JAVA Programming for Beginners


38 Control Statements

2. if-else statement executes a certain statement, if a condition is true, and a different statement, if
the condition is false.

Syntax:

if (<booleanExpression>) {
<statement>*;
}
else {
<statement>*;
}

Program 5.2 IfElseDemo.java

JAVA Programming for Beginners


Operators and Control Statements 39

3. if-else-if-else statement is an if-else statement in which, the else part defines another if
statement.

Program 5.3 IfElseIfDemo.java

JAVA Programming for Beginners


40 Control Statements

4. switch statement is used to compare the value of a variable with multiple values.

switch (<switchExpression>) {
case <value1>: <statement>*;
break;
case <value2>: <statement>*;
break;
. . .
case <valueN>: <statement>*;
break;
default: <statement-for-default>*;
}

Rules to remember when defining switch statement:


 The switchExpression must yield a value of char, byte, short, int, or String type and
must always be enclosed in parentheses.
 The value1, ..., and valueN must have the same data type as the value of the
switchExpression and it must be a constant or a literal.
 When the value in a case statement matches the value of the switchExpression, the
statements starting from this case are executed until either a break statement or the end of the
switch statement is reached.
 Keyword break is optional, it is used to end the switch statement
 The default case, which is also optional, can be used to perform actions when none of the specified
cases matches the switchExpression.
 The case statements are checked in sequential order, but the order of the cases (including the
default case) does not matter.

Program 5.4 SwitchDemo.java

JAVA Programming for Beginners


Operators and Control Statements 41

Loop statements allow a sequence of statements to be repeated a number of times.

1. while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true.
This loop checks the condition before it starts the execution of the statement.

Syntax :
while (<booleanExpression>) {
//loop body
<statement>*;
}

When executing, if the booleanExpression is evaluated to true, the loop body is executed. This will
continue as long as the expression evaluation is true; if its evaluation is false, the entire loop
terminates and the first statement after the while loop will be executed.

Program 5.5 WhileDemo.java

JAVA Programming for Beginners


42 Control Statements

2. do-while loop is used to repeatedly execute a set of statements until the condition that it uses
evaluates to false. This loop checks the condition after it completes the execution of all the statements
in its loop body. Since the condition is not tested until the end of the loop, the body of a do-while loop
is always executed at least once.

Syntax:
do {
//loop body
<statement>*;
} while (<booleanExpression>);

Program 5.6 DoWhileDemo.java

JAVA Programming for Beginners


Operators and Control Statements 43

3. for loop is usually used to execute a set of statements a fixed number of times usually used.

Syntax:
for (<initialization>; <booleanExpression>; <update>) {
//loop body
<statement>*;
}

Rules to remember and the flow of control in a for loop:


 An initialization block executes first and only once. A for loop can declare and initialize
multiple variables in its initialization block, but the variables it declare should be of the same type.
 The booleanExpression is evaluated once for each iteration before executing the
statements defined within the body of the loop. The for loop terminates when the
booleanExpression evaluates to false.
 A for loop can define exactly one termination condition.
 After the body of the for loop executes, the flow of control jumps back up to the update
statement. This updates any loop control variable. This statement can be left blank, as long as a
semicolon appears after the booleanExpression.
 The booleanExpression is now evaluated again. If it is true, the loop executes and the
process repeats itself (loop body, then update step, then booleanExpression). After the
booleanExpression becomes false, the for loop terminates.

Program 5.7 ForLoopDemo.java

JAVA Programming for Beginners


44 Control Statements

Branching statements are used to redirect the flow of program execution.

1. The break statement is used to exit—or break out of—the for, for-each, do, and do-while loops,
as well as switch constructs.

Program 5.8 BreakDemo.java

JAVA Programming for Beginners


Operators and Control Statements 45

2. The continue statement can be used to skip the current iteration of a for, while, or do-while
loop.

Program 5.9 ContinueDemo.java

3. The return statement exits from the current method, and control flow returns to where the method
was invoked.

Note: Methods will be discussed in Chapter 6.

JAVA Programming for Beginners


46 Control Statements

Reading Input from the Console

Reading input from the console enables the program to accept input from the user.

Using the Scanner Class


Java uses System.out to refer to the standard output device and System.in to the standard input device.
By default, the output device is the display monitor and the input device is the keyboard. To perform console
output, use the println method to display a primitive value or a String to the console. Console input is not
directly supported in Java, but the Scanner class can be used to create an object to read input from System.in
as follows:

Scanner <objRefVariable> = new Scanner(System.in);

Program 5.10 ScannerDemo.java

Table 5.1 Methods for Scanner Objects


Method Description
nextByte() Reads a byte type
nextShort() Reads a short type
nextInt() Reads an int type
nextFloat() Reads a float type
nextDouble() Reads a double type
next() Reads a String that ends before a whitespace character
nextLine() Reads a line of String

JAVA Programming for Beginners


Operators and Control Statements 47

Using the JOptionPane Class

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 a
message.

Program 5.11 InputFromKeyboard.java

This is the output:

Figure 5.2 Getting input using JOptionPane.

Figure 5.3 Input Aiah on the JOptionPane.

Figure 5.4 Showing a message using JOptionPane.

JAVA Programming for Beginners


48 Control Statements

Line 1 indicates that the class JOptionPane is imported from the javax.swing package.

Line 5, creates a JOptionPane input dialog, which will display a dialog box with a message, a text field and an
OK button as shown in Figure 5.2. This returns a String which will be saved in the name variable.

Line 6 creates a message stored in the msg variable.

Line 7 displays a dialog box which contains a message and an OK button as shown in Figure 5.4.

JAVA Programming for Beginners


Operators and Control Statements 49

Name: Year and Section: Date:

Activity

1. Write an application program that asks the user to enter two integers, obtains them from the user and displays
the larger number followed by the words "is larger". If the numbers are equal, print the message "These
numbers are equal".

2. Get a number as input from the user, and output the equivalent of the number in words. The number encoded
should range from 1-10. If the user inputs a number that is not within the range, the output will display,
"Invalid number".

To solve this problem, use:


 if-else statement
 switch statement

JAVA Programming for Beginners


50 Control Statements

3. Create a program that prints your name a hundred times. Do three versions of this program using a while
loop, a do-while loop, and a for-loop.

JAVA Programming for Beginners


CHAPTER 6

Arrays
At the end of the lesson, the student will be able to:
 Declare array reference variables, and create and process single-dimensional arrays
 Simplify programming using the enhanced for loop
 Declare array reference variables, and create and process two-dimensional arrays
52 Arrays

SINGLE - DIMENSIONAL ARRAY

Array is an object which stores a fixed-size sequential collection of elements of the same type. An array can store
a collection of primitive data types or a collection of objects.

Declaring Array Variables

Syntax: <dataType>[] <arrayRefVal>; // preferred way

or
<dataType> <arrayRefVal>[];

Note: In this chapter, [ ] is part of the syntax

Creating Arrays

You can create an array by using the new operator.

Syntax: <arrayRefVal> = new <dataType>[arraySize];

The above statement does two things:


1. It creates an array using new dataType[arraySize];
2. It assigns the reference of the newly created array to the variable arrayRefVal;

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be
combined in one statement,

<dataType>[] <arrayRefVal> = new <dataType>[arraySize];


or
<dataType> <arrayRefVal>[] = new <dataType>[arraySize];

Alternatively, it can also be created as follows:

<dataType>[] <arrayRefVar> = {<value0, value1,..., valueN>};

The array elements are accessed through index. Array indices are 0-based. It starts from 0 to
arrayRefVar.length - 1.

For example,

int[] myArray = new int[5];

This statement declares an array variable, myArray, creates an array of five elements of type int, and assigns
its reference to myArray. To assign values to the elements, use the syntax:

<arrayRefVal>[index] = <value>;

JAVA Programming for Beginners


Arrays 53

For example, the following code initializes the array.

myArray[0] = 10;
myArray[1] = 20;
myArray[2] = 30;
myArray[3] = 40;
myArray[4] = 50;

Program 6.1 ArrayDemo.java

Enhanced for loop also known as for-each loop is used to traverse the complete array sequentially without
using an index variable.

Syntax:

for (declaration : expression) {


<statement(s)>;
}

where,

declaration the newly declared block variable, which is of a type compatible with the
elements of the array be accessed
the variable will be available within the for block and its value would be
the same as the current array element

expression this evaluates the array you need to loop through


the expression can be an array variable or method call that returns an
array

JAVA Programming for Beginners


54 Arrays

Program 6.2 ArrayForEachDemo.java

Note: The code for(int num : myArray) can be read as "for each element num in myArray, do the following". Also,
the variable num must be declared as the same type as the elements in myArray.

Processing Single-Dimensional Arrays

Since all the elements in an array are of the same type and the size of the array is known, either for loop or
for-each loop is usually used when processing array elements.

Assume the array is created as follows:

double[] myArray = new double[10];

The following are some examples of processing arrays:


1. Initializing arrays with random values

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


myArray[i] = Math.random() * 100;
}

2. Printing arrays

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


System.out.print(myArray[i] + "");
}

For an array of the char[] type, it can be printed using one print statement. For example, the
following code displays Hello.

char[] greet = {'H', 'e', 'l', 'l', 'o'};


System.out.println(greet);

JAVA Programming for Beginners


Arrays 55

3. Summing all elements

double total = 0;
for (int i = 0; i < myArray.length; i++) {
total += myArray[i];
}

4. Finding the largest element

double max = myArray[0];


for (int i = 1; i < myArray.length; i++) {
if(myArray[i] > max)
max = myArray[i];
}

5. Finding the smallest index of the largest element

double max = myArray[0];


int indexOfMax = 0;
for(int i = 1; i < myArray.length; i++) {
if (myArray[i] > max) {
max = myArray[i];
indexOfMax = i;
}
}

JAVA Programming for Beginners


56 Arrays

MULTIDIMENSIONAL ARRAYS

A two-dimensional (or more) array is referred to as a multidimensional array. A two-dimensional array refers to
a collection of objects, where each of the objects is a one-dimensional array. Similarly, a three-dimensional array
refers to a collection of two-dimension arrays, and so on. A two-dimensional array does not need to be
symmetrical, and each of its rows can define different numbers of members.

Declaring Variables of Two-Dimensional Arrays

Syntax:

<dataType> [][] <arrayRefVar>;


or
<dataType> <arrayRefVar>[][];

For example,

int[][] twoDim;
or
int twoDim[][];

Creating Two-Dimensional Arrays

The syntax to create a two-dimensional array of 4 by 3 int values and assign it to twoDim is,

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

Alternatively, it can also be created as,

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

JAVA Programming for Beginners


Arrays 57

Program 6.3 TwoDimArrayDemo.java

An element in a two-dimensional array is accessed through a row and column index. As in a one-dimensional array,
the index for each subscript is of the int type and starts from 0, as shown in Figure 6.1.

column 0 column 1 column 2

twoDim[0,0] twoDim[0,1] twoDim[0,2]


row 0 1 2 3

twoDim[1,0] twoDim[1,1] twoDim[1,2]


row 1 4 5 6

twoDim[2,0] twoDim[2,1] twoDim[2,2]


row 2 7 8 9

twoDim[3,0] twoDim[3,1] twoDim[3,2]


row 3 10 11 12

Figure 6.1 Row and column indices of a two-dimensional array.

JAVA Programming for Beginners


58 Arrays

Processing Two-Dimensional Arrays

Suppose an array twoDim is created as follows:

int[][] twoDim = new int[10][10];

The following are some examples of processing two-dimensional arrays:


1. Initializing arrays with random int values between 0 and 99

for (int row = 0; row < twoDim.length; row++) {


for (int column = 0; column < twoDim[row].length; column++) {
twoDim[row][column] = (int)(Math.random() * 100);
}
}

2. Printing arrays

for (int row = 0; row < twoDim.length; row++) {


for (int column = 0; column < twoDim[row].length; column++) {
System.out.print(twoDim[row][column] + " ");
}
System.out.println();
}

3. Summing all elements

int total = 0;
for (int row = 0; row < twoDim.length; row++) {
for (int column = 0; column < twoDim[row].length; column++) {
total += twoDim[row][column];
}
}

4. Summing elements by column

for (int column = 0; column < twoDim[0].length; column ++) {


int total = 0;
for (int row = 0; row < twoDim.length; row++) {
total += twoDim[row][column];
System.out.println("Sum for column " + column + " is " + total );
}
}

JAVA Programming for Beginners


Arrays 59

Name: Year and Section: Date:

Activity

1. Create an array of Strings which are initialized to the 7 days of the week.
For example, String days[] = {"Monday", "Tuesday" ...};

Print the contents of the array.

2. Write a program that reads ten integers and display them in reverse order in which they were read.

JAVA Programming for Beginners


60 Arrays

3. Write a program that reads an unspecified number of scores and determines how many scores are above
or equal to the average and how many scores are below the average. A negative number will signify the
end of the input. The maximum score is 100.

JAVA Programming for Beginners


CHAPTER 7

Methods
At the end of the lesson, you will be able to:
 Define and call methods
 Create overloaded methods
 Pass variables in methods
 Call static methods
62 Methods

A method is a group of statements identified with a name. Methods can be used to organize, simplify and define
reusable codes.

Defining a Method

To define a method is to tell what the method is to do.

Syntax:

[modifier] <returnType> <methodName>(<parameter list>*) {


//method body
<statement>*;
}

Components of a method:
 Modifier which is optional, it defines the access type of the method. (Modifier will be discussed
thoroughly in Chapter 8)
 Return type is the data type of the value the method returns. Some methods can return a primitive value
or an object of any class, while some methods perform the desired operations without returning a value.
If the method does not return a value, the returnType is the keyword void.
 Method name is the actual name of the method.
 Method parameters or parameters are the variables that appear in the definition of a method and specify
the type and number of values that a method can accept.
 Method body contains a collection of statements that define what the method does.

Method signature is comprised of the method name and the parameter list.

Method arguments are the actual values that are passed to a method while executing it.

Parameter list refers to the type, order, and number of the parameters of a method.

Points to remember when defining method parameters:


 The method parameter can be a primitive type or a reference to an object.
 There is no limit on the number of method parameters that can be defined by a method.
 If a method doesn’t accept any parameter, the parentheses that follow the name of the method is
empty.
 Each method parameter must have an explicit type declared with its name.
 The method’s parameters are separated by commas.

Calling a Method

To execute a method is to call or invoke it. If a method returns a value, a call to the method is usually treated as
a value. If a method returns void, a call to the method must be a statement.

For example,
int result = sum(10, 20);

Invokes sum(10, 20) and assigns the result of the method to the variable sum.

JAVA Programming for Beginners


Methods 63

Another example of a call that is treated as a value is

System.out.println(sum(10, 20));

A call to a void method must be a statement. For example, the method println returns void.

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

When a program calls a method, program control is transferred to the called method. After the method has
finished execution, it goes back to the method that called it.

Program 7.1 MethodDemo.java

The return statement is used to exit from a method, with or without a value. The methods that don’t return a
value (return type is void) are not required to define a return statement. But it is valid to use the return
statement in a method even if it doesn’t return a value. This is usually used to define an early exit from a method.

Rules to remember when defining a return statement:


 For a method that returns a value, the return statement must be followed immediately by a value.
 For a method that doesn’t return a value (return type is void), the return statement must not be
followed by a return value.
 The return statement must be the last statement to execute in a method.

JAVA Programming for Beginners


64 Methods

Overloaded methods are methods with the same name but different method parameter lists. The compiler
determines which method is used based on the method signature.
Rules to remember for defining overloaded methods:
 Overloaded methods must have different method parameters from one another.
 Overloaded methods may or may not define a different return type.
 Overloaded methods may or may not define different access modifiers.
 Overloaded methods can’t be defined by only changing their return type or access modifiers.

Overloaded methods accept different lists of arguments. The argument lists can differ in terms of any of the
following:
 Change in the number of parameters that are accepted.
 Change in the types of parameters that are accepted.
 Change in the positions of the parameters that are accepted (based on parameter type, not variable
names).

Program 7.2 MethodOverloadingDemo.java

JAVA Programming for Beginners


Methods 65

Passing Variables in Methods

There are two types of passing data to methods, pass-by-value and pass-by-reference.

Pass-by-value
When a pass-by-value occurs, the value of the argument is passed to the parameter. If the argument is a variable
rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected,
regardless of the changes made to the parameter inside the method.

Program 7.3 PassByValueDemo.java

By default, all primitive data types when passed to a method are pass-by-value.

JAVA Programming for Beginners


66 Methods

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.

Program 7.4 PassByReferenceDemo.java

JAVA Programming for Beginners


Methods 67

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.

Syntax:

Classname.staticMethodName(parameter);

What can a static method access?

Neither static methods nor static variables can access the non-static variables and methods of a class. But the
reverse is true: non-static variables and methods can access static variables and methods because the static
members of a class exist even if no instances of the class exist. Static members are prohibited from accessing
instance methods and variables, which can exist only if an instance of the class is created.

JAVA Programming for Beginners


68 Methods

Name: Year and Section: Date:

Activity

1. Write a class that contains the following two methods:

/** Convert from Celsius to Fahrenheit */


public static double celsiusToFahrenheit(double celsius)

/** Convert from Fahrenheit to Celsius */


public static double fahrenheitToCelsius(double fahrenheit)

The formula for the conversion is:


fahrenheit = (9.0 / 5) * celsius + 32
celsius = (5.0 / 9) * (fahrenheit – 32)

Test your program by invoking these methods.

JAVA Programming for Beginners


CHAPTER 8

Classes and Objects


At the end of the lesson, you will be able to:
 Define object-oriented programming and some of its concepts
 Differentiate between classes and objects
 Define classes, instance and class variables, and constructors
 Encapsulate data fields
 Declare static methods
 Create objects and access object’s data and methods
 Use the keyword this to access instance variable
 Use the this() constructor call
 Apply access modifiers
70 Classes and Objects

Programs must be designed carefully. Software engineering is concerned with the construction of correct,
working, well-written programs. Software engineers try to use accepted and proven methods for analyzing the
problem to be solved and for designing a program to solve that problem.

The latest software engineering methodology is called object-oriented programming (OOP). OOP involves
programming using objects. In the software world, an object is a software component whose structure is similar
to objects in the real world. The objects in the physical world can easily be modelled as software objects using the
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 zoo software for kids.

 The property of an object, also known as its state, is represented by instance variables or data fields with
their current values that describe the essential characteristics of the object.

 The behavior of an object is defined by methods that describe how an object behaves.

A class allows you to define new data types similar to the built-in types such as int and char. It serves as a
template, a prototype or blue print that defines the data fields and methods of an object. Object is an instance of
a class. Objects of the same type are defined using a common class. Creating an instance is referred to as
instantiation.

Classes provide the benefit of reusability. You can instantiate a class over and over again to create many objects.
Just as you can bake as many chocolate cakes as you want from a single chocolate cake recipe.

Defining Classes

Classes are definitions for objects and objects are created from classes.

Syntax:
<modifier>class<name>{
<instanceVariableDeclaration>*
<constructorDeclaration>*
<methodDeclaration>*
}

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

To create a Student class, write:

public class Student{


//we'll add more code here later
}

where,
public makes the class accessible to other classes outside the package
class is the keyword used to create a class
Student is the name of the class; a unique identifier

JAVA Programming for Beginners


Classes and Objects 71

Declaring Instance Variables

Syntax:

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

Add the following instance variables in your class,

private String name;


private int age;

where,

private make the variables accessible only within the class

Class Variables or Static Variables

Class variables are defined by using the keyword static. The value of these variables are the same for all the
objects of the same class.

To declare a static variable that will hold the total number of students for the whole class write,

private static int studentCount = 0;

With data fields and a static variable, your class will now looks like this,

Declaring Constructors

A class provides methods of a special type, known as constructors that are used for creating and initializing a new
object. Constructors have the same name as the name of the class in which they are defined, and they do not
specify a return type—not even void.

Types of constructors:
 User-defined constructors
 Default constructors

User-defined constructor is a constructor defined by the programmer. A constructor is called as soon as an


object is created, so you can use it to assign default values to the instance variables of your class. Because a

JAVA Programming for Beginners


72 Classes and Objects

constructor is a method, you can also pass method parameters to it. Constructors can also be overloaded. You
can define a constructor using all access modifiers (access modifiers will be discussed later).

A constructor must not define any return type. Instead, it creates and returns an object of the class in which
it's defined. If a return type is defined for a constructor, it will be treated as a regular method, even though it
shares the same name as its class.

Default constructor is automatically inserted by Java in the absence of a user-defined constructor. This
constructor doesn't accept any method arguments. When a class is later modified by adding a constructor to
it, the Java compiler will remove the default, no-argument constructor that it initially added to the class.

Rules to remember for defining and using overloaded constructors:


 Overloaded constructors must be defined using different argument lists.
 Overloaded constructors may be defined using different access modifiers.
 Overloaded constructors can't be defined by just a change in the access modifiers.
 A constructor can call another overloaded constructor by using the keyword this.
 A constructor can't invoke a constructor by using its class's name.
 If present, the call to another constructor must be the first statement in a constructor.

As mentioned, constructors can also be overloaded, for example,

JAVA Programming for Beginners


Classes and Objects 73

Encapsulation is the concept of hiding certain elements of the implementation of a certain class. By placing a
boundary around the instance variables and methods, this prevent the programs from having their variables
changed in unexpected ways.

To implement encapsulation, the instance variables should be declared as private. The private members of a
class—its instance variables and methods—are used to hide information about a class. To access private data,
accessor methods are created.

Accessor method or getter method is used to retrieve the value of a variable (instance/static). It also returns a
value.

Accessor method are usually named as,

get<instanceVariable>

To implement one accessor method that can read the name of the Student,

public class Student {


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; it means that the method should return a value of
type String
getName is the name of the method
() the method has no parameter

The statement,

return name;

signify that the method will return the value of the instance variable name to the calling method. The return type
of the method should have the same data type as the data in the return statement.

JAVA Programming for Beginners


74 Classes and Objects

Mutator method or setter method is used to set the value of a variable.

A mutator method is usually written as,

set <instanceVariable>

To implement one mutator method,

public class Student{


private String name;
.
.
.
public void setName(String newName) {
name = newName;
}
}

where,
public means that the method can be called from objects outside the class
void means that the method does not return any value
setName is the name of the method
(String newName) is a parameter; it will be used inside the method

The statement,

name = newName;

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

Declaring Static Methods


For the static variable studentCount, a static method can be created to access its value.

public class Student{


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]
int is the return type of the method
getStudentCount is the name of the method
() the method has no parameter

JAVA Programming for Beginners


Classes and Objects 75

The code for the Student class,

Program 8.1 Student.java

JAVA Programming for Beginners


76 Classes and Objects

Creating Objects

Objects are accessed via the object's reference variables, which contain references to the objects.

Syntax:

ClassName objectRefVar;

Since in Java, a class is a type, a class name can be used to specify the type of a variable in a declaration statement,
or the type of a parameter, or the return type of a method. The following statement declares the variable stud
to be of Student type:

Student stud;

However, declaring a variable does not create an object. In Java, no variable can hold an object. A variable can
only hold a reference to an object. A reference to an object is the address of the memory location where the
object is stored. When you use a variable of object type, the computer uses the reference in the variable to find
the actual object.

The new operator, creates an object and returns a reference to that object.

The variable stud can reference a Student object. The next statement creates an object and assigns its reference
to stud:

stud = new Student();

The declaration of an object reference variable, the creation of an object, and the assigning of an object reference
to the variable can be combined in a single statement.

Syntax:

<ClassName> <objectRefVar> = new <ClassName>();

For example,

Student stud = new Student();

JAVA Programming for Beginners


Classes and Objects 77

Accessing an Object's Data and Methods

An object’s data and methods can be accessed through the dot (.) operator via the object's reference variable.
The dot operator (.) is also known as the object member access operator.

 objectRefVar.instanceVariable references an instance variable in the object.


 objectRefVar.method(arguments) invokes a method on the object.

For example, stud.name references the name in stud, and stud.getName() invokes the getName()
method on stud.

To test Student class, create TestStudent class,

Program 8.2 TestStudent.java

JAVA Programming for Beginners


78 Classes and Objects

The this Reference

The this reference is used to access the instance variables shadowed by the parameters.

Suppose the following declaration for setAge,

public void setAge(int age){


age = age; //this is WRONG
}

is wrong because the parameter name 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;

the value of the parameter age is being assigned to itself. To correct this, the this reference is used.

this.<nameOfTheInstanceVariable>

You can now rewrite your 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 Student.

NOTE: The this reference can only be used for instance variables and NOT to static or class variables.

JAVA Programming for Beginners


Classes and Objects 79

The this() Constructor Call

Constructor calls can be chained, which means that you can call another constructor from inside another
constructor. To do this, use the this() call. For example, given the following code,

when the statement at line 10 is called, it will call the default constructor in line 1. When statement in line 2 is
executed, it will then call the constructor that has a String parameter in line 5.

Rules to remember when using the this constructor call:


 When using the this constructor call, it must be the first statement in a constructor.
 It can only be used in a constructor definition.
 The this call can then be followed by any other relevant statements.

JAVA Programming for Beginners


80 Classes and Objects

Access Modifiers

Access modifiers control the accessibility of a class and its members. Access modifiers cannot be applied to local
variables and method parameters. An attempt to do this will cause compilation error.

Java defines four access modifiers:


 public
 protected
 default (no modifier)
 private

1. public
 the least restrictive access modifier
 classes and its members that are defined using the public access modifier are accessible to
anyone, both inside and outside the class

2. protected
 members of a class that are defined using the protected access modifier are accessible only to
methods in that class and the subclasses of the class

3. default access or package access


 The members of a class that are defined without using any explicit access modifier are defined
with package accessibility (also called default accessibility
 members with package access are only accessible to classes defined in the same package

4. private
 the most restrictive access modifier
 the class members are only accessible to the class they are defined in

package p1; package p2;


public class Class1 { public class Class2 { public class Class3 {
public int x; void aMethod() { void aMethod() {
int y; Class1 c1 = new Class1(); Class1 c1 = new Class1();
private int z; can access c1.x; can access c1.x;
can access c1.y; cannot access c1.y;
public void m1() { cannot access c1.z; cannot access c1.z;
}
void m2() { can invoke c1.m1(); can invoke c1.m1();
} can invoke c1.m2(); cannot invoke c1.m2();
private void m3() { cannot invoke c1.m3(); cannot invoke c1.m3();
} } }
} } }

Figure 8.1 The use of access modifiers.

JAVA Programming for Beginners


Classes and Objects 81

If a class is not declared public, it can be accessed only within the same package, as shown in below.

package p1; package p2;


class Class1 { public class Class2 { public class Class3 {
... can access Class1; cannot access Class1;
} } can access Class2;
}

Figure 8.2 A non-public class has package-access.

Table 8.1 Access Modifiers on Instance Variables and Methods


Subclass in a
Different
Modifier Same Class Same Package Different
Package
Package
public    
protected    –
default (no modifier)   – –
private  – – –

JAVA Programming for Beginners


82 Classes and Objects

Name: Year and Section: Date:

Activity

1. Create a class that contains an address book entry. The table below describes the information that an
address book entry has.

Properties Description
name name of the person in the address book
address address of the person
contact number contact number of the person
email address persons’ email address

The class should contain accessor and mutator methods for all the attributes. Also, provide the necessary
constructors.

2. Create a class address book that can contain 100 entries of the address book entry objects (use the class
you created in the first exercise). You should provide the following methods for the address book.
 Add entry
 Delete entry
 View all entries
 Update an entry

JAVA Programming for Beginners


CHAPTER 9

Inheritance and Polymorphism


At the end of the lesson, you will be able to:
 Apply inheritance
 Define superclasses and subclasses
 Call superclass constructors
 Override methods of superclasses
 Create final methods and final classes
 Apply polymorphism
84 Inheritance and Polymorphism

Inheritance is an important and powerful feature for reusing software. It enables a class to inherit the properties
and methods of an existing class. In Java, all classes, including the classes that make up the Java API, are subclassed
from the Object superclass.

Any class above a specific class in the class hierarchy is known as a superclass. While any class below a specific
class in the class hierarchy is known as a subclass of that class.

Object

Class A Class D

Class B Class C
Figure 9.1 Class hierarchy.

Defining Superclasses and Subclasses

The inheritance relationship enables a subclass to inherit features from its superclass with additional new
features. A subclass is a specialization of its superclass; every instance of a subclass is also an instance of its
superclass, but not vice versa. For example, every Student is a Person object, but not every Person object
is a Student. Therefore, you can always pass an instance of a subclass to a parameter of its superclass type.

To derive a class, use the extends keyword. To illustrate this, create a sample parent class called Person.

JAVA Programming for Beginners


Inheritance and Polymorphism 85

Program 9.1 Person.java

The properties name and address are declared as protected. This is to make them accessible by the
subclasses of the superclass.

Now, create another class named Student. Since a student is also a Person, just extend the class Person,
so that you can inherit all the properties and methods of the existing class Person. To do this, 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 executed. To illustrate this,
consider the following code,

JAVA Programming for Beginners


86 Inheritance and Polymorphism

public static void main(String[] args){


Student aiah = new Student();
}

The code above, creates an object of class Student. The output of the program is,

Inside Person:Constructor
Inside Student:Constructor

Calling Superclass Constructors

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 a
relevant constructor from the superclass, based on the arguments that were passed.

Syntax:

super(), or super(parameters);

For example, given the previous example classes Person and Student, show an example of a super
constructor call.

Given the following code for Student,

public Student(){
super("studentName", "studentAddress");
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 Person and executes it.

Things to remember when using the super constructor call:


 The super() call must be the first statement in a constructor.
 The super() call can only be used in a constructor definition.
 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).

JAVA Programming for Beginners


Inheritance and Polymorphism 87

For example,

public Student() {
super.name = "some name";
super.address = "some address";
}

Overriding Methods

A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to provide a new
implementation of a method defined in the superclass. This is referred to as method overriding. To override
a method, the method must be defined in the subclass using the same signature and the same return type as
in its superclass.

public class Person {


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

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

public class Student extends Person {


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

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

Student: getName

JAVA Programming for Beginners


88 Inheritance and Polymorphism

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, add the final keyword in the class declaration. For example, the class
Person to be declared final, write,

public final class Person


{
//some code here
}

It is also valid to create methods that cannot be overridden. These methods are called final methods. To
declare a method to be final, add the final keyword in the method declaration. For example, if you want
the getName method in class Person to be declared final, write,

public final String getName(){


return name;
}

Static methods are automatically final. This means that you cannot override them.

The three pillars of object-oriented programming are encapsulation, inheritance, and polymorphism. The first two
concepts was already discussed. The next section introduces polymorphism.

JAVA Programming for Beginners


Inheritance and Polymorphism 89

Polymorphism (from a Greek word meaning "many forms") means that a variable of a supertype can refer to a
subtype object. A type defined by a subclass is called a subtype, and a type defined by its superclass is called a
supertype.

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 9.1 Hierarchy for Person class and its subclasses.

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

public static void main(String[] args) {


Person personRef;
Student studentObject = new Student();
Employee employeeObject = new Employee();
personRef = studentObject; //Person personRef points to a Student object
//some code here
}

Suppose you have a getName method in your superclass Person, and you 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;
}
}

JAVA Programming for Beginners


90 Inheritance and Polymorphism

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

public static void main(String[] args) {


Person personRef;

Student studentObject = new Student();


Employee employeeObject = new Employee();

personRef = studentObject; //Person reference points to a student object

String temp = personRef.getName(); //getName of Student


System.out.println(temp);

personRef = employeeObject; //Person reference points to an Employee object


String temp = personRef.getName(); //getName of Employee
System.out.println(temp);
}

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 you try to pass a reference to methods.
Suppose you have a static method printInformation that takes in a Person object as reference, you 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 void main(String[] args) {


Student studentObject = new Student();
Employee employeeObject = new Employee();
printInformation(studentObject);
printInformation(employeeObject);
}

public static printInformation(Person p){


....
}

JAVA Programming for Beginners


Inheritance and Polymorphism 91

Name: Year and Section: Date:

Activity

1. Create a more specialized student record that contains additional information about an Information
Technology student. Your task is to extend the Student class that was implemented in the previous
chapter. Add some data fields and methods that you think are needed for an Information Technology
student record. Try to override some existing methods in the superclass Student, if you really need to.

JAVA Programming for Beginners


92 Inheritance and Polymorphism

This page is intentionally left blank

JAVA Programming for Beginners


CHAPTER 10

Basic Exception Handling


At the end of the lesson, you will be able to:
 Define exceptions
 Differentiate among checked exceptions, runtime exceptions, and errors
 Use try-catch-finally blocks to handle exceptions
 Throw exceptions using the throw and throws keywords
94 Basic Exception Handling

An exception is an event that interrupts the normal processing flow of a program. This event can occur for
many different reasons, including the following:

 A user has entered invalid data.


 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and still others by physical
resources that have failed in some manner. If these exceptions are not handled properly, the program will
terminate abnormally. Exception handling enables a program to deal with exceptional situations and continue its
normal execution.

Exceptions are objects, and objects are defined using classes. The Throwable class is the root of exception
classes.

java.lang.Object

java.lang.Throwable

java.lang.Error java.lang.Exception

java.lang.RuntimeException

Figure 9.1 Class hierarchy of exception categories.

Categories of Exceptions

1. Checked Exceptions are represented in the Exception class, which describes errors caused by your
program and by external circumstances. These errors can be caught and handled by your program.

Examples of subclasses are:


 ClassNotFoundException
 FileNotFoundException
 IOException

2. Runtime Exceptions also known as unchecked exceptions are represented in the


RuntimeException class. Runtime exceptions are generally thrown by the JVM. These occur from
inappropriate use of another piece of code.

JAVA Programming for Beginners


Basic Exception Handling 95

Examples of subclasses are:


 ArithmeticException
 NullPointerException
 ArrayIndexOutOfBoundsException
 IndexOutOfBoundsException

3. Errors are thrown by the JVM and is represented in the Error class. The Error class describes
internal system errors, though such errors rarely occur. If one does, there is little you can do beyond
warning the user and trying to terminate the program gracefully.

Examples of subclasses of are:


 VirtualMachineError
 StackOverflowError
 LinkageError.

Java does not mandate writing the code to catch or declare runtime exceptions and errors.

To handle exceptions in Java, a try-catch-finally block is used. The try block contains the code that is
executed in normal circumstances. If no exceptions arise during the execution of the try block, the catch blocks
are skipped and proceeds with the rest of the program. The exception is caught by the catch block. The code in
the catch block is executed to handle the exception so as not to let the program crash. The code in the
finally block is executed under all circumstances, regardless of whether an exception occurs in the try block
or is caught.

Syntax:

try {
// statements that may throw exceptions
}
catch (<Exception1 exVar1>){
// handler for exception1
}
. . .
catch (<ExceptionVarN>){
//handler for exceptionN
}
finally {
// final statements
}

JAVA Programming for Beginners


96 Basic Exception Handling

Rules to remember about the syntax of the try-catch-finally construct:


 A try block can be followed by one or more catch blocks.
 The catch blocks must be followed by zero or one finally block.
 The finally block executes regardless of whether the code in the try block throws an
exception.
 A try block can’t define multiple finally blocks.
 A try block may be followed by either a catch or a finally block or both.
 None of the try, catch, and finally blocks can exist independently.
 The finally block can’t appear before a catch block.
 The order in which the catch blocks are placed matters. If the caught exceptions have an
inheritance relationship, the base class exceptions can’t be caught before the derived class
exceptions. An attempt to do this will result in compilation failure.
 A try, catch, or finally block can define another try-catch-finally block. There is
no limit on the allowed level of nesting of try-catch-finally blocks.

Program 10.1 ExceptionHandlingDemo.java

JAVA Programming for Beginners


Basic Exception Handling 97

Throwing Exceptions

The throw Keywords


Aside from catching exceptions, Java also allows user program to throw exceptions. The keyword to throw an
exception is throw.

Syntax: throw <exception object>;

An exception may be thrown directly by using a throw statement in a try block, or by invoking a method that
may throw an exception.

Program 9.2 ExceptionHandlingDemo.java

JDK 7 has multi-catch feature to simplify coding for the exceptions with the same handling code.

Syntax:
catch(<Exception1> | <Exception2> | <...> | <ExceptionN ex>) {
// same code for handling these exceptions
}

Each exception type is separated from the next with a vertical bar (|). If one of the exceptions is caught, the
handling code is executed.

JAVA Programming for Beginners


98 Basic Exception Handling

The throws Keyword

In the case that a method can cause an exception but does not catch it, then the method must declare it using the
throws keyword. This rule only applies to checked exceptions.

Syntax:

[modifier]<returnType><methodName>(<parameterList>)throws <exceptionList> {
<methodBody>
}

A method is required to either catch or list all exceptions it might throw, but it may omit those of type Error or
Runtime Exception, or their subclasses.

For example:

public void myMethod() throws IOException

The throws keyword indicates that myMethod might throw an IOException. If the method might throw
multiple exceptions, add a list of the exceptions, separated by commas, after throws:

public void myMethod()


throws Exception1, Exception2, ..., ExceptionN

Program 9.3 StudentWithException.java

JAVA Programming for Beginners


Basic Exception Handling 99

Program 9.4 TestStudentWithException.java

JAVA Programming for Beginners


References

1. Balagtas, F. T. (2006). Introduction to Programming I (ver. 1.3). Java Education & Development
Initiative: Philippines

2. Deitel, P. J. & Deitel, H. M. (2012). Java How to Program (9th ed.). PrinticeHall:USA.

3. Eck, D. J. (2014). Introduction to Programming using Java (ver. 7.0). Retrieved from
http://math.hws.edu/javanotes/

4. Gupta, M. (2013). OCA Java SE 7 Programmer I Certification Guide. Manning Publications Co.:USA.

5. Liang, D. Y. (2015). Introduction to Java Comprehensive Version. PrinticeHall:USA.

6. http://docs.oracle.com/javase/tutorial.html

7. http://www.oracle.com/technetwork/java/javase/downloads/Index.html

8. http://www.textpad.com/download/#downloads8

9. http://facweb.cs.depaul.edu/noriko/javasetup/

You might also like