Vous êtes sur la page 1sur 178

MODULE OF INSTRUCTION

Introduction to Java

This is the first module of the course Computer Programming 2 and it


is about introducing Java. In this module we will be discussing the
background of Java and the Java technology. We will also discuss the
features and phases of 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.

Today Java is everywhere, in any devices and platform, in the Internet


and local device, from smart phones to computers, games to business
solutions. You can find Java anywhere and Java helps us to have a
better future.

What is Java Technology?

A programming language, Java is a general-purpose programming


language that can be used to create all kinds of applications on your
computer. Java syntax is mostly derived from C and C++, therefore if
you know how to write in C or C++ you could easily write Java
programs.

Computer Programming 2 1
Week 3-4 Administering Users and Roles

A Java platform, it is a software environment where the Java program


runs. There are four platforms that Java offers, these are:

 Java Standard Edition (Java SE), it is used to develop client-


side applications or an application that can run standalone.
 Java Enterprise Edition (Java EE), it is used to develop server-
side or network applications. There are several technologies
that JavaEE offers, such as Java servlets, JavaServer Pages
(JSP), and JavaServer Faces (JSF).
 Java Micro Edition (Java ME), it is used to develop
applications for small devices, such as cell phones, PDA and
smart phones.
 JavaFX is a platform for creating desktop applications and rich
internet applications that run across a wide variety of devices.

Phases of Java Program

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.

The Java Virtual Machine is responsible in interpreting your .class file.


It converts the bytecodes into another code that can be understood by
your processor. Since it is interpreted, the code will only be translated
everytime you perform operation of you program, unlike compiler all
your code will be translated at once.

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

Java is simple because of the following:

 It is easy to learn and the syntax is easy to understand, clean


and user-friendly.

 The syntax is mostly derived from C and C++ therefore it is


easier to learn Java after C or C++. The confusing features of
C++ were removed such as pointers, operator overloading etc.

 It has Garbage Collector that automatically removed


unreferenced or unused objects. One of the problems
encountered when writing a program is memory leak or the
program consumes too much available memory because the
programmer forget to deallocate memory. In Java, you no
longer need to deallocate the memory the garbage collection
thread is responsible for cleaning your memory.

Object Oriented

In Java, program focuses on Object that may contain data or


attributes and behaviour or methods. Java programs are made out
of objects that interact with one another, and it can be easily
extended since it is based on Object model.

4
MODULE OF INSTRUCTION

Platform Independent

A Java program is platform independent, which means you just


need to write a program once and run it on many different operating
systems. Unlike other programming languages such as C, C++, etc.,
they are compiled on a specific platform. The Java Virtual Machine or
JVM is responsible for making the same program capable of running
on multiple platforms.

Code Security

Java is secured which allow us to develop a program that is


free from virus or tampering. Java is secured because of the following
features:

Computer Programming 2 5
Week 3-4 Administering Users and Roles

 Java programs run inside a virtual machine (JVM). The Java


Virtual Machine is an abstract machine that is implemented by
emulating software on a real machine. Typically the program
(created from another language like C) directly interacts with
the operating system and if the program is infected with virus,
it will definitely affect the operating system, unlike in Java
program will not directly run though the operating system.

 The Class Loader is responsible for loading classes into Java


Virtual Machine. It adds security by separating the package for
the classes of the local file system from those that are imported
from network sources and classes are verified before it is
loaded to JVM.

 The Bytecode Verifier is responsible for traversing the


bytecode and checking the code fragments for illegal code that
can violate access right to object. It checks the bytecodes for
the correct number and type of operands, data types are not
accessed illegally, the stack is not over or underflowed and that
methods are called with the appropriate parameter types.

Robust

Robust means strong and effective in all or most situations and


condition. Java uses strong memory management and automatic
garbage collection mechanism. It has no pointers that avoids
security problem. There is an exception handling and type
checking mechanism. The Java Compiler checks the program for
any errors and interpreter checks any run time error.

Architecture-neutral

Architecture refers to the processor (CPU Architecture), Java


programs can run on any processors without considering the
architecture or vendor (providers). The languages like C or C++ is

6
MODULE OF INSTRUCTION

architecture dependent which means you need to have a separate


program for 32-bit and 64-bit Operating System.

Portable

According to Sun Microsystem:

“Portability = Platform Independent + Architecture Neutral”

Language Portability is when you can do the WORA ("Write


once, run anywhere") program. Java bytecode can be ported to
any platform regardless its architecture. It's a combination of
platform independence and architectural neutral that makes Java
portable.

Dynamic

Byte code makes Java become dynamic and can adapt to an


evolving environment. New features can be easily integrated or
the software can be easily extended without creating a new
version.

High Performance

Even though Java is an interpreted language the execution speed


of Java programs improved significantly because of just-in-time
compilation (JIT). Java is also faster compared to any interpreted
language because it uses byte code that is close to native code.

Computer Programming 2 7
Week 3-4 Administering Users and Roles

Multithreaded

Multithreading is a capability of a single program to execute


several tasks independently and continuously. Playing music
while downloading the video file in one program is an example of
multithreading. Multithreading is important for multimedia,
network programming etc.

Distributed

Distributed computing is a model wherein the components of a


software are located in multiple networked computers working
together to achieve common goals. In this way, it will improve the
efficiency and performance of the software. For example, in a 3-
tier model, rendering user interface is performed in one computer,
another computer conducts reading and writing to the database
and business logic is done in another computer. Java allows you to
create distributed software, since networking capability is
integrated into it.

LESSON SUMMARY:

In this lesson, you should have been introduced to Java.

 Java was developed in 1991 by James Gosling.

 Java is a programming language and a platform.

 Java code generates bytecodes after compilation and


interpreted by JVM.

8
MODULE OF INSTRUCTION

 Java is simple, object-oriented, platform independent, secured,


robust, architecture neutral, portable, dynamic, high
Performance, multithreaded and distributed.

Computer Programming 2 9
MODULE OF INSTRUCTION

Getting to know the programming


environment

In this module we are going to know the programming environment of


Java. We are also going to discuss on how to write, compile and run
Java programs using Netbeans IDE (Integrated Development
Environment) and Text Editor.

At the end of this lesson you should be able to:

- Write simple Java code in Text Editor and Netbeans.

- Compile and run Java code using Command Line and


Netbeans.

- Differentiate the three types of error, the syntax errors, runtime


errors and logical errors.

A. The “Hello World!” application, your first Java Program

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:

- Java Standard Edition (SE) Development Kit 8 (JDK8).

- A text editor, an example of this is Notepad.

Let’s start creating the “Hello World” program. The following are the
steps to create the program:

Step1 : Start the text editor.

Computer Programming 2 1
Week 2 Getting to know the programming environment

In this case we are going to use Notepad. Notepad is found in the


Accessories folder of the Start Menu.

Step 2: Write the source code in Notepad text editor.

2
MODULE OF INSTRUCTION

3. Save the source file.

We need to save the file as HelloWorld.java but before we do that we


need to first create a separate folder (let's name it JAVAPROGRAMS)
in drive C, the folder will be also used for all our future Java source
codes.

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

Step 4. Compiling the source code using the windows command


line.

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

To compile the Java source file we need to enter “JavaC [filename]”


in the command line, in our case we should enter “JavaC
HelloWorld.java”.

As we discuss in the phases of a Java program, the compilation


process generates bytecodes, in this case the HelloWorld.class will be
created and this contains the actual Java bytecode.

Computer Programming 2 7
Week 2 Getting to know the programming environment

To run the Java program, we need to enter “Java [filename]” or in our


case “Java HelloWorld”. You have just run your first program and
displayed the message, “Hello World!”

Resolving an error: "javac is not recognized as an internal or


external command"

If there is a problem occuring during the compilation like the figure


below, we need to set the JavaC path in the command prompt because
Java compiler or JavaC does not recognize in command prompt. What
we perform during the compilation is call or executes JavaC program
using command line, the error occurs because we are calling a program
which is not present in the current directory. To set the path, we need
to locate the directory of the JavaC which is by default it is located in

8
MODULE OF INSTRUCTION

"C:\Program Files\Java\jdk[version]\bin". Once the path was set for


JDK all files and programs inside the path directory (such as JavaC,
Java, etc.) will be available to be executed in the command line.

There are two ways to set Java path, one is temporary and other one is
permanent.

1. Setting the temporary path of JavaC


a. Launch command prompt
b. Enter the path command, for example,
“path C:\Program Files\Java\jdk1.7.0_03\bin”

Computer Programming 2 9
Week 2 Getting to know the programming environment

2. Setting permanent path of JDK.


a. On your desktop, right click the computer icon, then
click properties.

b. Click the advance system settings

c. Select the Advance tab and click the environment


variables

10
MODULE OF INSTRUCTION

d. Click the new button of user variable.

Computer Programming 2 11
Week 2 Getting to know the programming environment

e. On the variable name field enter the “path” word

12
MODULE OF INSTRUCTION

f. Copy the path of the JDK bin folder.

Computer Programming 2 13
Week 2 Getting to know the programming environment

g. Paste the copied path in the variable value field. Then


click all the OK buttons from all the windows you have
opened.

B. Errors

The example source code that was provided in this module is


free from error, if it happens that you still encountered error
during compilation aside from unrecognized JavaC you
probably got a syntax error and this section will be able to help
understanding your error. There are three types of error that
you might encounter in Java programming:

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.

 Misspelled keyword, variable and method names or


incorrect used of capitalization.

The figures above demonstrate a program that has


syntax errors. After compilation of the program, the
compiler encountered two errors. The first error
message tells us that we had an error on line 1 of our

Computer Programming 2 15
Week 2 Getting to know the programming environment

program and it is pointed on the word publix, which is a


misspelled word for public. The second error message
suggests that we had an error in line 6 and pointed in
between of the words Public and static, as you can see
the first letter of the word Public is in upper case and it
is expected to be in lower case.

 Missing semi-colon at the end of the statement or


incorrect used of symbols.

The program above obviously produces errors, the


violations are, first the use of comma (,) instead of dot
(.) and the second one is missing semi-colon at the end
of the statement. You can compile the program above to
see the generated error message.

 Brackets such as curly braces “{}”, parentheses “()“


and square brackets “[]” is not properly matches. Never
forget to enclose your brackets, make it a habit to type
the brackets in pair (opening and closing bracket).

Runtime Errors

Runtime errors only occur after compilation (when there is


no syntax error in the program) and running your program.
Runtime is when the program is running therefore you can
only encounter runtime error during execution of the
program or when you are using your program. The
common examples of these are, trying to open a file, but

16
MODULE OF INSTRUCTION

the file doesn’t exist or is corrupted and when you try to


execute division by zero.

The figure above is a sample program that has no syntax


error, but will produce runtime error and it has a statement
that performs a division by zero. The figure below shows
that the program was successfully compiled and didn’t
produce syntax error, however when we tried to run the
program, we encountered runtime error. The message tells
us that we are executing division by zero, which is not
possible or incorrect.

Logical Errors

Computer Programming 2 17
Week 2 Getting to know the programming environment

Logical errors also occur once the program is in use and


these errors will not interrupt the execution of the program.
Errors are those where the program is running smoothly,
but produces unwanted or unexpected result from what you
designed. The common examples of these are:

 Incorrect used of mathematical operation like using


of + symbol for subtraction.
 Displaying the incorrect message.
 Using data from incorrect source.

The figure below is an example that demonstrates a logical


error. As you can see there is no error message being
shown or the program was not interrupted, however we can
notice that there is something wrong in the output, we want
the program to show the addition of “2” and “2” but instead
it displayed the concatenated number “22”. Logical errors
are considered the most difficult type of errors to fix
because it is not clear where the errors originate since it
didn’t display any information about the error.

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.

In this part of the lesson we are going to discuss writing


and compiling Java program using NetBeans. Netbeans is
an Integrated Development Environment or IDE, it is a
programming environment that provides comprehensive
facilities to programmers for Developing Java programs.
NetBeans contains a source code editor, GUI Builder,
Compiler, interpreter and a debugger.

Step 1: Start NetBeans

To open the NetBeans program, double click the NetBeans


shortcut icon in your desktop.

The figure below shows the graphical user interface (GUI)


of the NetBeans IDE.

Computer Programming 2 19
Week 2 Getting to know the programming environment

Step 2. Creating a project.

To create a project, in the IDE menu bar choose File then


click New Project.

20
MODULE OF INSTRUCTION

After clicking the New Project, a New Project dialog bar


will show up. On the category list, select Java and on the
Project list, select the Java Application, then click the Next
button.

Computer Programming 2 21
Week 2 Getting to know the programming environment

In the New Application Dialog, do the following (as shown


in the figure below):

 In the Project Name field change the value to


JavaPrograms.
 Leave the default value of the Project Location, by
default our project is located in
C:\Users\<user>\Documents\NetBeansProjects
directory and all the files will be saved in
C:\Users\<user>\Documents\NetBeansProjects\Jav
aPrograms.
 Leave the Use Dedicated Folder for Sharing
Libraries unchecked.
 On the Create Main Class field, enter
“HelloWorld” and then click the Finish button.

The Java Application project is now created and opened in


the IDE. The IDE will have the following components:

 Projects window displays all projects loaded in the


IDE and it is presented in a tree view. This window
shows the components of the project such as source
files, libraries, etc.

22
MODULE OF INSTRUCTION

 Source Code Editor Window where you can write


Java source code.
 Navigator window where you can navigate
elements within the selected class.

Step 3. Writing your program in NetBeans IDE...

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.

Let us now create a program that displays “HelloWorld”


message. Replace the line of code:

// TODO code application logic here

with this statement:

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.

Step 4. Compiling and Running your program in NetBeans


IDE.

NetBeans IDE has Compile on Save feature, it


automatically compiles the Java source file after saving.
Therefore, we don’t need to manually compile the project
in order to run it.

NetBeans IDE has a real time syntax error checker, the


error icon (red glyph in the left margin) and red underline
on the statement will automatically show up if you typed a
misspelled keyword or forgot to enter the required symbol
(anything that violates the syntax).

24
MODULE OF INSTRUCTION

There are three ways to run your program in NetBeans


IDE:

 Select the Run on the menu bar then click Run


Project.

 Click the Run Icon on the Tool bar

 Press F6

Computer Programming 2 25
Week 2 Getting to know the programming environment

The output of the program will be shown in the output


window of NetBeans IDE.

LESSON SUMMARY:

1. You can write java program using notepad and compile it using
windows command line.

2. Set Java compiler path in command line to resolve "javac is not


recognized as an internal or external command" error.

3. There are three types of error in java these are Syntax errors, run
time errors and logical errors.

4. NetBeans IDE is a programming environment that provides


comprehensive facilities to programmers for Developing Java
programs.

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.

At the end of this lesson you should be able to:

- Recognize the parts of Java program.

- Apply Java comments in your program.

- Identify Java literals, primitive data types, variable types and


identifiers.

- Develop a simple program using the concepts mentioned


above.

A. Dissecting a Java program

Let us try to dissect your first Java program:

/**
* 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

All programs should begin with a comment to define the


purpose of it and this will also serve as reference for other
programmers or future used. The comments are not actually part of the
program, the compiler will not generate bytecodes for the comments or
it will just ignore during the compilation process.

2. Class definition
public class HelloWorld

Every Java program is a class. This part of the program


indicates the declaration of the class and we used the class keyword to
define it. All succeeding codes must be placed inside the class
declaration.

The public keyword is an access modifier, it indicates that our


class is accessible anywhere. We will be discussing more about access
modifiers later.

HelloWorld indicates the name of the class. The class name


must be the same as the file name of this program. In this case the
program is saved as HelloWorld.java.

The coding guidelines for naming class are:

 Class name must start with a letter, an underscore or a dollar


sign. It is a good practice that you use uppercase letter at the
beginning of the word, and in the case that the class name is
more than one word, every first character of the word should be
in upper case. For example HelloWorld.
 Class name must only contain letters, digits, underscores or
dollar signs. Always remember that the class name must not
contain whitespace. The

Reserved word is not allowed to use as class name. We are going


to identify all the Java reserved words later.

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
{

Since the method also contained codes or block of codes, opening


curly brace is also needed to indicate the beginning of the method.

6. Output Statement
System.out.println("Hello World!");

The System.out.println( ) is an output statement used in Java. This


statement will print any text inside the double quotes and add a new line at the
end of the printed text. Since the "Hello World!" was placed inside the
System.out.println( ) statement therefore it will output on the screen the text
Hello World!.

7. Two Right curly braces (or closing curly braces)


}}

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:

1. You should always save your Java program with a filename


extension .java.
2. Your java program filename should match the name of your
class declaration. For example, public class HelloWorld should
be saved as HelloWorld.java.

Computer Programming 2 3
Week 3-4 Programming Fundamentals

B. Java Comments

The Comment is an understandable explanation or notes of a code in a


program and it makes the code easier to understand. Although comment is
part of the program, it is not translated into bytecode during the compilation,
the compiler will just ignore the comment.

Comments are very useful, especially in a big project where several


programmers are working together and sharing codes with each other. It
would be very difficult or time consuming reading others code, but having
comments along with code you can easily understand the purpose of the code.
Even you are not working on a team comments are still very useful, as a
programmer we write a tremendous line of codes and I am sure that you will
not be able to recall all the codes that you have written that's why we need
comments to remind us about what we have written. There are three types of
comments in Java these are single line comments, multi-line comments and
documentation comments.

1. Single line comments.


To have a single line comment you need to place two forward slashes
// before the text. All text after the // will be treated as a comment. For
example:
// This is a single line comment.

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
*/

C. Java Statements and blocks

A statement is an action that is defined in the program to perform a


certain task. The common actions include variable declarations, assigning
value and calling and defining the method, traversing collection and
performing decision construct.
A statement may consist of one or more lines of code that ends in a
semicolon. An example of a single statement is:
System.out.println(“Hello World!”);

A block is a group of zero or more statements enclosed in opening and


closing curly {} brackets and can contain nested blocks. The following code
shows an example of a block:

public static void main(String[] args){ //begin block


System.out.println("Hello World!");
System.out.println("Welcome to Java!");
} //end block

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

Identifiers represent the name of variable, method, class, package and


interface. It is simply used to identify a declaration. In the HelloWorld program,
HelloWorld, args, main and System are 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.

The following are the examples of invalid identifiers:


 1stInput - Identifier begins with a number.
 Hello World - Identifier contains whitespace or special character.
 O'Reilly - Identifier contains apostrophe or special character.
 static - Static is a java keyword.

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)

5. For constant variable, the convention changes slightly, we need to


capitalize all the letters and separate the succeeding words with
underscore. For example, MAX_CREDIT = 10;
6. Avoid using underscore and dollar ($) sigh at the start of the identifier. We
only use underscore (at the start of an identifier) in an inevitable situation
where we need to use the reserved word as an identifier. For example,
_for, _true. And in some cases you may find a dollar sign (at the
beginning of the identifier) in auto-generated identifiers.

E. Java Keywords

Keywords are reserved words defined by Java for specific purposes. It


cannot be used as an identifier or name for class, method, variable, etc.
Please refer below for the list of keywords.

abstract double Int super


assert else interface switch
boolean enum long synchronized
break extends native this
byte final new throw
case finally package throws
catch float private transient
char for protected try
class goto public void
const if return volatile
continue implements short while
default import static

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

A Java literal is a constant value represented directly in the code.


Literals can be assigned to any primitive type variable. The following are
the different literals in Java:
 Integer Literals
 Floating-Point Literals
 Boolean Literals
 Character Literals
 String 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.

You can express floating-point literals either in decimal form or


scientific notation. The following are the examples of floating-point literal
expressed in scientific notation:
 The scientific notation for 1234.56 is 1.23456 * 103 can be
written as 1.23456E3 or 1.23456E+3 in Java program.
 The scientific notation for 0.00123456 is 1.23456 * 10-3 can be
written as 1.23456E-3 in Java program.

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.

A character literal can be:


 A plain character (e.g., 'x')
 A Unicode character (e.g., '\u02C0'). A Unicode character is a 16-
bit character set, and it allows the inclusion of symbols and
special characters from other languages.
 An escape sequence (e.g., '\n'). An escape sequence is a character
preceded by a backslash (\) and followed by a character that has
special meaning to the compiler. Below are the Java escape
sequences:

Escape Sequence Character Represented

\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.

G. Primitive Data Type

A data type is a classification of a particular type of data. It


specifies what kind of value can be stored in a particular data item and
determines how much space it occupies in storage. There are eight
primitive data types in Java, these are byte, short, int, long, double, float,
boolean and char.

byte

 byte data type is an 8-bit signed integer


 byte data type can hold values from -128 to 127 (or -27 to 27 -
1)
 The default value for byte data type is 0
 It saves memory, it only consumes eight bits as against to 32
bits for integer.
 Examples are:
byte b1 = -60;
byte b2 = 101;

short

10
MODULE OF INSTRUCTION

 short data type is a 16-bit signed integer


 short data type can hold values from -32768 to 32767 (or -215
to 215 - 1)
 The default value for short data type is 0
 Like bytes, it also saves memory and better alternative to int
data types, particularly if your data falls within the specified
range.
 Examples are:
short s1 = -129;
short s2 = 128;

int

 int data type is a 32-bit signed integer


 int data type can hold value from - 2,147,483,648 to
2,147,483,647 (or -231 to 231-1)
 The default value for int data type is 0
 It is usually used as the default data type for integral values.
 Examples are:
int i1 = -32769;
int i2 = 32768;

long

 long data type is a 64-bit signed integer


 long data type can hold value from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 (or 263 to 263-1)
 The default value for long data type is 0L
 Long data type is used when you need a bigger range than int.
 Examples are:
long l1 = -32769L;
long l2 = 32768L;

float

 float data type is a 32-bit IEEE 754 floating point


 float data type can hold a negative value from -3.4028235E+38 to -
1.4E–45, and a positive value from 1.4E -45 to 3.4028235E +38.
 The default value for float data type is 0.0F
 float data type consumed less memory as compare to double.
 Examples are:
float f1 = -1.2345F;
float f2 = 3.4028235E+38F;

Computer Programming 2 11
Week 3-4 Programming Fundamentals

double

 double data type is a 64-bit IEEE 754 floating point


 double data type can hold a negative value from -
1.7976931348623157E+308 to -4.9E-324, and a positive value from
4.9E - 324 to 1.7976931348623157E + 308.
 The default value for double data type is 0.0D
 The double type is twice as big as float type, so you should use this
type because it is more accurate than the float type.
 Examples are:
double d1 = 1.23456;
double d2 = -12.3456D;
double d3 = 12.3456D;

boolean

 boolean data type represents 1 bit of information.


 boolean data type can only have a value of either true or false.
 The default value for boolean data type is false.
 The double type is twice as big as float type, so you should use this
type because it is more accurate than the float type.
 Example: boolean odd = true;

char

 char data type represents single 16-bit Unicode character.


 char data type can have a value from \u0000 (or 0) to \uFFFF (65,535)
 The default value for char data type is '\u0000'
 Char data type is used to store any single character and it must be
enclosed in single quotes.
 Examples are:
char letterA = ‘a’; //The letter a
char newLine = ‘\n’; //A new line
char hash = ‘\u0023’; //for hash sign (#)

The Unicode standard has been extended to allow up to 1,112,064


characters. The Java character data type can only support 65,535 characters
and it is sometimes referred to as the Basic Multilingual Plane (BMP) and
those characters that go beyond the 16-bit (65,535) limit is called
supplementary characters. Supplementary characters are represented as a pair
of char values and it can be handled using String data type. String is not a
primitive data type (it is a Class or non-primitive data type). A String data
type contains multiple characters and enclosed in double quotes.

12
MODULE OF INSTRUCTION

For example:
String message = “Hello world!”;
String supplementaryCharacter = “\uD801\uDC00”;

H. Variables

Variable is used to store a specific value or literals that can be used


later in a program. Since it holds value, you may assign or call its value in
a statement or block. Variable has data type and name. Variable Data Type
identifies the kind of value that you can store, like number or text.

Declaring and Initializing Variable

To declare a variable you need to have the following:

<data type> <name> [= initial value]

Data type and name are both required and initial value for variable is optional.

Below is the example of implementation of variables in a program:

The output of the program is:

The line 4 or this code

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.

Line 5 or this code

is also a variable declaration and it has a variable name of centimeter and int
data type and has no initial value.

Line 6 or this code

is a statement where we assign value to variable centimeter. We call this


statement as a variable assignment. This statement will just perform the
operation and assign the result to variable centimeter. In this case will just
multiply the value of meter (which is 2) to 100 and will result to 200. The
value of centimeter now is 200.

Line 7 and 8 or this code

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.

Below is the implementation System.out.print() in java program::

The output of the example above is:

Below is the example of displaying variable using System.out.println():

The output of the example above is:

Computer Programming 2 15
MODULE OF INSTRUCTION

4. Operators and Operator Precedence

In this module, we are going to discuss the different operators that can
be use in Java.

At the end of this lesson, you should be able to:

- Identify the different operators in Java.

- Enumerate the operator precedence.

- Develop a simple program using the concepts mentioned


above.

4.1 Operator

An operator is a symbol that is used to perform a specific


mathematical or logical operation. In Java, we use different types of
operators and these are the following:

 Arithmetic Operators
 Relation Operators
 Logical Operators
 Conditional Operator
 Bitwise and Bit Shift Operators
 Assignment Operators

4.1.1 The Arithmetic Operators

Arithmetic operators are used to perform a basic computation


in a program and it operates the same way that they are used in
algebra. The table below shows the list of arithmetic operators:

*Let us assume that the value of x = 15 and y = 5


Operator Example Result Description
+ (Addition) x+y 20 Adds the value of x and y

Computer Programming 2 1
Week 3-4 Operator and Operator Precedence

- (Subtraction) x-y 10 Subtracts the value of y from x


*
x*y 75 Multiplies the value of x by y
(Multiplication)
/ (Division) x/y 3 Divides the value of x by y.
Divides the value of x by y and get the
% (Modulus) x%y 0
remainder.
x++ (post) 15
++ (Increment) Increment the value of x by 1.
++x (pre) 16
x—(post) 15
-- (Decrement) Decrement the value of operand by 1.
--x (pre) 14

Below is the sample program that implements arithmetic operators:

public class ArithmeticOperatorsDemo {


public static void main(String[] args) {
int x = 13;
int y = 9;
double result = 0;

System.out.println("Variable values:");
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("result = " + result);

System.out.println(); //add a new line


System.out.println("Arithmetic Operation:");

result = x + y; //performs addition


System.out.println("Addition: x + y = " + result);

result = x - y; //performs subtraction


System.out.println("Subtraction: x - y = " + result);

result = x * y; //performs multiplication


System.out.println("Multiplication: x * y = " + result);

result = x / y; //performs division


System.out.println("Division: x / y = " + result);

result = x % y; //gets the remainder


System.out.println("Modulus: x % y = " + result);

2
MODULE OF INSTRUCTION

result = x++; //increment by 1


System.out.println("Increment: x++ = " + result);

result = x--; //decrement by 1


System.out.println("Decrement: x-- = " + result);
}
}

The output of the program above is:

The Relational Operators

Relational operator is an operator that compares two values.


When you use a relational operator in an operation the result is a
Boolean value (either true or false). The table below shows the list of
relational operators:

*Let us assume that the value of x and y is 5


Operator Example Result Description

Checks if the two values are equal,


== (equal to) x==y true if yes then the result is true,
otherwise false.

Checks if the two values are not


!= (not equal to) x!=y false equal, if yes then the result is true,
otherwise false.

Computer Programming 2 3
Week 3-4 Operator and Operator Precedence

Checks if the value of x is greater


> (greater than) x>y false than the value of y, if yes the result
is true, otherwise false.

Checks if the value of x is less than


< (less than) x<y false the value of y, if yes the result is
true, otherwise false.

Checks if the value of x is greater


>= (greater than than or equal to the value of y, if
x>=y true
or equal to) yes the result is true, otherwise
false.

Checks if the value of x is less than


<= (less than or
x<=y true or equal to the value of y, if yes the
equal to)
result is true, otherwise false.

Below is the sample program that implements relational operators:

public class RelationalOperatorsDemo {


public static void main(String[] args) {
int x = 5;
int y = 10;
int z = 5;
boolean result;

System.out.println(); //add a new line


System.out.println("Relational Operation:");

System.out.println(); //add a new line


System.out.println("Equal to:");
result = x == y; //checks if the two values are equal
System.out.println(x + " == " + y + " = " + result);
result = x == z; //checks if the two values are equal
System.out.println(x + " == " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Not equal to:");
result = x != y; //checks if the two values are not equal
System.out.println(x + " != " + y + " = " + result);
result = x == z; //checks if the two values are equal

4
MODULE OF INSTRUCTION

System.out.println(x + " != " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Greater than:");
result = y > x; //checks if the two values are not equal
System.out.println(y + " > " + x + " = " + result);
result = x > z; //checks if the two values are equal
System.out.println(x + " > " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Less than:");
result = x < y; //checks if the two values are not equal
System.out.println(x + " < " + y + " = " + result);
result = x < z; //checks if the two values are equal
System.out.println(x + " < " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Greater than or equal to:");
result = y >= x; //checks if the two values are not equal
System.out.println(y + " >= " + x + " = " + result);
result = x >= z; //checks if the two values are equal
System.out.println(x + " >= " + z + " = " + result);

System.out.println(); //add a new line


System.out.println("Less than or equal to:");
result = x <= y; //checks if the two values are not equal
System.out.println(x + " <= " + y + " = " + result);
result = x <= z; //checks if the two values are equal
System.out.println(x + " <= " + z + " = " + result);
}
}

The output of the program above is:

Computer Programming 2 5
Week 3-4 Operator and Operator Precedence

The Logical Operators

Logical operator is an operator that can only be use in an


operation with Boolean values. Like relational operator, it also returns
is a Boolean value. The table below shows the list of relational
operators:

*Let us assume that the value of x=true and y = false


Operator Example Result Description

6
MODULE OF INSTRUCTION

This operator is called Logical


AND operator. If the boolean
&& (logical
x && y False values of both operands are true,
and)
the result will be true, otherwise
false.

This operator is called Logical


OR operator. If there is one
|| (logical or) x || y True operand that has boolean values
of true, the result will be true,
otherwise false.

This operator is called Logical


NOT operator. It returns the
opposite value of its operand. If
! (logical not) !x False an operand to right is true, the
result will be false. And if the
operand to the right is false, the
result will be true.

Below is the sample program that implements logical operators:

public class LogicalOperatorsDemo {


public static void main(String[] args) {
boolean x = true;
boolean y = false;
boolean result;

System.out.println("Logical Expression:");

System.out.println(); //add a new line


System.out.println("Logical AND:");
result = x && x; //result here is true
System.out.println(x + " && " + x + " = " + result);
result = x && y; //result here is false
System.out.println(x + " && " + y + " = " + result);
result = y && x; //result here is false
System.out.println(y + " && " + x + " = " + result);
result = y && y; //result here is false

Computer Programming 2 7
Week 3-4 Operator and Operator Precedence

System.out.println(y + " && " + y + " = " + result);

System.out.println(); //add a new line


System.out.println("Logical OR:");
result = x || x; //result here is true
System.out.println(x + " || " + x + " = " + result);
result = x || y; //result here is true
System.out.println(x + " || " + y + " = " + result);
result = y || x; //result here is true
System.out.println(y + " || " + x + " = " + result);
result = y || y; //result here is false
System.out.println(y + " || " + y + " = " + result);

System.out.println(); //add a new line


System.out.println("Logical NOT:");
result = !x; //result here is false
System.out.println("!" + x + " = " + result);
result = !y; //result here is true
System.out.println("!" + y + " = " + result);
result = !(x && y); //result here is true
System.out.println("!("+ y + " && " + x + ") = " + result);
result = !(x || y); //result here is false
System.out.println("!(" + y + " || " + y + ") = " + result);
}
}

The output of the program above is:

8
MODULE OF INSTRUCTION

The Conditional Operators

Conditional operator is also called as the ternary operator because this


operator consists of three operands. The purpose of this operator is to
evaluate which value should be returned to the variable. The structure
of the expression using this operator is:

operand1?operand2:operand3

The operand1 is a Boolean expression that will be evaluated, if the


value of operand1 is true, operand2 is the value returned, otherwise
operand3 will be returned.

public class ConditionalOperatorDemo {


public static void main(String[] args) {
String result = "";
int age = 17;
result = (age >= 18) ? "qualified to Vote!" : "too young to vote!";
System.out.println(age + " is " + result);
}
}

Computer Programming 2 9
Week 3-4 Operator and Operator Precedence

The output of the program above is:

Let us discuss what happened in the program after we use the


conditional operator. The expression (age >= 18) ? "Qualified to
Vote!" : "Too young!" uses conditional operator, the first operand
here is (age >= 18) and if we evaluate this we will get the value of
false because the variable age has a value of 17 and it is not greater
than or equal to 18. Since the value of the first operand is false this
expression will return the value of operand3 which is “too young to
vote”.

Let’s try another example, this time we set the value of variable age to
19.

public class ConditionalOperatorDemo {


public static void main(String[] args) {
String result = "";
int age = 19;
result = (age >= 18) ? "qualified to Vote!" : "too young to vote!";
System.out.println(age + " is " + result);
}
}

The output of the program above is:

Bitwise and Bit Shift Operators

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:

A B A&B A|B A^B ~A


0 0 0 0 0 1
0 1 0 1 1 1
1 1 1 1 0 0
1 0 0 1 1 0

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).

 & (Bitwise And) – The result of the operation will be 1 if it


exists in both operands.
For example: 12 & 5
We need to convert both values to binary:
12 = 00001100, 5 = 00000101
Value Bit Representation
12 1 1 0 0
5 0 1 0 1
Result 0 1 0 0

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

Here is the example of Bitwise And in Java program:

Computer Programming 2 11
Week 3-4 Operator and Operator Precedence

The output for the program above is:

Here is the bit representation of the sample Java


program:
14 = 00001110, 5 = 00000101
Value Bit Representation
a = 14 1 1 1 0
b=5 0 1 0 1
Result 0 1 0 0
c = 00000100 or 4

 | (Bitwise Inclusive Or) – The result of the operation will be 1


if it exists in either operand.
For example: 9 | 13
We need to convert both values to binary:
9 = 00001001, 13 = 00001101
Value Bit Representation
9 1 0 0 1
13 1 1 0 1
Result 1 1 0 1

therefore: 12 | 5 = 13

Here is the example of Bitwise Inclussive Or in Java


program:

12
MODULE OF INSTRUCTION

The output for the program above is:

Here is the bit representation of the sample Java


program:
20 = 00010100, 16 = 00010000
Value Bit Representation
a = 20 1 0 1 0 0
b = 16 1 0 0 0 0
Result 1 0 1 0 0
c = 00010100 or 20

 ^ (Bitwise Exclussive Or) – The result of the operation will be


1 if both operands are different.
For example: 6 | 9
We need to convert both values to binary:
6 = 00000110, 9 = 00001001
Value Bit Representation
6 0 1 1 0
9 1 0 0 1
Result 1 1 1 1

therefore: 6 | 9 = 15

Here is the example of Bitwise Exclussive Or in Java


program:

Computer Programming 2 13
Week 3-4 Operator and Operator Precedence

The output for the program above is:

Here is the bit representation of the sample Java


program:
20 = 00010010, 17 = 00010001
Value Bit Representation
a = 18 1 0 0 1 0
b = 17 1 0 0 0 1
Result 0 0 0 1 1
c = 00000011 or 3

 ~ (Bitwise One’s Complement) – This operator is used to flip


the bits, it toggles each bit from 0 to 1 or from 1 to 0.
For example:
10001001 and if we flip the each bit it will result to
01110110.

 << (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

.10100001 >> 2 = 00101000


 >>> (Unsigned Right Shift Zero Fill) –This operator shifts
the left operands value to the right by the number of bits
specified in the right operand and shifted values will be filled
with zeros.
For example:
01101000 >>> 2 = 00011010
.10000001 >>> 2 = 00100000

Assignment Operators

Let us discuss first what is Assignment Statement and Assignment


Expressions.

An assignment statement is use to assign value to a variable. It uses =


(equal) operator or any assignment operators to designate a value for a
variable. The syntax for assignment statement is as follows:

<variable> = <expression>;

An expression can be a value, variable or a computation of values and


variables using operators and evaluate them to a value. For example,

m = 2; //assign value of 2 to variable m

cm = m * 100; // assign the multi to variable cm

In assignment statement, we can assign the variable to itself, for


example:

int x = 1;
x=m+1

The assignment statement x = x + 1 means, we assign the addition of x


and 1 to variable x, then the value of x becomes 2 after the statement is
executed.

In the case that we need to assign the value to a multiple variables, we


can do this:

x = y = z = 1;

Computer Programming 2 15
Week 3-4 Operator and Operator Precedence

The statement above is equivalent to:

x = 1;
y = 1;
z = 1;

Augmented Assignment Operators

Java allows you to combine arithmetic operator with assignment (=)


using Augmented Assignment Operators. The list of augment assignment
operators are as follows:

Operator Description Example


Simple assignment operator. Assigns z = x + y will
= values from right side operands to left assign value of x +
side operand. y into z
Add and assignment operator. This
operator adds right operand to the left z += 2 is equivalent
+=
operand and assign the result to left to z = z + 2
operand.
Subtract and assignment operator. This
operator subtracts right operand from z -= x is equivalent
-=
the left operand and assign the result to to z = z – x
left operand.
Multiply and assignment operator. This
operator multiplies right operand with z *= x is equivalent
*= the left operand and assign the result to to z = z * x
left operand.
Divide and assignment operator. This
operator divides left operand with the z /= 2 is equivalent
/= right operand and assign the result to to z = z / 2
left operand.
Modulus and assignment operator. This
z %= x is
operator takes modulus using two
%= equivalent to z = z
operands and assign the result to left
%x
operand.
z <<= 2 is same as
<<= Left shift and assignment operator.
z = z << 2
z >>= x is same as
>>= Right shift and assignment operator.
z = z >> x

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

Precedence of Java Operators

Operator precedence determines which operators should be the first to execute.


An operator can have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator +. The
table shows the list of operators according to precedence order.

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:

Given a complicated expression,

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,

z = ((x%2) *3) + (b/4) + 9 - c;

18
[CS202 / Computer Programming 2]
1
[Getting Input]

Getting Keyboard Input


Since we have already written a program that can output text, we are now going to make
our more interactive by allowing the user input text in our program. In this module, we are
going to discuss two ways of getting input, the first one is using Scanner class and the other
one is using JOptionPane class.
At the end of the lesson, the student should be able to:
• Create an Java program that accepts input.
• Use the Scanner class to get input through console.
 Use the JOptionPane class to get input from the keyboard through a graphical user
interface.

Using Scanner Class


In this section we are going to read user input in a console application using Scanner class.
Here’s an example of program using Scanner class:

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:

Let us try to explain each line of code:


Line 1 or this statement:

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 output of the progran above is:

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.

Let us discuss each line of code, the first statement,

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.

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


 Use decision control structures (if, if-else, switch) which allows the program to select of
specific block of code to be executed.
 Use repetition control structures (while, do-while, for) which allows the program to execute a
block of codes a number of times.
 Use branching statements (break, continue, return) which allows the program to redirect the
flow of execution.
 Create program using control structures.

Decision Control Structures


Decision control structures are statements that allow the program to decide which block of
codes to be executed based from the given condition. The conditions in decision control structures
can be expressed using boolean expression. A Boolean expression is an expression that results to
boolean values (true or false). The following are the control structures used in Java:
 if statement
 if else statement
 if - else if - else statement

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;
...
}

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


The figure below shows the execution flow of the if statement:

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!");

Below is the flowchart for the sample code above:

age >= 18

S
y
Computer Programming 2
3
Control Structures

if Statement Sample Program:

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.

The if-else statement has the form,


if( boolean_expression )
statement;
else
statement;

or can also be written as,


if( boolean_expression ){
statement1;
statement2;
...
}
else{
statement1;
statement2;
...
}

Below is the flowchart for if-else statement:

Based from the flowchart above, statement1 will be executed if the


boolean_expression evaluates to true, otherwise the statement2 will be executed.
Computer Programming 2
5
Control Structures

For example:
if(age>=18)
System.out.println("Qualified to vote!");
else
System.out.println("To young to vote!");

Below is the flowchart for the sample code above:

S S
y y

if-else Statement Sample Program:

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).

if-else if-else Statement


if-else if-else is used when the program have multiple alternative action to take. This
statement is actually an if-else statement with another if-else statement inside the else block.
Below is the form of nested-if statement:
if( boolean_expression ){
statement1;
statement2;
...
}
else{
if( boolean_expression ){
statement1;
statement2;
...
}
}

we usually write this as:


if( boolean_expression ){
statement1;
statement2;
...
}
else if( boolean_expression ){
statement1;
Computer Programming 2
7
Control Structures

statement2;
...
}
Take note that we can omit the last else block and we can add more else-if block after the
if-block.

Below is the flowchart for if-else if-else statement:

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

if-else if-else Statement Sample Program:

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).

Common Errors when using the decision control structure:


1. Only boolean value is accepted in the condition statement. For
example,
//WRONG
int num = 0;
if( num ){
// statements
}

The variable num does not hold a boolean value.


2. Using = instead of == for comparison. For example,
int num = 5;
if( num = 5 ){ //error in the condition
// statements
}

This should be written as,


int num = 5;
if( num == 5 ){
// statements
}

Course Module
3. Adding semi-colon at the end of if statement. For example,
if(num == 5);
// statements

4. Writing elseif instead of else if.


int num = 5;
if(num = 5){ //error in the condition
// statements
}elseif(num == 0){ //error, no space between else and if
// statements
}

This should be written as,


int num = 5;
if(num == 5){
// statements
}else if(num == 0){
// 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.

Below is the swith-statement form:


switch( switch_expression ){
case case_value1:
// statements
break;
case case_value2:
// statements
break;
...
Computer Programming 2
11
Control Structures

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");
}

Below is the flowchart of the example above:

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

Sample switch Statement Program:

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.

Repetition Control Structures


Repetition control structures are Java statements that allow the program to execute
statements repeatedly. Repetition control structure is also called as loop statement, you can use
this statement if you want your program to perform the desired number of actions. For example, if
you want to display String value hundred times, instead of writing hundred statements for
displaying String value you can simply write one loop statement that iterates 100 times and inside
the loop is a statement that display String value. The following are the repetition structures used
in Java:
 while
 do-while
 for loop

The while Loop


The while loop executes the statements repeatedly as long as the condition is true. The
while loop has this form:
while(loop_condition){
//loop body
statements;
}

Below is the flowchart of while loop 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++;
}

Below is the flowchart for the code snippet above:

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.

While Loop Sample Program:


Computer Programming 2
17
Control Structures

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

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.

The do-while loop has this form:

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.

Below is the flowchart of 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);

Below is the flowchart for the code snippet above:

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);

The example above will display 54321.

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.

do-while Loop Sample Program:

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

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:

for (loop_initial_expression; loop_condition; step_expression){


//loop body
statements;
}

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.

This example, is equivalent to the while loop shown below,


int x = 0;
while( x < 5 ){
System.out.print(x);
x++;
}

The following are other examples of for loops,


Example 1:

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.

while Loop Sample Program:

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.

The Nested Loop

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:

for(int x = 1; x<=3; x++)


{
for(int y = 1; y<=5; y++)
{
System.out.print(y);
}
System.out.println();
}
Computer Programming 2
25
Control Structures

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]

that can be also written as,

int[] intArray = new int[10];


Computer Programming 2
3
Array

Below is the representation of the declared array above:

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];

intArray[0] = 10; //assign 10 to the element index 0


intArray[1] = 8; //assign 8 to the element index 1
intArray[2] = 38; //assign 38 to the element index 2
intArray[3] = 80; //assign 80 to the element index 3
intArray[4] = 3; //assign 3 to the element index 4
intArray[5] = 13; //assign 13 to the element index 5
intArray[6] = 10; //assign 10 to the element index 6
intArray[7] = 21; //assign 21 to the element index 7
intArray[8] = 5; //assign 5 to the element index 8
intArray[9] = 3; //assign 3 to the element index 9

There is another way to declare, create and assign values to the array at once:

int[] intArray = { 10, 8, 38, 80, 3, 13, 10, 21, 5, 3 };

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,

System.out.println("First Element at index 0: " + intArray[0]);


System.out.println("Fifth Element at index 4: " + intArray[4]);
System.out.println("Tenth Element at index 2: " + intArray[9]);

Let us now create a program that implements Java array:

Below is the output of the sample program above:


Computer Programming 2
5
Array

Here’s another example of Java program that shows another way of assigning values to an array:

Below is the output of the sample program:

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:

int[] intArray = new int[100];


int arrayLength = intArray.length;

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];

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


intArray[i] = i+1;
}

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


System.out.print (intArray[i]);
}

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.

Let us create a program that traverse an array using for loop:


Computer Programming 2
7
Array

Below is the output of the sample program above:

Course Module
Let’s have another example of array, but this time we are going to use array of String.

Below is the output of the sample code above:


Computer Programming 2
9
Array

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

Multidimensional array is implemented as arrays of arrays. Multidimensional arrays are


declared by appending the two or more bracket pairs after the array name or data type. Below is
the example of two-dimensional array:

int[][] int2DArray = new int[5][10];

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:

//creates two-dimensional array


int[][] int2DArray = new int[2][3];

//assign the value of 1 to an element at index 0 and 0


int2DArray[0][0] = 1;
Course Module
int2DArray[0][1] = 2;
int2DArray[0][2] = 3;
int2DArray[1][0] = 4;
int2DArray[1][1] = 5;
int2DArray[1][2] = 6;

Another way to assign the above values in a multidimensional array is:

int[][] int2DArray = {{1,2,3},{4,5,6}};

Here’s an example of Multidimensional Array in Java program:

Below is the out of the sample program above:


Computer Programming 2
11
Array

Traversing Multidimensional Array using Loop

To iterate a multidimensional array, we need to iterate each dimension of the array


separately, therefore we need to use nested loop to traverse the multidimensional array. Below is
the example of a java program that traverses 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.

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


 Explain what is method and how to use it
 Define a method in a Java program
 To call and pass parameter on method in a Java program
 Explain and implement an overloading method in a Java program

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:

Below is output of the sample program above:

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,

Below is output of the sample program above:

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

Passing Arguments in Method


In the previous example, we have already tried passing arguments (value or variable
that we specified when calling a method) to methods. Now, we are going to discuss the two
ways of passing arguments to method, the first one is pass-by-value and the other one is
pass-by-reference.
We have to be cautious when passing arguments, they must match the parameters
in order, number, and compatible data type, as defined in the method. Compatible data type
means that you can pass an argument to a parameter even if they do not have the exact type
as long as they are compatible, such as passing an int value argument to a double value
parameter.
Pass-by-value
When a pass-by-value occurs, the method makes a copy of the value of the variable
passed to the method. The variable will not be affected even if there are changes made to
the parameter inside the method. For example,

The sample program above will have the output below:

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,

The sample program above will have the output below:

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

public int add(int num1, int num2, int num3){


…..
}
 Different data type of parameters.
public void swap(int num1, int num2){
…..
}
public void swap(String num1, String num2){
…..
}
Method Overloading Sample Program
Below is the example of overloading method with different number of parameter:

Below is the output of the sample program above:

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:

Below is the output of the sample program above:

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

Basic Java Object Oriented Programming

In this section, we will discuss what is object-oriented programming and its


concepts such as classes and objects. We will discuss on how to use these classes and their
members.

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


 Explain object-oriented programming and some of its concepts
 Differentiate between classes and objects
 Differentiate between instance variables or methods and class (static) variables or
methods.
 Cast primitive data types and objects
 Compare objects and determine the class of an objects

Introduction to Object Oriented Programming


Object-Oriented programming or OOP revolves around the concept of objects as
the basic elements of your programs. When we compare this to the physical world, we can
find many objects around us, such as cars, lion, people and so on. These objects are
characterized by their state (or attributes) and behaviors.
For example, a bicycle object has the states, current gear, current pedal cadence and
current speed. Its behaviors are turning, braking and accelerating. Similarly, we can define
different properties and behavior of a dog. Please refer to the table below for the examples.

Object State Behavior


Dog  Name  Barking
 Color  Fetching
 Hungry  Wagging Tail

Bicycle  Current Gear  Changing Gear


 Current Pedal Cadence  Changing Pedal Cadence
 Current Speed  Accelerating

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.

Classes and Objects


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

Car Class Object Car A Object Car B


Plate Number AAA 123 BBB 456
Instance Color Red Black
Variables Manufacturer Honda Toyota
Current Speed 60 km/hr 55 km/hr
Accelerate Method
Instance
Turn Method
Methods
Brake Method

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

Encapsulation
Encapsulation is the method of hiding certain elements of the implementation of a
certain class. By placing a boundary around the properties and methods of our objects, we
can prevent our programs from having side effects wherein programs have their variables
changed in unexpected ways.
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 Variables and Methods


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

Car Class Object Car A Object Car B


Plate Number AAA 123 BBB 456
Instance Color Red Black
Variables Manufacturer Honda Toyota
Current Speed 60 km/hr 55 km/hr
Class
Count = 2
Variable
Accelerate Method
Instance
Turn Method
Methods
Brake Method

Class Instantiation
To create an object or an instance of a class, we use the new operator. 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 );
}

public static void main(String []args) {


// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}

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.

Casting, Converting and Comparing Objects


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

Casting Primitive Types


Casting between primitive types enables you to convert the value of one data from
one type to another primitive type. This commonly occurs between numeric types. There
is one primitive data type that we cannot do casting though, and that is the boolean data
type.
An example of typecasting is when you want to store an integer data to a variable
of data type double. For example,
int varInt = 10;
double varDouble = varInt; //implicit cast
In this example, since the destination variable (double) holds a larger value than
what we will place inside it, the data is implicitly casted to data type double.
Computer Programming 2
5
Basic Java Object Oriented Programming

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

Casting Primitive Types


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

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,

Class Hierarchy for superclass Employee

The following example casts an instance of the class VicePresident to an instance


of the class Employee; VicePresident is a subclass of Employee with more information,
which here defines that the VicePresident has executive washroom privileges,
Employee emp = new Employee();
VicePresident veep = new VicePresident();
emp = veep; // no cast needed for upward use
veep = (VicePresident)emp; // must cast explicitlyCasting
Computer Programming 2
7
Basic Java Object Oriented Programming

Converting Primitive Types to Objects and Vice Versa


One thing you can't do under any circumstance is cast from an object to a primitive
data type, or vice versa. Primitive types and objects are very different things in Java, and
you can't automatically cast between the two or use them interchangeably.
As an alternative, the java.lang package includes classes that correspond to each
primitive data type: Float, Boolean, Byte, and so on. Most of these classes have the same
names as the data types, except that the class names begin with a capital letter (Short instead
of short, Double instead of double, and the like). Also, two classes have names that differ
from the corresponding data type: Character is used for char variables and Integer for int
variables. (Called Wrapper Classes)
Java treats the data types and their class versions very differently, and a program
won't compile successfully if you use one when the other is expected. Using the classes
that correspond to each primitive type, you can create an object that holds the same value.
For example,
//The following statement creates an instance of the Integer
// class with the integer value 7801 (primitive -> Object)
Integer dataCount = new Integer(7801);

//The following statement converts an Integer object to


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

// A common translation you need in programs


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

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

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.

The following code illustrates this,


class EqualsTest {
public static void main(String[] arguments) {
String str1, str2;
str1 = "Free the bound periodicals.";
str2 = str1;
System.out.println("String1: " + str1);
System.out.println("String2: " + str2);
System.out.println("Same object? " + (str1 == str2));
str2 = new String(str1);
System.out.println("String1: " + str1);
System.out.println("String2: " + str2);
System.out.println("Same object? " + (str1 == str2));
System.out.println("Same value? " + str1.equals(str2));
}
}
This program's output is as follows,
String1: Free the bound periodicals.
String2: Free the bound periodicals.
Same object? true
String1: Free the bound periodicals.
String2: Free the bound periodicals.
Same object? false
Same value? True
Computer Programming 2
9
Basic Java Object Oriented Programming

This program's output is as follows,


String str1, str2;
str1 = "Free the bound periodicals.";
The first part of this program declares two variables (str1 and str2), assigns the
literal "Free the bound periodicals." to str1, and then assigns that value to str2. As you
learned earlier, str1 and str2 now point to the same object, and the equality test proves that.
In the second part of this program, you create a new String object with the same
value as str1 and assign str2 to that new String object. Now you have two different string
objects in str1 and str2, both with the same value. Testing them to see whether they're the
same object by using the == operator returns the expected answer: false—they are not the
same object in memory. Testing them using the equals() method also returns the expected
answer: true—they have the same values.

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

Determining the Class of an Object


Want to find out what an object's class is? Here's the way to do it for an object
assigned to the variable key:
1. The getClass() method returns a Class object (where Class is itself a class) that
has a method called getName(). In turn, getName() returns a string representing the
name of the class.
For Example,
String name = key.getClass().getName();
2. The instanceOf operator. The instanceOf has two operands: a reference to an
object on the left and a class name on the right. The expression returns true or false
based on whether the object is an instance of the named class or any of that class's
subclasses.
For Example,
boolean ex1 = "Texas" instanceof String; // true
Object pt = new Point(10, 10);
boolean ex2 = pt instanceof String; // false

Course Module
Computer Programming 2
1
Inheritance, Polymorphism and Interfaces

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.

Inheritance is a major advantage in object-oriented programming since once a


behavior (method) is defined in a superclass, that behavior is automatically inherited by all
subclasses. Thus, you can encode a method only once and they can be used by all
subclasses. A subclass only need to implement the differences between itself and the
parent.

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,

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


subclass. For example,
public static main( String[] args )
{
Person ref;
Student studentObject = new Student();
Employee employeeObject = new Employee();
ref = studentObject; //Person ref points to a
// Student object
//some code here
}
Now suppose we have a getName method in our superclass Person, and we override
this method in both the subclasses Student and Employee,
public class Person
{
public String getName(){
System.out.println(“Person Name:” + name);
return name;
}
}

public class Student extends Person


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

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();

ref = studentObject; //Person reference points to a Student object


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

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


String temp = ref.getName(); //getName of Employee class is called
System.out.println( temp );
}
This ability of our reference to change behavior according to what object it is
holding is called polymorphism. Polymorphism allows multiple objects of different
subclasses to be treated as objects of a single superclass, while automatically selecting the
proper methods to apply to a particular object based on the subclass it belongs to.
Another example that exhibits the property of polymorphism is when we try to pass
a reference to methods. Suppose we have a static method print Information that takes in a
Person object as reference, we can actually pass a reference of type Employee and type
Student to this method as long as it is a subclass of the class Person.
public static main( String[] args )
{
Student studentObject = new Student();
Employee employeeObject = new Employee();
printInformation( studentObject );
printInformation( employeeObject );
}
public static printInformation( Person p ){
..
}
Computer Programming 2
9
Inheritance, Polymorphism and Interfaces

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...");
}

public void eat(){


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

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.

Why do we use Interfaces?


We need to use interfaces if we want unrelated classes to implement similar
methods. Thru interfaces, we can actually capture similarities among unrelated classes
without artificially forcing a class relationship.
Let's take as an example a class Line which contains methods that computes the
length of the line and compares a Line object to objects of the same class. Now, suppose
Computer Programming 2
11
Inheritance, Polymorphism and Interfaces

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.

Interface vs. Abstract Class


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

Interface vs. Class


One common characteristic of an interface and class is that they are both types. This
means that an interface can be used in places where a class can be used. For example, given
a class Person and an interface PersonInterface, the following declarations are valid:
PersonInterface pi = new Person();
Person pc = new Person();
However, you cannot create an instance from an interface. An example of this is:
PersonInterface pi = new PersonInterface(); //COMPILE ERRO
Another common characteristic is that both interface and class can define methods.
However, an interface does not have an implementation code while the class have one.

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;

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


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

public double getLength(){


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

public boolean isGreater( Object a, Object b){


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

public boolean isLess( Object a, Object b){


double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen < bLen);
}
Computer Programming 2
13
Inheritance, Polymorphism and Interfaces

public boolean isEqual( Object a, Object b){


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

When your class tries to implement an interface, always make sure that you
implement all the methods of that interface, or else, you would encounter this error,
Line.java:4: Line is not abstract and does not override
abstract method isGreater(java.lang.Object,java.lang.Object) in
Relation
public class Line implements Relation
^
1 error
Coding Guidelines: Use interfaces to create the same standard method definitions in may
different classes. Once a set of standard method definition is created, you can write a single
method to manipulate all of the classes that implement the interface.

Relationship of an Interface to a Class


As we have seen in the previous section, a class can implement an interface as long
as it provides the implementation code for all the methods defined in the interface.
Another thing to note about the relationship of interfaces to classes is that, a class
can only EXTEND ONE super class, but it can IMPLEMENT MANY interfaces. An
example of a class that implements many interfaces is,
public class Person implements PersonInterface, LivingThing,
WhateverInterface {
//some code here
}

Another example of a class that extends one super class and implements an interface
is,
public class ComputerScienceStudent extends Student implements PersonInterface,
LivingThing {
//some code here
}

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

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 {
..
}

public interface StudentInterface extends PersonInterface {


..
}
Computer Programming 2
1
Basic Exception Handling

Basic Exception Handling

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

Multiple Catch Blocks


A try block can be followed by multiple catch blocks. The syntax for multiple catch
blocks looks like the following:
try {
// Protected code
}catch(ExceptionType1 e1) {
// Catch block
}catch(ExceptionType2 e2) {
// Catch block
}catch(ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch blocks, but you can have any
number of them after a single try. If an exception occurs in the protected code, the exception
is thrown to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches,
in which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.
Computer Programming 2
3
Basic Exception Handling

Here is code segment showing how to use multiple try/catch statements:

Below is the output of the example above:

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.

The Finally Block


The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want
to execute, no matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax
try {
// Protected code
}catch(ExceptionType1 e1) {
// Catch block
}catch(ExceptionType2 e2) {
// Catch block
}catch(ExceptionType3 e3) {
// Catch block
}finally {
// The finally block always executes.
}
For example:
Computer Programming 2
5
Basic Exception Handling

The output of the above example is:

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

2. The feature of Java which makes it possible to execute several tasks


simultaneously
Select one:
a. Code Security
b. Multithreaded Correct
c. None of the Above
c. Robust
d. Platform independent

3. The Java feature, "write once, run anywhere", is termed as


Select one:
a. High Performance
b. None of the Above
c. Object Oriented
d. Platform independent Correct
e. Robust
4. What did java generates after compiling the java source code?
Select one:
a. Image file
b. None of the Above
c. Byte Code Correct
d. Executable file
e. Class Code

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

6. What is the extension name of a Java Source code?


Select one:
a. javac
b. j
c. java Correct
d. class
e. None of the Above
7. What is the input for Java Compiler?
Select one:
a. None of the Above
b. Code
c. Native Code
d. Source Code Correct
e. Byte Code

8. Which of the following is not the feature of java?


Select one:
a. Code Security
b. Robust
c. Platform independent
d. None of the Above
e. Static Correct

9. When was the officially released of Java?


Select one:
a. 1996
b. None of the Above
c. 1992
d. 1995 Correct
e. 1991

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.

11.Which of the following is true about Runtime errors:


Select one:
a. Runtime errors occur when there is a design flaw in your program
b. Runtime errors occur after compilation.
c. Runtime errors occur during run-time. Correct
d. All ofthe above.
e. None of the Above
12. Can we directly compile codes from notepad?
Select one:
a. Yes, Because we can call Java compiler from notepad
b. No, We can only write codes in Notepad Correct
c. Both A and C are correct. Correct
d. lt depends, if there is a compiler embedded in Notepad.

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

20. Which of the following is not a primitive data type?


Select one:
a. short
b. long
c. byte
d. none of the above
e. String Correct

21. Which of the following is not a java keyword?


Select one:
a. name Correct
b. None of the above
c. goto
d. else
e. if
22. Which of the following is not a Java comment?
Select one:
a. None of the above
b. Documentation Comments
c. Declaration Comments Correct
d. Single Line Comments
e. multi-Line Comments

23. Which of the following is not a valid Float value’?


Select one:
a. 3.4028235E+38F
b. none of the above Correct
c. 1.2345E+3
d. 1.23
e. 12345678910F
24. Which of the following is not valid variable declaration in Java?
Select one:
a. int x
b. float x
c. short x;
d. int x;
e. 1; Correct
f. None of the above
g. 2.0D;

25. Which of the following is not Java Literal?


Select one:
a. None of the above Correct
b. Integer value
c. Boolean value
d. Character value
e. Float value

26. Which of the following a valid Jaw identifier?


Select one:
a. all of the above
b. _id
c. id
d. $id
e. id_1 Correct
27. Which of the following is not an escape sequence?
Select one:
a. \t
b. \b
c. \f
d. none of the above Correct

28. Which of the following is a valid identifier?


Select one:
a. static
b. public
c. true
d. None of the above
e. name Correct
29. What is floating-point literal?
Select one:
a. By default it is double type.
b. lt could be double or float value.
c. All of the above Correct
d. An integer literal with decimal point.
e. Can be express in scientific notation.
30. Which of the following is a valid statement to accept String input?
Select one:
a. None of the above
b. string str = scan.nextShort();
c. String num = scan.nextText();
d. String str = JOptionPane.showlnputDialog(""); Correct
e. String str = scan.nextString();
31. Which of the following is a valid nextByte() return value?
Select one:
a. short value
b. int value
c. 3 Correct
d. None of the above
e. 128
32. Which of the following is a valid statement to accept int input? let us assume
that we have declared scan
as Scanner.
Select one:
a. None of the above Correct
b. short num = scan.nextlnt();
c. short num = scan.nextShort();
d. int num = scan.getlnt();
e. int num = scan.nextLong():

33. What type of value does the nextLine() returns?


Select one:
a. double
b. String Correct
c. long
d. Line
e. None of the above
34. What will happen if you use JOptionPane.showMessageDialog statement in your
program?
Select one:
a. The program will display an input dialog box that allows the user to input text and
returns String value
b. The program will display message dialog box. Correct
c. None of the above
d. The program will display message dialog box returns String value.
e. The program will display an input dialog box that allows the user to input text and
returns the correct
type value.

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()

36. Which of the following is a valid nextlnt() return value?


Select one:
a. 1010 Correct
b. None of the above
c. long value
d. 3.1416
e. floating-point literal
37. Which ofthe following does not return numeric value?
Select one:
a. nextDouble()
b. nextl_ong()
c. nextShort()
d. None of the above Correct
e. nextlnt()

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

39. Which of the following is a valid nexDouble() return value?


Select one:
a. All of the above Correct
b. 12.0
C. double value
d. floating-point literal
e. 3.1416

40. What will be the output if you execute this code?


do{System.out.println("Hello World!");}while(false);
Select one:
a. print "Hello World" infinitely
b. Do nothing
c. None of the above.
d. The code will not run because of syntax error
e. print "Hello World" Correct

41. Which is not a decision control structure?


Select one:
a. switch
b. if
c. if else
d. if else-if else
e. None of the above Correct

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

44. Which statement will check if x is equal to y?


Select one:
a. none of the above Correct
b- if (y>y)
c. if (x<>y)
d. if (x>y)
e. if (x!<y)

45. what will be the output if you execute this code?


int x=1;
switch(x){
case 1:
System.out.print("1");
case 2:
System.out.print("1");
case 3:
System.out.print("1");
default:
System.out.print("1");
}
Select one:
a. display 1
b. display 1111 Correct
c. display 1234
d. None of the above}
e. display nothing

46. What will be the output if you execute this code?


do{System.out.println("Hello World!");}while(true);
Select one:
a. The code will not run because of syntax error
b. None of the above.
C. print "Hello World"
d. print "Hello World" infinitely Correct
e. Do nothing

47. What will be the value of x after executing this code


for(int x=O; x<=10; x++) {} is run?
Select one:
a. 11 Correct
b. 10
c. 1
d. none of the above
e. 0
48. Which statement will check if x is less than y?
Select one:
a. if (x>y)?:
b. none of the above
C. if (x>y)
d. if (x<y); Correct
e. if (x<>y)

49. Which is not a repetition control structure?


Select one:
a. while
b. for
c. None of the choices
d. do while
e. switch Correct

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

55. What is the output of the code snippet below :


int[] intArray ={ 1, 2, 3, 5, 6, 7 };
for(int X = intArray.leng1h-1; x>=O; x--){System.out.print(intArray[x]);}
Select one:
a. 12356
b. none of the choices
o. The given code is not valid
d. 123567
e. 765321 Correct

56. What is the output of the code snippet below:


int[] intArray = new int[10];
for(iht x = 0; x<intArray.length; x++){System.out.print(intArray[x]);}
Select one:
a. 012356789
b. 1235678910
c. 0000000000 Correct
d. none of the choices
e. The given code is not valid

57. Which of the following declares an array of int named intArray’?


Select one:
a. All of the above Correct
b. int intArray[][];
c. int[][] intArray;
d. int intArray[];
e. int[] intArray;

58. What is the maximum index of the array: int[] intArray = { 1, 2, 3, 5, 6, 7)


Select one:
a. 4
b. None of the choices
C. 7
d. 5 Correct
e. 6

59. What is the length of the array: int[] intArray = { 1, 2, 3, 5, 6, 7 };


Select one:
a. none of the choices
b. 6 Correct
C. 7
d. 5
e. 4

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

62. Which of the following shows a valid Overloading method?


Select one:
a. void test(){} void test()[}
b. void test(int x){} void test(int y){}
C. All ofthe choices
d. none of the choices Correct
e. void test(char x, int y){} void test(im x, char y){}

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

64. Which of the following shows Overloading method?


Select one:
a. All of the above
b. None of the above
c. void test(int x){} void test(int y){}
d. void test(int x){} void test(double x){} Correct
e. void test(){} void test(){}
65. What is the output of the code snippet below :
void main()(
test(1.0);
test(1);}
void test(double x){
System.out.print(x); }
void test(int x){
System.out.print(x);}
Select one:
a. None of the choices
b. 11
c. 1.01.0
d. 1.0
e. 1.01 Correct
66. What is the return value of this method: int test(){return 1;} ?
Select one:
a. test
b. return 1
c. All of the choices
d. int
e. 1 Correct
67. What is the return type of this method: int test(){return 1;} ?
Select one:
a. 1
b. test()
C. int Correct
d. void
e. None of the above
68. what is the output of the code snippet below: void main(){test();test();} void
test(){System.out.print("1");}
Select one:
a. 11 Correct
b. None of the choices
c. 2
d. 1
e. 3
69. What is the name of this method: int test(){return 1;} ?
Select one:
a. 7
b. None of the choices
c. int
d. test Correct
e. 6
70. Which of the following is a valid method name
Select one:
a. none of the choices
b. compute Correct
c. final
d. compute grade
e. int
Quiz#9
71. Which of the following creates an instance of e class?
Select one:
a. String str = new String();
b. Test t = new Test();
c. String str = new String();
d. Object obj = new Object();
e. All of the choices Correct
72. What is the result if we execute this: "a".equals("a");?
Select one:
a. true Correct
b. None of the above
c. The code is not valid
d. "a"
e. false
73. What do you call a variable that belong to the whole class?
Select one:
a. Object Variable
b. Static Variable
c. None of the above
d. Class Method
e. Class Variable Correct
74. It is a template for creating an object?
Select one:
a. None of the above
b. Encapsulation
c. Method
d. Object Oriented
e. Class Correct
75. What is the result if we execute this: "a" instance of String; ?
Select one:
a. None of the above
b. true Correct
c. “a”
d. false
e. The code is not valid
76. What do you call e blueprint of an object?
Select one:
a. Method
b. Object
c. Constructor
d. Class Correct
e. None of the above
77. What will be the value of x if we execute this: String s = "25"; int x =
Integer.parseInt(s); ?
Select one:
a. int 25 Correct
b. 0
c. None of the above
d. String 25
e. The code is not valid.
78. Which of the following show casing object?
Select one:
a. All of the choices Correct
b. (className) object;
c. SuperClass sc = new SuperClass(); SubClass sbc = new SubClasS(); sbc =
(SubClass) sc;
d. Employee emp = new Employee(); VicePresident veep = new VicePresidenl();
veep =
(VicePresident)emp;

79. It is the method of hiding certain elements of the implementation of a certain


class?
Select one:
a. None of the above
b. Encapsulation Correct
c. Object
d. Object Oriented
e. Class
80. Which of the following will do implicit cast?
Select one:
a. None of the above
b. All of the above
c. String x = "o"; int y = x;
d. short x=1; int y = x; Correct
e. Object obj = new Object();

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()

84. It is the ability of an object to have many forms?


Select one:
a. Polymorphism Correct
b. Inheritance
c. None of the above
d. Abstraction
e. Interface

85. Which of the following is the correct way to use an interface?


Select one:
a. public class Person implements [InterfaceName] {} Correct
b. public class Person use [lnterfaceName] {}
c. public class Person extends [lnterfaceName] {}
d. public class Person apply [lnterfaceName] {}
e. None of the above

86. Which of the following class declaration is not allowed to be inherited?


Select one:
a. public final class Person {} Correct
b. class Person{}
c. public abstract class Person {}
d. None of the above
e. public class Person {}
87. Which of the following is the correct way to define an interface?
Select one:
a. public [lnterfaceName] {}
b. public class interface [lnterfaceName] {}
c. public interface [|nterfaceName] {} Correct
d. interface: [lnterfaceName]
88. What keyword is used to perform class inheritance?
Select one:
a. None of the above
b. extends Correct
c. inherits
d. derives
e. implements
89. What do you call a class that inherits a class?
Select one:
a. Superclass
b. Subclass Correct
c. Class
d. Parent class
e. None of the above
100. Which of the following is true about Interface?
Select one:
a. All of the above Correct
b. It defines a standard and public way of specifying the behavior of classes
c. lt is a special kind of block containing method signatures only
d. It defines the signatures of a set of methods without the body
e. It is use to remodel multiple inheritance which allows a class to have more than
one superclass

Vous aimerez peut-être aussi