Académique Documents
Professionnel Documents
Culture Documents
Introduction to Java
Java Background
Java was developed in 1991 by a team of engineers called the “Green
Team” led by James Gosling and released in 1995 by Sun
Microsystems. It was initially called oak after an oak tree that stood
outside his office. Java was originally designed to use in embedded
chips in various consumer electronic appliances such as toasters and
refrigerators. In 1995 its name was changed to Java because a
trademark search revealed that Oak was used by Oak Technology and
it was also redesigned for developing Web applications. All the Java
releases since 2010 is owned by Oracle because they acquire Sun
Microsystems in that year.
Computer Programming 2 1
Week 3-4 Administering Users and Roles
The first phase of a java program is writing your source code in a text
editor or IDE (Integrated Development Environment). The text editors
that can be used are notepad, vi, sublime, etc. and for the IDE are
NetBeans, Eclipse, BlueJ, etc. The written code should be saved with
the .java extension.
2
MODULE OF INSTRUCTION
After creating the source file, you need to compile it using the javac
compiler. This process will produce a compiled file containing
bytecodes and with the extension name of .class. Normally the
compiler (other programming language like C, C++, etc.) should
produce object code (executable program) that is understandable by
the processor, however in Java the compiled object is a .class file
which contains bytecode that is not readable by your processor.
Java Features
The main reason why they created Java was to deliver a portable and
secured programming language. In addition to these major features,
other Java features are the following:
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. High Performance
10. Multithreaded
11. Distributed
Computer Programming 2 3
Week 3-4 Administering Users and Roles
Simple
Object Oriented
4
MODULE OF INSTRUCTION
Platform Independent
Code Security
Computer Programming 2 5
Week 3-4 Administering Users and Roles
Robust
Architecture-neutral
6
MODULE OF INSTRUCTION
Portable
Dynamic
High Performance
Computer Programming 2 7
Week 3-4 Administering Users and Roles
Multithreaded
Distributed
LESSON SUMMARY:
8
MODULE OF INSTRUCTION
Computer Programming 2 9
MODULE OF INSTRUCTION
In this section we are going to write, compile and run a Java program
in Text Editor and Command Line. We are going to create a simple
program that will display the words “Hello World!”. Below is the
source code of our first program:
public class HelloWorld{
public static void main(String args[]){
System.out.println("Hello World!");
}
}
Before we can run any Java program, we will need the following:
Let’s start creating the “Hello World” program. The following are the
steps to create the program:
Computer Programming 2 1
Week 2 Getting to know the programming environment
2
MODULE OF INSTRUCTION
To save the file in notepad, on the menu bar, click file then select
"save as".
Computer Programming 2 3
Week 2 Getting to know the programming environment
The Save dialog box will show up, navigate to drive C and then select
the folder that you created a while ago.
On the file name input box, enter "HelloWorld.java" and change the
"Save as type" to "All Files" and then click save.
4
MODULE OF INSTRUCTION
The first thing that we need to do to compile the source code is launch
the command prompt, click the start menu and on search bar type
command or cmd.
When the command prompt open up, by default it will take you to the
current user directory. In the example below the default directory is in
Administrator.
Computer Programming 2 5
Week 2 Getting to know the programming environment
We need to navigate to the folder where the Java source code was
saved or we need to go to “C:\JAVAPROGRAMS”. On the command
line type “cd C:\JAVAPROGRAMS” then press enter. You are now
inside the JAVAPROGRAMS directory. The “cd” command stands
for change directory; it is used to change the current directory.
Let us check whether we are in the right directory and see if the Java
source file was saved in this directory. On the command line type “dir”
then press enter, your Java source file should be displayed. “dir”
command is used to display files and subdirectories inside a directory.
6
MODULE OF INSTRUCTION
Computer Programming 2 7
Week 2 Getting to know the programming environment
8
MODULE OF INSTRUCTION
There are two ways to set Java path, one is temporary and other one is
permanent.
Computer Programming 2 9
Week 2 Getting to know the programming environment
10
MODULE OF INSTRUCTION
Computer Programming 2 11
Week 2 Getting to know the programming environment
12
MODULE OF INSTRUCTION
Computer Programming 2 13
Week 2 Getting to know the programming environment
B. Errors
14
MODULE OF INSTRUCTION
Syntax errors
Runtime errors
Logical errors
Syntax Errors
The errors occur when the syntax of the language is
violated, specifically when a word or symbol was not correctly
placed in an instruction or statement of the program.
Computer Programming 2 15
Week 2 Getting to know the programming environment
Runtime Errors
16
MODULE OF INSTRUCTION
Logical Errors
Computer Programming 2 17
Week 2 Getting to know the programming environment
18
MODULE OF INSTRUCTION
Using NetBeans
In our previous discussion, we tackled the hard way of
running Java program. Let’s now try the easiest way of
writing and running the Java program.
Computer Programming 2 19
Week 2 Getting to know the programming environment
20
MODULE OF INSTRUCTION
Computer Programming 2 21
Week 2 Getting to know the programming environment
22
MODULE OF INSTRUCTION
Since you have left the Create Main Class checked in the
New Application dialog the NetBeans IDE have generated
HelloWorld.java file that contains code that is shown in the
source code editor window.
System.out.println(“Hello World!”);
Computer Programming 2 23
Week 2 Getting to know the programming environment
Save the code by selecting File on the menu bar and then click
save or we can simply press CTRL + S.
24
MODULE OF INSTRUCTION
Press F6
Computer Programming 2 25
Week 2 Getting to know the programming environment
LESSON SUMMARY:
1. You can write java program using notepad and compile it using
windows command line.
3. There are three types of error in java these are Syntax errors, run
time errors and logical errors.
26
MODULE OF INSTRUCTION
Programming Fundamentals
In this module we are going to discuss the basic parts of Java program
and coding guidelines to write readable programs.
/**
* Sample Java Program
*/
public class HelloWorld{
public static void main(String args[]){
System.out.println("Hello World!");
}
}
Always remember that Java code is case sensitive. Now let’s discuss
the each part of the sample program above.
1. The comment:
/**
* Sample Java Program
*/
Computer Programming 2 1
Week 3-4 Programming Fundamentals
2. Class definition
public class HelloWorld
3. Left curly brace (or opening curly brace) after class declaration
{
A set of curly braces { } is needed for every class. Curly braces are needed to
define the block or the beginning and end of the program or statement. The
opening curly brace indicates the beginning of the block of the statement.
2
MODULE OF INSTRUCTION
4. Main Method
public static void main (String[ ] args)
This part defined the main method of the program. The main method is
needed to start the execution of the program or it is executed first therefore
you need to have at least one method named main. You will not be able to run
a Java program without a main method. The static and void keyword will be
discussed later. The String args[] represents an array of String parameter, this
will also further discuss later. The public keyword is also the same as the
public defined in a class definition, it is an access modifier that sets the
accessibility of the method, in this case our main method is accessible
anywhere, this will be discuss further later.
5. Left curly brace (or opening curly brace) after class main method
{
6. Output Statement
System.out.println("Hello World!");
The right curly brace (}) represents the end of the block of codes. The
two right curly braces are used to end the main method and class definition.
Reminders:
Computer Programming 2 3
Week 3-4 Programming Fundamentals
B. Java Comments
2. Multi-line comments.
This comment is used for block commenting or series of multiple lines
of code. It starts with /* then followed by the text you want to comment and
then ends with */. All text inside the /* */ will be treated as comments. For
example:
/* This multi-line comment,
it can support multiple
line of codes. */
3. Documentation Comments
It is almost the same as multi-line comment that covers a block of
codes commenting but has a special purpose. Documentation comments are
used by the JDK java doc tool to generate HTML documentation for your
Java programs.
/**
* The HelloWorld program is an application that \n
* simply displays "Hello World!".
4
MODULE OF INSTRUCTION
*
* @author Juan Dela Cruz
* @version 1.0
*/
Coding Guidelines:
1. In block, you should place opening curly brace in line with the statement.
For example:
public static void main(String[] args){
2. Always indent the statements after the begin block, for example:
public class HelloWorld{ //begin block 1
public static void main(String[] args){ //begin block 2
System.out.println("Hello World!");
System.out.println("Welcome to Java!");
} //end block 1
} //end block 2
Computer Programming 2 5
Week 3-4 Programming Fundamentals
3. Closing curly brace should be vertically aligned with the statement that
defines the block (they should be on the same column number). For
example,
public class HelloWorld{ //begin block 1
public static void main(String[] args){ //begin block 2
System.out.println("Hello World!");
System.out.println("Welcome to Java!");
} //end block 1
} //end block 2
D. Identifiers
Rules for an Identifier (Take note that invalid identifier will result to syntax
error.):
Identifier must start with a letter, an underscore or a dollar sign.
Identifier must only contain letters, numbers, underscores or dollar
signs.
Special characters, such as a semicolon, period, whitespaces, slash or
comma are not allowed to be used as Identifier.
Identifiers are case sensitive in Java. For example hello and Hello are
two different an identifiers in Java.
Java Keywords is not allowed to use as an identifier. We are going to
identify all the Java reserved words later.
Coding Guidelines:
1. Use meaningful, descriptive or straight forward identifier, for example, if
you have a method that computes for the grade, name it computeGrade.
6
MODULE OF INSTRUCTION
2. Avoid using abbreviations for identifiers and use complete words to make
it readable.
3. In naming classes you should capitalize the first letter and for methods and
variables the first letter should be in lowercase. For example:
public class Hello (class identifier Hello starts with a capital letter)
public void main (method declaration main starts with small letter)
4. For multi-word identifiers use camel case. Camel case may start with a
capital letter or with a lowercase letter and all the succeeding words must
start with a capital letter. For example,
HelloWorld (this is a class identifier)
computeGrade (this is method identifier)
firstName (this is a variable identifier)
E. Java Keywords
Computer Programming 2 7
Week 3-4 Programming Fundamentals
do instanceof strictfp
In addition to the keywords listed above true, false and null are also
reserved words. The keywords goto and const are keywords reserved in
other programming languages like C, C++, c#, etc. but currently not used
in Java. There will be a discussion of each keyword as we go along the
way.
F. Java Literals
Integer Literal
An integer literal can be stored to an integral type variable. It can be a
decimal, binary, octal or hexadecimal constant. There is a format that we need
to follow in order to use integer literal. To represent a binary integer using a
prefix 0b or 0B (zero B), to represent hexadecimal integer use a prefix 0x or
0X (zero X), for octal use a prefix 0 (zero) and decimal has no prefix.
The following are the examples of integer literal in a program:
System.out.println(42); //Displays 42
System.out.println(0b101010); //Displays 42
System.out.println(0x2A); //Displays 42
System.out.println(052); //Displays 42
By default, the integer literal data type is int. An int value is between
-2147483648 and 2147483647. In case, that you want to use long type literal
you need to append the letter "L" or "l" on it. For example, to use
21474836470 in a Java program, you have to write it as 21474836470L,
because if you didn’t append “L” on the literal you will get an error since the
value exceeds the range for int value. We should use the L suffix in long type
integer literal because l (lowercase L) can easily be confused with 1 (the digit
one).
The following are the examples of integer literal with long data type in
a program:
System.out.println(21474836470L); // Displays 21474836470
System.out.println(0b101010L); // Displays 42
8
MODULE OF INSTRUCTION
System.out.println(0237777777766L); //Displays
21474836470
System.out.println(0x4FFFFFFF6L); // Displays 21474836470
Floating-Point Literals
Floating-point literal is an integer literal followed by a decimal point.
By default, the floating-point literal data type is double, but if you want to
explicitly express that the floating point literal is a double type value you can
append d or D on it and in case that you need to use type float value you need
to append f or F on it. For example, you can use 3.1416f or 3.1416F for a float
value, and 3.1416, 3.1416d or 3.1416D for a double value.
Boolean Literals
Boolean literals have only two possible values, true and false.
Character Literals
Character literals are enclosed in single quotes; for example, 'a' can be
stored in a simple variable of char type.
\t Tab
\b Backspace
Computer Programming 2 9
Week 3-4 Programming Fundamentals
\n New line
\r Carriage return
\f Form Feed
\' Single quote character
\" Double quote character
\\ Backslash character
String Literals
String literals are constant value consist of zero or more characters
enclosed in double quotes, for example, “Hello World”.
String literals may contain escape sequence character. When an escape
sequence is used in a print statement, it will be evaluated according to its
purpose. For example, if you want to print a text that is enclosed in double
quotes you need to use the escape sequence \". The code below demonstrates
the printing of text enclosed in double quotes:
System.out.println("Escape sequence \"double quote\" demo.");
The code above will display:
Escape sequence "double quote" demo.
byte
short
10
MODULE OF INSTRUCTION
int
long
float
Computer Programming 2 11
Week 3-4 Programming Fundamentals
double
boolean
char
12
MODULE OF INSTRUCTION
For example:
String message = “Hello world!”;
String supplementaryCharacter = “\uD801\uDC00”;
H. Variables
Data type and name are both required and initial value for variable is optional.
Computer Programming 2 13
Week 3-4 Programming Fundamentals
is a variable declaration with initial value. The word meter is the variable
name, int is the data type and 2 is the initial value.
is also a variable declaration and it has a variable name of centimeter and int
data type and has no initial value.
will just print the value inside the println. The + sign in the code is used to
combine or concatenate the values in between the symbol. In this case the
statement will print: 2 m = 200 cm.
Printing Variable
There are two statements that you can use to display or output the value from
a variable, these are the following:
System.out.println()
System.out.print()
14
MODULE OF INSTRUCTION
The two statements are both used to display value, the only difference
is the System.out.println() appends newline after it display the value while the
other one does not.
Computer Programming 2 15
MODULE OF INSTRUCTION
In this module, we are going to discuss the different operators that can
be use in Java.
4.1 Operator
Arithmetic Operators
Relation Operators
Logical Operators
Conditional Operator
Bitwise and Bit Shift Operators
Assignment Operators
Computer Programming 2 1
Week 3-4 Operator and Operator Precedence
System.out.println("Variable values:");
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("result = " + result);
2
MODULE OF INSTRUCTION
Computer Programming 2 3
Week 3-4 Operator and Operator Precedence
4
MODULE OF INSTRUCTION
Computer Programming 2 5
Week 3-4 Operator and Operator Precedence
6
MODULE OF INSTRUCTION
System.out.println("Logical Expression:");
Computer Programming 2 7
Week 3-4 Operator and Operator Precedence
8
MODULE OF INSTRUCTION
operand1?operand2:operand3
Computer Programming 2 9
Week 3-4 Operator and Operator Precedence
Let’s try another example, this time we set the value of variable age to
19.
Bitwise and Bit Shift Operators are basically used for bit manipulation,
or using bits of an integral type value to perform bit-by-bit operation.
These operators can be applied to any integral type (long, int, short,
char and byte).
10
MODULE OF INSTRUCTION
There are three Bitwise operators in Java, these are & (Bitwise And), |
(Bitwise Inclusive Or), ^ (Bitwise Exclusive Or) and ~ (One’s
Compliment). The truth table for Bitwise operators are as follows:
We will be using byte data type for all the examples in bitwise
operators, because byte can be easily represented in bits (byte is only 8
bits while other integral data types is much more than that).
The table above shows the bit computation of the example, each
bit will be computed separately using the & operator. For
example, let us execute the second row from the table 1 & 0 the
result would be 0. The result if we execute 00001100 & 00000101
expression is 00000100 or 4.
therefore: 12 & 5 = 4
Computer Programming 2 11
Week 3-4 Operator and Operator Precedence
therefore: 12 | 5 = 13
12
MODULE OF INSTRUCTION
therefore: 6 | 9 = 15
Computer Programming 2 13
Week 3-4 Operator and Operator Precedence
<< (Binary Left Shift) –This operator shifts or move the left
operands value to the left by the number of bits specified in the
right operand.
For example:
00000001 << 2 = 00000100
.01010001 << 3 = 1010001000
>> (Binary Right Shift) – This operator shifts or move the left
operands value to the right by the number of bits specified in
the right operand, filling with the highest (sign) bit on the left.
For example:
01001000 >> 3 = 00001001
14
MODULE OF INSTRUCTION
Assignment Operators
<variable> = <expression>;
int x = 1;
x=m+1
x = y = z = 1;
Computer Programming 2 15
Week 3-4 Operator and Operator Precedence
x = 1;
y = 1;
z = 1;
16
MODULE OF INSTRUCTION
z &= 2 is same as z
&= Bitwise AND and assignment operator.
=z&2
Bitwise exclusive OR and assignment z ^= 2 is same as z
^=
operator. =z^2
Bitwise inclusive OR and assignment z |= x is same as z =
|=
operator. z|x
Operators Precedence
postfix expr++, expr--
++expr, --expr, +expr, -
unary
expr, ~, !
multiplicative *, /, %
additive +, -
shift <<, >>, >>>
relational <, >, <=, >=
equality ==, !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
=, +=, -=, *=, /=, %=, &=,
assignment
^=, |=, <<=, >>=, >>>=
For example:
z = x%2*3+b/4+9-c;
Computer Programming 2 17
Week 3-4 Operator and Operator Precedence
we can re-write the expression and place some parenthesis base on operator
precedence,
18
[CS202 / Computer Programming 2]
1
[Getting Input]
The output of the program will depend on the user input. The program will ask the user to
enter his name and after entering the name it will display the “Your name is “ and the name
that was entered. Below is the sample output:
Course Module
indicates that we want to use the class Scanner, which is part of java.util package. Java
provided us Application Programming Interface (API) containing hundreds of predefined
classes that are very useful in writing programs. These classes are organized into what we
call packages.
Line 3 and 4,
we have already discussed this in the previous lesson, this means we declare a class named
GetInputUsingScanner and we also declare the main method.
The statement,
we declare variable scan with Scanner type. Don't worry about what the syntax for now,
we will cover more about this later. The statement will allow us to use all the features
attributed to Scanner class.
Line 8 will just display the text on the screen asking for the name of the user.
In the line 9,
the scan.nextLine() is a method call that gets input from the user and will return a String
value. The returned value will be saved to the variable name, which will be used to display
in the output statement,
Aside from nextLine(), there are other methods (in Scanner class) that can be called to read
input from the user, these are the following:
nextByte(), returns byte value
nextShort(), returns short value
nextInt(), returns int value
nextLong(), returns long value
nextFloat(), returns float value
nextDouble(), returns double value
nextBoolean(), returns boolena value
[CS202 / Computer Programming 2]
3
[Getting Input]
nextByte()
Method calls to get input from the user and will return a byte value. For example:
Assume that the user input number 5, the output will be:
nextShort()
Method calls to get input from the user and will return a short value. For example:
Assume that the user input number 260, the output will be:
Course Module
nextInt()
Method calls to get input from the user and will return a int value. For example:
Assume that the user input number 25566465, the output will be:
nextLong()
Method calls to get input from the user and will return a long value. For example:
Assume that the user input number 123456789012345, the output will be:
nextFloat()
Method calls to get input from the user and will return a float value. For example:
[CS202 / Computer Programming 2]
5
[Getting Input]
Assume that the user input number 3.1416, the output will be:
nextDouble()
Method calls to get input from the user and will return a double value. For example:
Assume that the user input number 123456.78901, the output will be:
nextBoolean()
Method calls to get input from the user and will return true or false value. For
example:
Assume that the user input False, the output will be:
Course Module
Using JOptionPane Class
Another way to read input from the user is through a graphical user interface using
the JOptionPane class which is found in the javax.swing package. JOptionPane allows you
to show pop up dialog box that prompts users for a value or just show the message.
Here’s the implementation of JOptionPane in a program:
The figure above is an input dialog box that was prompted after we run the program,
the input dialog box allows the user to enter any value.
We had input John in the input dialog box and click OK button, then the message
dialog box show up.
tells the compiler that we want to import the JOptionPane class from the javax.swing
package.
[CS202 / Computer Programming 2]
7
[Getting Input]
Line 2,
displays JOptionPane input dialog box that is composed of a message, a text field, OK and
Cancel Button. The showInputDialog() returns String value and saved in the variable
name.
This statement,
declares msg variable with a value of “Hello “ together with the value of variable name
and “!”.
The next line,
displays a message dialog box which contains a message and an OK button, in this case,
message is based from the value of msg variable.
Course Module
Computer Programming 2
1
Control Structures
Introduction to Algorithms
This module includes topics on:
1. Control Structures
2. Decision Control Structures
3. For loop
4. While and Do while
Control Structures
In this module, we are going to discuss control structures, that allows the program to choose a
direction in which to go based on a given condition.
if Statement
The if-statement enables the program to execute a statement or block of codes if and only
if the boolean expression is true.
The if-statement is can be express this form,
Course Module
if (boolean_expression)
statement;
or
if (boolean_expression){
statement1;
statement2;
...
}
The flowchart above illustrates the process on how the program executes if-statement.
Flowchart is a diagram used to describe the process of a program, it uses shapes to represent the
steps or parts of the process. The diamond box represents a decision that determines which paths
is to be followed, or it denotes a boolean expression. Rectangular box represents the process
operation, or it denotes statements. Arrows connecting them represent the flow of control.
For example:
if(age>=18)
System.out.println("Qualified to vote!");
age >= 18
S
y
Computer Programming 2
3
Control Structures
Output:
The program prompts the user to enter his age (lines 5–6) and displays "You are qualified
to vote it" if the value of age is greater than or equal to 18 (lines 7–8). If the value of age is less
than 18 it will do nothing.
Coding Guidelines:
1. Using if-statement without curly braces makes the code shorter, but it is prone to errors and
hard to read.
2. You should indent the statements inside the block, for example:
if( boolean_expression ){
//statement1;
//statement2;
}
3. Inside the block you can put any statement, meaning you have another if statement inside the
if statement, fir example:
if(boolean_expression){
if (boolean_expression){
//Statements
}
}
Course Module
if-else Statement
if-else statement is used when you want the program decide from which of the two sets of
statements is going to be executed based on whether the condition is true or false.
An if statement only executes the statements if the condition is true, and do nothing if the
condition is false. Unlike in an if-else statement the program can take alternative actions when the
condition is false. In the if-else statement we can execute another statements if the condition is
false.
For example:
if(age>=18)
System.out.println("Qualified to vote!");
else
System.out.println("To young to vote!");
S S
y y
Course Module
Output:
The program prompts the user to enter his age (lines 5–6) and displays "You are qualified
to vote it" if the value of age is greater than or equal to 18 (lines 7–8) and if the age is less than 18
it will display "You are too young to vote" (lines 10-11).
statement2;
...
}
Take note that we can omit the last else block and we can add more else-if block after the
if-block.
Boolean Expression 1
Boolean Expression 2
In the flowchart shown above, if boolean_expression1 evaluates to true, the program will
execute the statement1 and skips the other statements, if false,s the program will proceed to
evaluate the boolean_expression2. If boolean_expression2 evaluates to true, the program executes
statement2 and skips the else statement, otherwise the program will execute statement3.
For example:
if(age>=18){
System.out.println("Qualified to vote!");
}
else if(age < 0){
System.out.println("Invalid age!");
}
else{
System.out.println("Too young to vote!");
}
Course Module
Below is the flowchart for the sample code above:
age >= 18
S
y age < 0
Output:
Computer Programming 2
9
Control Structures
The program prompts the user to enter his age (lines 5–6) and displays "You are qualified
to vote it" if the value of age is greater than or equal to 18 (lines 7–8) and if the age is less than 0
it will display "You have entered an invalid age!" (lines 10-11), otherwise it will display it will
display "You are too young to vote" (lines 13-14).
Course Module
3. Adding semi-colon at the end of if statement. For example,
if(num == 5);
// statements
Switch Statement
Another way to allow the program to have multiple alternative action is through switch
statement. It is similar to if-else if-else statement, however, if-else if-else statement is based from
the condition (whether true or false), while the switch statement can test the given value or
expression to different cases.
case case_valueN:
// statements
break;
default:
//statements
}
The switch_expression is a variable or expression that must have a type value of char, short,
int, long or string. The case_values must have the same type value as the switch_expression for
they will be checked if one of them is equal to the switch_expression. The case_values should be
a constant expression, meaning they cannot contain variables such x + 1. The case_values should
also unique, it is not allowed duplicate case_value. The keyword break is optional, this statement
immediately ends (break) the switch statement. It is allowed in a switch statement to have no block.
The switch statement first evaluates with the switch_expression, and then it will check if
value of first case (case_value1) matches the value of switch_expression. If their value matches it
will execute all the statements after case value until a break statement is encountered. If the two
values didn't matched it will proceed to another case, then check again if it matches with the
switch_expression. The process will continue until the program finds the matching case. In case
that there is no case matches with the switch_expression the default will be executed.
For example:
int num = 2;
switch(num){
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:
Course Module
System.out.println("Four");
break;
default:
System.out.println("Invalid Number");
}
Sy
The example above checks whether the value of num matches from value 1, 2, 3 or 4. If
the value of num matches with anyone from the cases, the program will display the converted word
of a number, if there is no matching value, “Invalid Number” will be displayed.
Computer Programming 2
13
Control Structures
Course Module
The program prompts the user to enter any number (lines 4–6) and displays the converted
word of a number if the number have entered matches with the listed cases (8-25). If there is no
matching value if will do nothing since it has no default case in switch statement.
The statements inside the while loop will be executed as long as the loop_condition
evaluates to true. If the loop_condition evaluates to false it will exit or stop the loop. For example:
Computer Programming 2
15
Control Structures
int x = 1;
while(x <= 5){
System.out.print(x);
x++;
}
The sample code snippet will display 12345. The program will first execute the statement
int x = 1;, this defines the variable x with an initial value of 1. Next, the program will execute the
while loop statement with loop_condition x<=5, in this case we yield true for the loop_condition.
Now that the loop_condition is true, the program displays the value of x which is 1. After the
program displays the value of x, it will execute the x++;, which means increment the value of x by
1, now we get 2 for the value of x. Next step is, the program will execute again the loop_condition,
in this step we evaluate the loop_condition to true since the value of x is 2. Then it will just repeat
the process until the value of x reaches to 5. The loop stops when the value of x is greater than 5.
The following are other examples of while loops,
Example 1:
int x = 5;
while (x>0)
{
System.out.print (x);
x--;
}
Course Module
The example above will display 54321. In this case we used decrement operator. The while
loop will stop when the value of x becomes 0.
Example 2:
int x = 0;
while(x<=5){
System.out.println(“Hello World!”);
}
The sample code above will have an infinite loop or it will just display “Hello World”
continuously without stopping. It leads to infinite loop because we didn't put statement that
controls the iteration. In this case, the value of x remains 0 and loop_condition (x<=5) is will
always be true.
Example 3:
//no loops
int x = 5;
while(x<5){
System.out.println(“Hello World!”);
}
The sample code above will display nothing because it will not reach the statements
System.out.println(“Hello World!”); due to loop_condition (x<5) evaluates to false.
The program prompts the user to enter any number (lines 5–6). Now, if num > 0 is true,
the program adds the value of num to sum. The value of variable num depends on the user’s input
(in this case num is 5), for each loop the value of num is decremented by 1. when the value of num
reaches 0, num > 0 is false, so the loop exits. Therefore, the sum is 5 + 4 + 3 + 2 + 1 = 15.
The do-while loop is almost the same as while loop, where they execute the body of loop
repeatedly as long as the condition is true. The only difference is that, do-while loop executes the
body of loop first and then evaluates the loop_condition.
do{
//loop body
statements;
} while(loop_condition);
Take note that there is a semi-colon after the while expression, that is a common mistake
when using do-while loop.
Course Module
As you can see from the flowchart above, the loop body was executed first and then
evaluates the loop_condition. If the loop_condition evaluates to true, the loop body will be
executed again and if it is false, the loop will be terminated. The loop will continue as long as the
loop_condition evaluates to true. For example:
int x = 1;
do{
System.out.print(x);
x++;
} while(x <= 5);
The sample code snippet will display 12345. The program will first execute the statement
int x = 1;, this defines variable x with an initial value of 1. Next, the program will execute the do-
while loop statement which will execute first the loop body, the loop body will display and
increment the value of x. After that, it will evaluate the loop_condition (x<=5), if the
loop_condition evaluates to true it will execute again the loop_body. The program will repeat the
same process until the value of x becomes 6.
The following are other examples of do-while loops,
Example 1:
int x = 5;
do{
System.out.print (x);
x--;
} while (x>0);
Example 2:
int x = 0;
Computer Programming 2
19
Control Structures
do{
System.out.println(“Hello World!”);
} while(x<=5);
The sample code above will have an infinite loop or it will just display “Hello World”
continuously without stopping.
Example 3:
int x = 5;
do{
System.out.println(“Hello World!”);
} while(x<5);
The sample code above will display Hello World!”, this loop will just execute the body of
statement then terminate the loop because the loop_condition (x<5) evaluates to false. Use a do-
while loop if you want your loop_body to be executed at least once.
Course Module
The program prompts the user to enter any number repeatedly until the user entered 0.
Every time the user entered number it will be saved to variable num then the value of num will be
added to variable sum. The loop will not stop until the user entered 0. The program will just add
all the numbers that the user have entered.
The for loop is the same as the previous loop statement where it allows the program to
execute statement repeatedly. Unlike the previous loops, for loop has clear form to define loop.
Below is the form to define for loop:
The for loop statement starts with the keyword for, followed by a pair of parenthesis
enclosing the control structure of the loop. This structure used to define the limit of the iteration
and it is consist of loop_initial_expression followed by the loop_condition, then step_expression,
and they are separated by semi-colon. The loop_initial_expression is used to set the initial or
starting value of the loop variable. The loop_condition is used to compare the loop_variable to a
certain value (or value that defines the limit of the loop). The step_expression is used to update the
loop variable. The control structure is followed by the loop body enclosed inside the braces. loop
body contains statements that will be executed repeatedly based from the limit defined in control
structure. Below is the flowchart of for loop:
Computer Programming 2
21
Control Structures
As you can see from the flowchart, for loop first executes the loop_initial_expression, after
the program set the initial value of loop variable the program will proceed to loop_condition, if the
loop condition evaluates to true, the program will proceed to loop body, otherwise it will exit the
loop. After the loop body, the program will now execute the step_expression to update the loop
variable, then loop back to loop_condition, the process will continue as long as the loop_condition
evaluates to true.
For example:
int x;
for(x = 0; x <=5; x++){
System.out.print(x);
}
Course Module
The sample code snippet will display 12345. Below is the flowchart of while loop statement:
Based from the flowchart above, the program will executes first the x=0
(loop_initial_expression), after that, it will evaluate x<=5 (loop_condition), in this case we yield
true for this expression because the value x is 0 and it is less than 5, then the program will execute
the loop body. Next, x++ (step_expression) will be executed, this means that variable x will be
incrementd by 1. After the step_expression the program will execute again the loop_condition.
The same process will be repeated until the value of x becomes greater than 5.
int x;
for(x=5; x>0; x--){
System.out.print(x);
}
Computer Programming 2
23
Control Structures
The example above will display 54321. In this case we used decrement operator. The while
loop will stop when the value of x becomes 0.
Example 2:
int x;
for(x=0; x<=5; x--){
System.out.print("Hello World!");
}
The sample code above will loop until the maximum negative int value. In this case, the
value of x is decremented by 1 and loop_condition (x<=5) is will always be true.
Example 3:
int x;
for(x=5; x<5; x--){
System.out.print("Hello World!");
}
The sample code above will display nothing because it will not reach the statements
System.out.println(“Hello World!”);, due to loop_condition (x<5) evaluates to false.
Course Module
The program prompts the user to enter any number (lines 7–8). The program will display
the value x repeatedly based from the number of the user’s input.
Nested loop is a loop inside the loop. The body of loop contains any statement, therefore it
could have another loop. Nested loops consist of an outer loop and one or more inner loops, this
means that for every loop inside the outer loop there is a complete execution of inner loop.
For example:
Based from the sample code above, the outer will execute the loop body 3 times and it
contains inner loop and a statement that add new line (System.out.println()). The output of a
complete inner loop is 12345 therefore the final output of the sample code is:
1
2
3
4
5
Course Module 1
2
3
4
Nested Loop Sample Program:
The program prompts the user to enter table size (lines 6–7). The program will display
Multiplication Table and the size of the table will be based from the user’s input.
Computer Programming 2
1
Array
Java Array
This module includes topics on:
1. Array
2. Multidimensional array
Java Array
In this module we are going to discuss the concept of an array and how to use it in a Java
program.
At the end of the lesson, the student should be able to:
Discuss what is Java array.
Declare and create an array.
Use array in Loops
Declare and create a multidimensional array.
Create a program that implements Arrays.
Introduction to Array
In the previous lesson, we have been working with variables that a store single value at a
time. Variables can only hold one value, for example, in an integer variable you can assign single
number and String variable can be assigned one long string of text. An array can hold multiple
same type value at a time, just like a list of items.
An array is a collection of variables of the same type. It has fixed number of values and its
length is defined upon creation, therefore after creating an array its length is fixed.
For example, an array of int is a collection of variable of type int and each variable in the
collection has indexed and can hold different int value. Below is the illustration of a Java array:
The figure above is an array of 8 elements. Each item is called an element and an element
has an index number and it used to access the value of an element. An array always starts with
index 0 and the maximum index number is n-1 (where n is the length of an array), that is why the
maximum index of the array of 8 elements is 7. For example, to get the value of the 3 rd element
(38), you can access it at index 2.
Course Module
Declaring Array
Declaring an array is similar to variable declaration. To declare an array, you need to
specify the type, followed by a pair of square brackets and, and then followed by array name or
identifier, for example,
int[] intArray;
or you can put the pair of square brackets after the identifier,
int intArray[];
where type is the data type of the elements; the pair of square brackets are special symbols that
indicates that this variable is an array. An array name can be anything you want, provided that it
follows the rules of valid identifier. The size of the array was not specified because the declaration
does not actually create an array, it only tells the compiler that this variable will hold an array of
the specified type.
The following are the examples of array declaration in other types:
byte[] byteArray;
short[] shortArray;
long[] longArray;
float[] floatArray;
double[] doubleArray;
boolean[] booleanArray;
char[] charArray;
String[] anArrayOfStrings;
After declaring the array, we can now create it and specify its length. One way to create an
array is with the new keyword. Always remember that the size of an array is not allowed to be
changed once you have created the array. For example,
//array declaration
int[] intArray;
//array creation
intArray = new int[10]
The example above shows how to declare and create an array. Based from the example, the
array has a name of intArray and it can hold 10 elements with the int data type.
Now that we have created an array we can now assign values to it. To assign values to the
array, we need to access each element and use the assignment operator. To access the element, we
need to specify the array name followed by opening bracket, then the index of the element and
then closing bracket.
For example,
//declaration and creation of an array
int[] intArray = new int[10];
There is another way to declare, create and assign values to the array at once:
Course Module
Below is the representation of the examples above,
Each element has now an assigned value, therefore we can now use the value by accessing
the element through its index. For example,
Here’s another example of Java program that shows another way of assigning values to an array:
Array Length
Length is a property of array objects that you can use to get the size of the array. Below is
the example of getting the length of an array:
From the example above, we have created an array with the size of 100. We also declared
variable arrayLength that was assigned with intArray.length this means that the variable
arrayLength will contain the value 100.
Course Module
Array and Loop
Loops are useful in an array, for example, we have to assign a series of numbers in an array
or we need to traverse all the elements of an array. Here is an example of assigning and iterating
an array with a for loop:
int[] intArray = new String[5];
From the example above, the first statement creates an array of int with the length of 5.
Initially, each element has no value, the first loop statements assigns value to each element of
intArray. In the loop statement, the variable i is initialized to 0 and runs up until the length of the
array minus 1. In this case, variable i will have the values 0 through 9, and for each iteration
variable i has different value. The statement intArray[i] = i + 1;, this assigns values to each
element in the array. Instead of using number between the square brackets of the array, we
specified the variable i. This increases by 1 for each iteration of the loop, therefor every time the
variable i increases the position or index of the array element that we access also increases. Now,
for every iteration in the loop, each element will have the value of i+1. So, the value of each
element in the array is just the incremented loop value. The intArray has now the values of 1 to
10. The second loop statement will also traverse the intArray and display all the value of each
element. When we execute the example code above it will display 1 2 3 4 5 6 7 8 9 10.
Course Module
Let’s have another example of array, but this time we are going to use array of String.
The program displays the values of the array (line 13 – 15) and prompts the user to enter a
name to search (line 18 – 20), if the name that the user has entered is present in the array (names)
the program will display the index position of the matching element, and if the name is not present
it will do nothing.
Multidimensional Array
This example creates a two-dimensional array of int elements. The array contains 5
elements in the first dimension, and 10 elements in the second dimension. The array of arrays has
space for 5 int arrays, and each int array has space for 10 int elements.
We can access the elements in a multidimensional array with one index per dimension
(bracket pair). The example above is a two-dimensional array therefore we have to use two indices
to access each element. Here is an example on how we assign values in a multidimensional array:
Course Module
Below is the out of the sample program above:
The first nested loop is used to display the array of int while the other one is used to display
the array of String. For every iteration of the outer loop is a complete loop of the inner loop, in
other words, for every iteration of outer loop the statement System.out.println("int2DArray[" + i
+ "][" + j + "]: " + int2DArray[i][j]); is executed 3 times. On the first outer loop iteration the
value of i is 0 and the value of j is from 0 to 2, that is why we will have an output of:
int2DArray[0][0]: 1
int2DArray[0][1]: 2
int2DArray[0][2]: 3
On the second outer loop iteration the value of i will become 1 and the value of j is also 0
to 2, and we will have an output of :
int2DArray[1][0]: 4
int2DArray[1][1]: 5
int2DArray[1][2]: 6
Now, on the last outer loop iteration the value of i will become 2 and the value of j is again
0 to 2, and we will have an output of :
int2DArray[2][0]: 7
int2DArray[2][1]: 8
int2DArray[2][2]: 9
Computer Programming 2
13
Array
The same process will be applied on the other nested loop and we can get this output:
string2DArray[0][0]: a
string2DArray[0][1]: b
string2DArray[0][2]: c
string2DArray[1][0]: d
string2DArray[1][1]: e
string2DArray[1][2]: f
Course Module
Computer Programming 2
1
Methods
Methods
Java Methods
In this module, we are going to discuss the concept of the method. We will also
explain the importance of methods and how to implement it in Java programs.
Introduction
In the previous lesson, all the sample program contains one method only and it is
the main method, in one Java program (class) we are allowed to define one or methods.
Why do we need more methods in a program where we can solve the problem in one
method? The reason is, the method is used to simplify and organize coding and define
reusable codes. The method can help to have clean, organize and readable codes. It could
also, eliminate redundant codes defined in a class.
A method contains a collection of statements that are grouped together, and it is
called by another method (such as main) to perform a specific task or operation. An
example of the method call is when you use the System.out.println() in main method.
Executing println(), the compiler actually executes several statements in order to display a
message on the console. The following are characteristics of methods:
It can return one or no values.
It can accept any values.
After the method finished the execution, it goes back to the method that called it.
Defining Method
Below is an example of the method declaration:
public double computeOperation(int param2, int param2){
//statements that performs calculation
}
Course Module
As you can see from the example above, method has the following components:
Modifier (public) - It defines the access type of the method and it is optional to use. Other
modifiers that can used are private, protected and default, modifiers will be discussed
further later. Modifier is optional, therefore, you can define method without modifier.
Return type (double) – The data type of the value that the method returns. If the method
defined as void it will not return any value.
Method name (computeOperation) – Specifies the name that identifies the method, we
apply here the coding guidelines for the valid identifier.
Parameter List ((int param1, intparam2))- A list of parameters, preceded by their data types
and enclosed by parentheses, (). If your method does not have any parameters, you must
use empty parenthesis.
Method body ({ //statements }) - The Method body is enclosed in curly brackets. It defines
what the method does with the statements.
Naming a method
Method name should follow the rules of valid identifier, and it should be a verb in
lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives,
nouns, etc. In multi-word names, the first letter of each of the second and following words
should be capitalized. Here are some examples:
compute
computeGrade
execute
getAge
setAge
compareTo
setValue
isEmpty
Method Calling
The process of method calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then returns control
to the caller in two conditions, when the return statement is executed or when it reaches the
method ending closing brace.
The methods returning void is considered as call to a statement. For example,
System.out.println("Hello World!");
Here's an example of method call that returns value,
int result = sum(8, 6);
Computer Programming 2
3
Methods
Below is the example that demonstrates on how to define and call methods:
From the example above, we defined two methods the getMin and getMax. They are
expected to return int value and they were called inside the main method. The two methods
have both static keyword, we use this keyword because the caller (main) is also defined as
static, we will discuss more on static keyword later.
The getMin method has two parameters the int num1 and int num2, and returns which
of these two parameters have the minimum value. The getMax method has also two parameters
and returns which of them has the maximum value. In getMax method, we defined return
keyword twice, we placed the them inside the if condition, so whatever the result of condition
it will automatically return the value to the caller method (main), unlike the getMin method we
defined min variable that will contain the minimum value and return it after the if condition.
Course Module
Here’s an example that calls method that does not return value,
From the example above, we defined two methods the displayMin and displayMax,
this time they will not return any value. The two methods used void keyword as the return
type. The void keyword allows us to create methods which do not return a value. The two
methods were called inside the main method, they will just display minimum and maximum
value respectively.
Computer Programming 2
5
Methods
As you can see from the output above, the value of variable x and y remain
unchanged even if they were passed as arguments in the method swap and change their
value inside the method.
Course Module
Pass-by-reference
In pass-by-value, it makes a copy of the variable that will be passed to method,
while pass-by-reference, it passed the actual argument. In pass by reference, the parameter
specified in the method is just an alias to the actual parameter and it refers to the actual
argument. Any changes made to the parameter inside the method will reflect in the actual
argument. For example,
Method Overloading
Typically, a method has a unique name within its class. However, a method might
have the same name as other methods due to method overloading. Method overloading
allows you to define multiple method with the same name in a class, provided their
parameter lists are different.
Two ways to overload the method in Java:
Method should have different number of parameters. For example,
public int add(int num1, int num2){
…..
}
Computer Programming 2
7
Methods
From this example, we have created two overloaded methods. The first sum method
has two int parameters and performs addition of the two parameters. The second one has
three parameters and performs the addition of the three parameters.
Course Module
Another example of overloading method but differs in data type of the parameters:
From the example above, we have created two overloaded methods that differ in
data type. The first displaySum method has two int parameters, the method display the sum
of two parameters. The second method has two double parameters and also displays the
sum of two parameters.
Computer Programming 2
1
Basic Java Object Oriented Programming
Course Module
With these descriptions, the objects in the physical world can easily be modeled as
software objects using the state as data and the behaviors as methods. These data and
methods could even be used in programming games or interactive software to simulate the
real-world objects! An example would be a car software object in a racing game or a lion
software object in an educational interactive software zoo for kids.
When instantiated, each object gets a fresh set of state variables. However, the
method implementations are shared among objects of the same class. Classes provide the
benefit of reusability. Software programmers can use a class over and over again to create
many objects.
Encapsulation
Encapsulation is the method of hiding certain elements of the implementation of a
certain class. By placing a boundary around the properties and methods of our objects, we
can prevent our programs from having side effects wherein programs have their variables
changed in unexpected ways.
Computer Programming 2
3
Basic Java Object Oriented Programming
We can prevent access to our object's data by declaring them declaring them in a
certain way such that we can control access to them. We will learn more about how Java
implements encapsulation as we discuss more about classes.
Class Instantiation
To create an object or an instance of a class, we use the new operator. There are
three steps when creating an object from a class:
Declaration − A variable declaration with a variable name with an object type.
Instantiation − The 'new' keyword is used to create the object.
Initialization − The 'new' keyword is followed by a call to a constructor. This
call initializes the new object.
Course Module
For example:
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
The new operator allocates a memory for that object and returns a reference of that
memory location to you. When you create an object, you actually invoke the class'
constructor. The constructor is a method where you place all the initializations, it has the
same name as the class.
Another example is when we want to typecast an int to a char value or vice versa.
A character can be used as an int because each character has a corresponding numeric code
that represents its position in the character set. If the variable i has the value 65, the cast
(char)i produces the character value 'A'. The numeric code associated with a capital A is
65, according to the ASCII character set, and Java adopted this as part of its character
support. For example,
char varChar = A;
int varInt = varInt; //implicit cast
System.out.println(varInt); //print 65
In case that we want to convert a data that has a large type to a smaller type, we
must use an explicit cast. Explicit casts take the following form:
(Data_Type)value;
Where,
Data_Type, is the output data type that you’re converting.
value, is an expression that results in the value of the source type.
For example,
double varDouble = 10.12;
int varInt = (int)varDouble; //convert varDouble to int type
double x = 10.2;
int y = 2;
int result = (int)(x/y); //typecast result of operation to int
Course Module
Sample Class Hierarchy
This is true in the reverse, and you can use a superclass when a subclass is expected.
There is a catch, however: Because subclasses contain more behavior than their
superclasses, there's a loss in precision involved. Those superclass objects might not have
all the behavior needed to act in place of a subclass object. For example, if you have an
operation that calls methods in objects of the class Integer, using an object of class Number
won't include many methods specified in Integer. Errors occur if you try to call methods
that the destination object doesn't have.
To use superclass objects where subclass objects are expected, you must cast them
explicitly. You won't lose any information in the cast, but you gain all the methods and
variables that the subclass defines. To cast an object to another class, you use the same
operation as for primitive types:
To cast,
(Class_Name)object;
Where,
Class_Name, is the name of the destination class.
value, is a reference to the source object.
For example,
CAUTION: The void class represents nothing in Java, so there's no reason it would be
used when translating between primitive values and objects. It's a placeholder for the void
keyword, which is used in method definitions to indicate that the method does not return a
value.
Course Module
Comparing Objects
In our previous discussions, we learned about operators for comparing values-
equal, not equal, less than, and so on. Most of these operators work only on primitive types,
not on objects. If you try to use other values as operands, the Java compiler produces errors.
The exceptions to this rule are the operators for equality: == (equal) and != (not
equal). When applied to objects, these operators don't do what you might first expect.
Instead of checking whether one object has the same value as the other object, they
determine whether both sides of the operator refer to the same object.
To compare instances of a class and have meaningful results, you must implement
special methods in your class and call those methods. A good example of this is the String
class.
It is possible to have two different String objects that contain the same values. If
you were to employ the == operator to compare these objects, however, they would be
considered unequal. Although their contents match, they are not the same object.
To see whether two String objects have matching values, a method of the class
called equals() is used. The method tests each character in the string and returns true if the
two strings have the same values.
NOTE: Why can't you just use another literal when you change str2, rather than using
new? String literals are optimized in Java; if you create a string using a literal and then use
another literal with the same characters, Java knows enough to give you the first String
object back. Both strings are the same objects; you have to go out of your way to create
two separate objects.
Course Module
Computer Programming 2
1
Inheritance, Polymorphism and Interfaces
In this module, we will discuss how a class can inherit the properties of an existing
class. We will also discuss a special property of Java wherein it can automatically apply
the proper methods to each object regardless of what subclass the object came from. This
property is known as polymorphism. Finally, we are going to discuss about interfaces that
helps reduce programming effort.
At the end of the lesson, the student should be able to:
Define super classes and subclasses
Override methods of superclasses
Create final methods and final classes
Inheritance
In Java, all classes, including the classes that make up the Java API, are subclassed
from the Object superclass. A sample class hierarchy is shown below.
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.
Course Module
Defining Superclasses and Subclasses
To derive a class, we use the extends keyword. In order to illustrate this, let's create
a sample parent class. Suppose we have a parent class called Person.
public class Person
{
protected String name;
protected String address;
/**
* Default constructor
*/
public Person(){
System.out.println(“Inside Person:Constructor”);
name = "";
address = "";
}
/**
* Constructor with 2 parameters
*/
public Person( String name, String address ){
this.name = name;
this.address = address;
}
/**
* Accessor methods
*/
public String getName(){
return name;
}
public String getAddress(){
return address;
}
public void setName( String name ){
this.name = name;
}
public void setAddress( String add ){
this.address = add;
}
}
Notice that, the attributes name and address are declared as protected. The reason
we did this is that, we want these attributes to be accessible by the subclasses of the
superclass. If we declare this as private, the subclasses won't be able to use them. Take note
that all the properties of a superclass that are declared as public, protected and default can
be accessed by its subclasses.
Computer Programming 2
3
Inheritance, Polymorphism and Interfaces
Now, we want to create another class named Student. Since a student is also a
person, we decide to just extend the class Person, so that we can inherit all the properties
and methods of the existing class Person. To do this, we write,
public class Student extends Person
{
public Student(){
System.out.println(“Inside Student:Constructor”);
//some code here
}
// some code here
}
When a Student object is instantiated, the default constructor of its superclass is
invoked implicitly to do the necessary initializations. After that, the statements inside the
subclass are executed. To illustrate this, consider the following code,
public static void main( String[] args ){
Student anna = new Student();
}
In the code, we create an object of class Student. The output of the program is,
Inside Person:Constructor
Inside Student:Constructor
The program flow is shown below.
Course Module
The super keyword
A subclass can also explicitly call a constructor of its immediate superclass. This is
done by using the super constructor call. A super constructor call in the constructor of a
subclass will result in the execution of relevant constructor from the superclass, based on
the arguments passed.
For example, given our previous example classes Person and Student, we show an
example of a super constructor call. Given the following code for Student,
public Student(){
super( "SomeName", "SomeAddress" );
System.out.println("Inside Student:Constructor");
}
This code calls the second constructor of its immediate superclass (which is Person)
and executes it. Another sample code shown below,
public Student(){
super();
System.out.println("Inside Student:Constructor");
}
This code calls the default constructor of its immediate superclass (which is Person)
and executes it.
There are a few things to remember when using the super constructor call:
1. The super() call MUST OCCUR THE FIRST STATEMENT IN A
CONSTRUCTOR.
2. The super() call can only be used in a constructor definition.
3. This implies that the this() construct and the super() calls CANNOT BOTH
OCCUR IN THE SAME CONSTRUCTOR.
Another use of super is to refer to members of the superclass (just like the this
reference). For example,
public Student()
{
super.name = “somename”;
super.address = “some address”;
}
Computer Programming 2
5
Inheritance, Polymorphism and Interfaces
Overriding Methods
If for some reason a derived class needs to have a different implementation of a
certain method from that of the superclass, overriding methods could prove to be very
useful.
A subclass can override a method defined in its superclass by providing a new
implementation for that method. Suppose we have the following implementation for the
getName method in the Person superclass,
public class Person
{
..
public String getName(){
System.out.println("Parent: getName");
return name;
}
}
To override, the getName method in the subclass Student, we write,
public class Student extends Person
{
..
public String getName(){
System.out.println("Student: getName");
return name;
}
}
So, when we invoke the getName method of an object of class Student, the
overridden method would be called, and the output would be,
Student: getName
Course Module
Final Methods and Final Classes
In Java, it is also possible to declare classes that can no longer be subclassed. These
classes are called final classes. To declare a class to be final, we just add the final keyword
in the class declaration. For example, if we want the class Person to be declared final, we
write,
public final class Person
{
//some code here
}
Many of the classes in the Java API are declared final to ensure that their behavior
cannot be overridden. Examples of these classes are Integer, Double and String.
It is also possible in Java to create methods that cannot be overridden. These
methods are what we call final methods. To declare a method to be final, we just add the
final keyword in the method declaration. For example, if we want the getName method in
class Person to be declared final, we write,
public final String getName(){
return name;
}
Static methods are automatically final. This means that you cannot override them.
Computer Programming 2
7
Inheritance, Polymorphism and Interfaces
Polymorphism
Now, given the parent class Person and the subclass Student of our previous
example, we add another subclass of Person which is Employee. Below is the class
hierarchy for that,
Course Module
public class Employee extends Person
{
public String getName(){
System.out.println(“Employee Name:” + name);
return name;
}
}
Going back to our main method, when we try to call the getName method of the
reference Person ref, the getName method of the Student object will be called. Now, if we
assign ref to an Employee object, the getName method of Employee will be called.
public static main( String[] args )
{
Person ref;
Student studentObject = new Student();
Employee employeeObject = new Employee();
Abstract Classes
Now suppose we want to create a superclass wherein it has certain methods in it
that contains some implementation, and some methods wherein we just want to be
overridden by its subclasses.
For example, we want to create a superclass named LivingThing. This class has
certain methods like breath, eat, sleep and walk. However, there are some methods in this
superclass wherein we cannot generalize the behavior. Take for example, the walk method.
Not all living things walk the same way. Take the humans for instance, we humans walk
on two legs, while other living things like dogs walk on four legs. However, there are many
characteristics that living things have in common, that is why we want to create a general
superclass for this.
In order to do this, we can create a superclass that has some methods with
implementations and others which do not. This kind of class is called an abstract class.
An abstract class is a class that cannot be instantiated. It often appears at the top of
an object-oriented programming class hierarchy, defining the broad types of actions
possible with objects of all subclasses of the class.
Those methods in the abstract classes that do not have implementation are called
abstract methods. To create an abstract method, just write the method declaration without
the body and use the abstract keyword. For example,
public abstract void someMethod();
Now, let's create an example abstract class.
public static main( String[] args )
public abstract class LivingThing
{
public void breath(){
System.out.println("Living Thing breathing...");
}
Course Module
/**
* abstract method walk
* We want this method to be overridden by subclasses of
* LivingThing
*/
public abstract void walk();
}
When a class extends the LivingThing abstract class, it is required to override the
abstract method walk(), or else, that subclass will also become an abstract class, and
therefore cannot be instantiated. For example,
public class Human extends LivingThing
{
public void walk(){
System.out.println("Human walks...");
}
}
If the class Human does not override the walk method, we would encounter the
following error message,
Human.java:1: Human is not abstract and does not override
abstract method walk() in LivingThing
public class Human extends LivingThing
^
1 error
Coding Guidelines: Use abstract classes to define broad types of behaviors at the top of an
object-oriented programming class hierarchy, and use its subclasses to provide
implementation details of the abstract class.
Interfaces
An interface is a special kind of block containing method signatures (and possibly
constants) only. Interfaces define the signatures of a set of methods without the body.
Interfaces define a standard and public way of specifying the behavior of classes.
They allow classes, regardless of their location in the class hierarchy, to implement
common behaviors. Note that interfaces exhibit polymorphism as well, since program may
call an interface method and the proper version of that method will be executed depending
on the type of object passed to the interface method call.
we have another class MyInteger which contains methods that compares a MyInteger
object to objects of the same class. As we can see here, both of the classes have some
similar methods which compares them from other objects of the same type, but they are
not related whatsoever. In order to enforce a way to make sure that these two classes
implement some methods with similar signatures, we can use an interface for this. We can
create an interface class, let's say interface Relation which has some comparison method
declarations. Our interface Relation can be declared as,
public interface Relation
{
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}
Another reason for using an object's programming interface is to reveal an object's
programming interface without revealing its class. As we can see later on the section
Interface vs. Classes, we can actually use an interface as data type. Finally, we need to use
interfaces to model multiple inheritance which allows a class to have more than one
superclass.
Course Module
Creating Interface
To create an interface, we write,
public interface [InterfaceName]
{
//some methods without the body
}
As an example, let's create an interface that defines relationships between two
objects according to the “natural order” of the objects.
public interface Relation
{
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}
Now, to use the interface, we use the implements keyword. For example,
/**
* This class defines a line segment
*/
public class Line implements Relation
{
private double x1;
private double x2;
private double y1;
private double y2;
When your class tries to implement an interface, always make sure that you
implement all the methods of that interface, or else, you would encounter this error,
Line.java:4: Line is not abstract and does not override
abstract method isGreater(java.lang.Object,java.lang.Object) in
Relation
public class Line implements Relation
^
1 error
Coding Guidelines: Use interfaces to create the same standard method definitions in may
different classes. Once a set of standard method definition is created, you can write a single
method to manipulate all of the classes that implement the interface.
Another example of a class that extends one super class and implements an interface
is,
public class ComputerScienceStudent extends Student implements PersonInterface,
LivingThing {
//some code here
}
Take note that an interface is not part of the class inheritance hierarchy. Unrelated
classes can implement the same interface.
Course Module
Inheritance among Interfaces
Interfaces are not part of the class hierarchy. However, interfaces can have
inheritance relationship among themselves. For example, suppose we have two interfaces
StudentInterface and PersonInterface. If StudentInterface extends PersonInterface, it will
inherit all of the method declarations in PersonInterface.
public interface PersonInterface {
..
}
In this module, we will discuss the technique used in Java to handle unusual
conditions that interrupt the normal operation of the program. This technique is called
exception handling.
At the end of the lesson, the student should be able to:
Define exceptions
Handle exceptions using a try-catch-finally block
What is Exception?
An exception (or exceptional event) is a problem that arises during the execution of
a program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios
where an exception occurs.
A user has entered an 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
others by physical resources that have failed in some manner.
Handling Exceptions
A method catches an exception using a combination of the try and catch keywords.
A try/catch block is placed around the code that might generate an exception. Code within
a try/catch block is referred to as protected code, and the syntax for using try/catch looks
like the following:
try {
// Protected code
}catch(ExceptionName e1) {
// Catch block
}
Course Module
The code which is prone to exceptions is placed in the try block. When an exception
occurs, that exception occurred is handled by catch block associated with it. Every try block
should be immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception you are trying to catch.
If an exception occurs in protected code, the catch block (or blocks) that follows the try is
checked. If the type of exception that occurred is listed in a catch block, the exception is
passed to the catch block much as an argument is passed into a method parameter.
For example:
public class ExceptionSample {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
The result of the example above is:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
In the above example, we have two lines that might throw an exception:
arr[5] = 5;
The statement above can cause array index out of bound exception and
result = num1 / num2;
this can cause arithmetic exception.
Inside the try block when exception is thrown then type of the exception thrown is
compared with the type of exception of each catch block. If type of exception thrown is
matched with the type of exception from catch then it will execute corresponding catch
block.
Course Module
Notes:
At a time, only single catch block can be executed. After the execution of catch
block control goes to the statement next to the try block.
At a time, only single exception can be handled.
All the exceptions or catch blocks must be arranged in order.
Notes:
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses whenever a try/catch block is present.
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.
Course Module
Quiz#1
1. JVM is responsible for
Select one:
a. Compiling source code
b. Interpreting bytecode Correct
c. None of the Above
d. Reading bytecode
e. Generating bytecode
5. Which of the following we are not allowed to write java source code?
Select one:
a. Notepad
b. BlueJ
c. NetBeans
d. eclipse
e. None of the Above Correct
10 What was the initial name for the Java programming language?
Select one:
a. NetBeans
b. C
c. Java
d. Oak Correct
e. None of the Above
Quiz#2
10.Can we directly compile codes from NetBeans?
Select one:
a. No, we can only write codes in NetBeans
b. Both A and C are correct.
c. Yes, because we can call Java compiler from NetBeans Correct
d. lt depends, if there is a compiler embedded in NetBeans.
12.Which of the following we are not allowed to write java source code?
Select one:
a. None of the Above Correct
b. NetBeans
c. BlueJ
d. Notepad
e. eclipse
14. What will happen if we compile the statement below?
-System.out.println("Hello World!")
Select one:
a. There will be a runtime error after compilation.
b. There will be no error after compilation.
c. There will be a logical error after compilation.
d. There will be a syntax error after compilation. Correct
e. None of the Above
15. What is the correct statement to run Java program in command line?
Select one:
a. javac HelloWorld
b. java HelloWorld.java
c. None of the Above
d. javac HelloWorld.java
e. java HelloWorld Correct
16. What is the correct statement to compile Java program in command line?
Select one:
a. jaw HelloWorld
b. javac HelloWorld.java Correct
c. java HelloWorld.java
d. javac HelloWorld
17. Which of the following is true about syntax errors:
Select one:
a. You will have syntax errors if you misspell the Java command.
b. Incorrect capitalization leads to syntax error.
c. Syntax errors are usually typing errors.
d. All of the above. Correct
e. None of the Above
18. Why do we need to set the path for JavaC in command line?
Select one:
a. lt is part of the compilation process
b. To make JavaC available or accessible in command line. Correct
c. To resolve runtime error
d. None of the Above
e. To resolve syntax error
19. What is the correct statement to set JavaC path in command line?
Select one:
a. set path
b. C:\Program Files\Java\jdk1.6.0_23\bin Correct
c. set path
e. None of the Above
f. path C: \Program Files\Java\jdk1.6_0_23\bin
g. All of the above
35. Which of the following method reads input from the user and return String
value?
Select one:
a. All of the above
b. nextValue()
c. nextText()
d. nextLine() Correct
e. nextString()
38. What will happen if you use JOptionPane. showInputDialog statement in your
program?
Select one:
a. The program will display message dialog box returns String value.
b. The program will display an input dialog box that allows the user to input text and
returns the correct
type value.
c. The program will display message dialog box.
d. The program will display an input dialog box that allows the user to
input text and returns
String value. Correct
e. None of the above
42. What will be the value of x after you execute this statement
int z=0; for(int x=0; x<10; x++) for( int y=0; y<x; y++) z*=(x*y);
Select one:
a. 128
b. 512
c. None of the above Correct
d. 1
e. 236
50. Which of the following has the correct form for an if statement?
Select one:
a. if boolean_expression
b. boolean_expression
c. if boolean_expression
d. if(boolean_expression) Correct
e. none of the above
Quiz# 7
51. Which of the following correctly accesses the sixth element stored in an array of
10 elements?
Select one:
a. intArray[6]; Incorrect
b. intArray[1O];
c. intArray[7];
d. None of the above
e. stringArray[5]; Correct
52. Which of the following is a valid multidimensional array?
Select one:
a. int[][] intArray;
b. int[][][][] intArray;
c. All of the above Correct
d. int[][][] intArray;
e. int intArray[][][];
53. Which of the following correctly accesses the sixth element stored in an array of
10 elements?
Select one:
a. intArray[7];
b. None of the above
c. stringArray[5]; Correct
d. intArray[6];
e. intArray[1O];
54. What is the index number of the last element of an array with 30 elements?
Select one:
a. 30
b. 31
c. None of the above
d. 29 Correct
e. 0
60. From the array int[] intArray = { 1, 2, 3, 5, 6, 7 };, what is the value of
intArray[3]?
Select one:
a. 5 Correct
b. 7
o. None of the choices
d. 6
e. 4
Quiz# 8
61. What is the output of the code snippet below:
void main(){test("11");test("1");}
void test(String x){System.out.print(x + x);}
Select one:
a.111111Correct111
b. 6
c. 222
d. None of the choices
63. What is the return value of this method: public void sum(){int x=1;} ?
Select one:
a. x
b. void Correct
c. sum
d. 1
e. none of the choices
Quiz #10
81. Which of the following class declaration is not allowed to be instantiated?
Select one:
a. public final class Person {}
b. public abstract class Person {} Correct
c. public class Person {}
d. class Person()
e. None of the above
82. Which of the following method is allowed to be overridden?
Select one:
a. public void setName(){}
b. public static void setName(){}
c. public final void setName(){} Correct
d. None of the above
e. public no_override void setName(){}
83. Which of the following is the correct way to call the constructor of the parent
class?
Select one:
a. this()
b. super() Correct
c. this.call()
d. super.call()