Java Programming For Beginners by JA Villaruz
Java Programming For Beginners by JA Villaruz
for Beginners
Jolitte Alinsog-Villaruz
Philippine Copyright 2019
by
Jolitte Alinsog-Villaruz
and
Aklan State University
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 [email protected].
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.
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.
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.
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
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.
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)
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.
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
2. Select the version and click on 32 or 64-bit as appropriate to start your download.
4. Open the folder and run Setup.exe and follow the instructions.
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.
1. Start TextPad.
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.
7. Do the same for Run Java Application, in Parameters box looks like ""-classpath . $BaseName".
9. You are now ready to start working with your first Java program.
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
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. 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.
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.
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.
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);
}
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 Language Keywords or Reserved words are words that have specific meaning to the compiler and cannot be
used for other purposes in the program.
Identifiers are words given by programmers to name programming entities such as variables, constants, methods,
classes, and packages.
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.
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
For example,
//The number 12, in decimal
int decVal = 12;
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)
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.
5. String Literals
Represent multiple characters and are enclosed by double quotes such as "Hello world!"
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
: :
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.
Integers Floating-point
Floating point
float
double
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.
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
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:
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.
Expected output:
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.
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
Arithmetic Operators
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.
range increases
byte, short, int, long, float, double
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
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
Relational Operators
are used to determine whether a primitive value is equal to, less than or greater than the other value
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
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
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.
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.
10 % 20 * 30 + 10 / 20
Is evaluated as,
Note: Keep your expressions simple and use parenthesis to avoid confusion in evaluating mathematical operations.
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)
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.
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.
1. if statement executes the corresponding statement(s), if and only if the condition is true.
Syntax:
if (<booleanExpression>) {
<statement>*;
}
Note: The booleanExpression used as a condition for theif statement can also include assignment operation.
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>*;
}
3. if-else-if-else statement is an if-else statement in which, the else part defines another if
statement.
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>*;
}
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.
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>);
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>*;
}
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.
2. The continue statement can be used to skip the current iteration of a for, while, or do-while
loop.
3. The return statement exits from the current method, and control flow returns to where the method
was invoked.
Reading input from the console enables the program to accept input from the user.
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.
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 7 displays a dialog box which contains a message and an OK button as shown in Figure 5.4.
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".
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.
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
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.
or
<dataType> <arrayRefVal>[];
Creating Arrays
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be
combined in one statement,
The array elements are accessed through index. Array indices are 0-based. It starts from 0 to
arrayRefVar.length - 1.
For example,
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>;
myArray[0] = 10;
myArray[1] = 20;
myArray[2] = 30;
myArray[3] = 40;
myArray[4] = 50;
Enhanced for loop also known as for-each loop is used to traverse the complete array sequentially without
using an index variable.
Syntax:
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
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.
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.
2. Printing arrays
For an array of the char[] type, it can be printed using one print statement. For example, the
following code displays Hello.
double total = 0;
for (int i = 0; i < myArray.length; i++) {
total += myArray[i];
}
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.
Syntax:
For example,
int[][] twoDim;
or
int twoDim[][];
The syntax to create a two-dimensional array of 4 by 3 int values and assign it to twoDim is,
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.
2. Printing arrays
int total = 0;
for (int row = 0; row < twoDim.length; row++) {
for (int column = 0; column < twoDim[row].length; column++) {
total += twoDim[row][column];
}
}
Activity
1. Create an array of Strings which are initialized to the 7 days of the week.
For example, String days[] = {"Monday", "Tuesday" ...};
2. Write a program that reads ten integers and display them in reverse order in which they were read.
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.
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
Syntax:
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.
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.
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.
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.
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).
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.
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.
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);
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.
Activity
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
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
Syntax:
<modifier><type><name>[=<default_value>];
where,
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,
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
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.
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.
get<instanceVariable>
To implement one accessor method that can read the name of the Student,
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.
set <instanceVariable>
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.
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
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:
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:
For example,
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.
For example, stud.name references the name in stud, and stud.getName() invokes the getName()
method on stud.
The this reference is used to access the instance variables shadowed by the parameters.
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>
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.
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.
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.
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
4. private
the most restrictive access modifier
the class members are only accessible to the class they are defined in
If a class is not declared public, it can be accessed only within the same package, as shown in below.
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
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.
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.
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,
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,
The code above, creates an object of class Student. The output of the program is,
Inside Person:Constructor
Inside Student:Constructor
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.
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.
Another use of super is to refer to members of the superclass (just like the this reference).
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.
To invoke the getName method of an object of class Student, the overridden method would be called,
and the output would be,
Student: getName
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,
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,
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.
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,
Suppose you have a getName method in your superclass Person, and you override this method in both the
subclasses Student and Employee,
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.
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.
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.
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:
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
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.
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.
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
}
Throwing Exceptions
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.
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.
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:
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:
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.
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/