Java Hand Outs

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

1 Introduction to Java

1. 1 Objectives
In this section, we will be discussing a little bit of Java history and what
is Java Technology. We will also discuss the phases that a Java program undergoes.

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

Describe the features of Java technology such as the Java virtual machine,
garbage collection and code security
Describe the different phases of a Java program

1.2 Java Background


1.2.1 A little Bit of History
Java was created in 1991 by James Gosling et al. of Sun Microsystems. Initially
called Oak, in honor of the tree outside Gosling's window, its name was changed to
Java because there was already a language called Oak.

The original motivation for Java was the need for platform independent language
that could be embedded in various consumer electronic products like toasters and
refrigerators. One of the first projects developed using Java was a personal hand-held
remote control named Star 7.

At about the same time, the World Wide Web and the Internet were gaining
popularity. Gosling et. al. realized that Java could be used for Internet programming.

1.2.2 What is Java Technology?

A programming language
As a programming language, Java can create all kinds of applications that you
could create using any conventional programming language.

A development environment
As a development environment, Java technology provides you with a large
suite of tools: a compiler, an interpreter, a documentation generator, a class file
packaging tool, and so on.

An application environment
Java technology applications are typically general-purpose programs that runs
on any machine where the Java Runtime Environment (JRE) is installed.

A deployment environment
There are two main deployment environments: First, the JRE supplied by the
Java 2 Software Development Kit (SDK) contains the complete set of class files for all
the Java technology packages, which includes basic language classes, GUI component
classes, and so on. The other main deployment environment is on your web browser.
Most commercial browsers supply a Java technology interpreter and runtime
environment.

1.2.3 Some Features of Java

The Java Virtual Machine


The Java Virtual Machine is an imaginary machine that is implemented by
emulating software on a real machine. The JVM provides the hardware platform
specifications to which you compile all Java technology code. This specification enables
the Java software to be platform-independent because the compilation is done for
a generic machine known as the JVM.

A bytecode is a special machine language that can be understood by the Java


Virtual Machine (JVM). The bytecode is independent of any particular computer
hardware, so any computer with a Java interpreter can execute the compiled Java
program, no matter what type of computer the program was compiled on.

Garbage Collection
Many programming languages allow a programmer to allocate memory during
runtime. However, after using that allocated memory, there should be a way to
deallocate that memory block in order for other programs to use it again. In C,
C++ and other languages the programmer is responsible for this. This can be difficult
at times since there can be instances wherein the programmers forget to
deallocate memory and therefore result to what we call memory leaks.

In Java, the programmer is freed from the burden of having to deallocate that
memory themselves by having what we call the garbage collection thread. The
garbage collection thread is responsible for freeing any memory that can be freed. This
happens automatically during the lifetime of the Java program.

Code Security
Code security is attained in Java through the implementation of its Java
Runtime Environment (JRE). The JRE runs code compiled for a JVM and performs
class loading (through the class loader), code verification (through the bytecode verifier)
and finally code execution.

The Class Loader is responsible for loading all classes needed for the Java
program. It adds security by separating the namespaces for the classes of the local file
system from those that are imported from network sources. This limits any Trojan horse
applications since local classes are always loaded first. After loading all the classes,
the memory layout of the executable is then determined. This adds protection against
unauthorized access to restricted areas of the code since the memory layout is
determined during runtime.
After loading the class and lay outing of memory, the bytecode verifier then
tests the format of the code fragments and checks the code fragments for illegal code
that can violate access rights to objects.

After all of these have been done, the code is then finally executed.

1.2.4 Phases of a Java Program


The following figure describes the process of compiling and executing a Java program.

The first step in creating a Java program is by writing your programs in a text
editor. Examples of text editors you can use are notepad, vi, emacs, etc. This file is
stored in a disk file with the extension .java.

After creating and saving your Java program, compile the program by using the
Java Compiler. The output of this process is a file of Java bytecodes with the file
extension .class.

The .class file is then interpreted by the Java interpreter that converts the
bytecodes into the machine language of the particular computer you are using.
2 Getting to know your Programming Environment
2.1 Objectives
In this section, we will be discussing on how to write, compile and run Java
programs. There are two ways of doing this; the first one is by using a console and a
text editor. The second one is by using NetBeans which is an Integrated
Development Environment or IDE.

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


Know the Netbeans environment
Create a Java program using NetBeans

2.2 Introduction
An IDE is a programming environment integrated into a software
application that provides a GUI builder, a text or code editor, a compiler and/or
interpreter and a debugger.

Make sure that before you do this tutorial, you have installed Java and NetBeans
in your system. For instructions on how to install Java and NetBeans, please refer to
Appendix A. For the Windows XP version of this section, please refer to Appendix B.
Before going into details, let us first take a look at the first Java program you will be
writing.

2.3 My First Java Program

public class Hello


{
/**
* My first java program
*/
public static void main(String[] args) {
//prints the string "Hello world" on screen
System.out.println("Hello world!");
}
}

Before we try to explain what the program means, let's first try to write this
program in a file and try to run it.

2.4 Using NetBeans


In this part of the lesson, we will be using NetBeans, which is an Integrated
Development Environment or IDE. An IDE is a programming environment integrated
into a software application that provides a GUI builder, a text or code editor, a compiler
and/or interpreter and a debugger.

Step 1: Run NetBeans


To Run NetBeans, click on the shortcut icon found on your desktop or go
Programs then look for NetBeans.

Step 2: Make a Project


Click on File Menu then New Project. After doing this, a New Project dialog will
appear. Now click on Java Application and click on the NEXT button.

Now set the Name and Location of the Project


If you want to change the project location click the Browse button then select a new
directory.

Finally, on the Create Main Class textfield, type in Hello as the main class' name, and
then click on the FINISH button.

Step 3: Type in your program


As shown below, NetBeans automatically creates the basic code for your Java
program. You can just add your own statements to the generated code. On the left side
of the window, you can see a list of folders and files that NetBeans generated after
creating the project. This can all be found in your MYJAVAPROGRAMS folder, where
you set the Project location.

The folders and files that The code Netbeans


Netbeans generate after automatically creates for
you created the project. you
These can all be found in
youre
MYJAVAPROGRAMS
folder

Now, try to modify the code generated by NetBeans. Ignore the other parts of the
program for now, as we will explain the details of the code later. Insert the code:

System.out.println("Hello world!");

after the statement, //TODO code application logic here.


Step 4: Run your program
To Run your program, click Run -> Run File or Shift+F6 or Click the Run Command.

Program output
2.5 Exercises
1. Create a new project and name it with your family name, then create a class and
name it with your first name. The program should output:

Welcome to Java Programming [your name]!!!!

2. Create another class named: My Song or My Poem in the same project. The program
should output the title of your favorite song or poem including the first stanza.

3 Programming Fundamentals
3.1 Objectives
In this section, we will be discussing the basic parts of a Java program. We will start by
trying to explain the basic parts of the Hello.java program introduced in the previous
section. We will also be discussing some coding guidelines or code conventions along
the way to help in effectively writing readable programs.

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


Identify the basic parts of a Java program
Differentiate among Java literals, primitive data types, variable types ,identifiers
and operators
Develop a simple valid Java program using the concepts learned in this chapter

3.2 Dissecting my first Java program


Now, we'll try to dissect your first Java program:

public class Hello


{
/**
* My first java program
*/
public static void main(String[] args) {
//prints the string "Hello world" on screen
System.out.println("Hello world!");
}
}

The first line of the code,

public class Hello

indicates the name of the class which is Hello. In Java, all code should be placed inside
a class declaration. We do this by using the class keyword. In addition, the class uses
an access specifier public, which indicates that our class in accessible to other classes
from other packages (packages are a collection of classes). We will be covering
packages and access specifiers later.

The next line which contains a curly brace { indicates the start of a block. In this code,
we placed the curly brace at the next line after the class declaration, however, we can
also place this next to the first line of our code. So, we could actually write our code as:

public class Hello


{
or
public class Hello {

The next three lines indicate a Java comment. A comment is something used to
document a part of a code. It is not part of the program itself, but used for
documentation purposes. It is good programming practice to add comments to your
code.

/**
* My first java program
*/

A comment is indicated by the delimiters /* and */. Anything within these


delimiters are ignored by the Java compiler, and are treated as comments.
The next line,

public static void main(String[] args) {

or can also be written as,

public static void main(String[] args)


{

indicates the name of one method in Hello which is the main method. The main
method is the starting point of a Java program. All programs except Applets written in
Java start with the main method. Make sure to follow the exact signature.

The next line is also a Java comment,

//prints the string "Hello world" on screen

Now, we learned two ways of creating comments. The first one is by placing the
comment inside /* and */, and the other one is by writing // at the start of
the comment.

The next line,


System.out.println("Hello world!");
prints the text Hello World! on screen. The command System.out.println(),
prints the text enclosed by quotation on the screen.

The last two lines which contains the two curly braces is used to close the main method
and class respectively.

Coding Guidelines:
1. Your Java programs should always end with the .java extension.
2. Filenames should match the name of your public class. So for example, if the
name of your public class is Hello, you should save it in a file called Hello.java.
3. You should write comments in your code explaining what a certain class does,
or what a certain method do.

3.3 Java Comments


Comments are notes written to a code for documentation purposes. Those text are not
part of the program and does not affect the flow of the program. Java supports three
types of comments: C++-style single line comments, C-style multiline comments and
special javadoc comments.

3.3.1 C++-Style Comments


C++ Style comments starts with //. All the text after // are treated as comments. For
example,

// This is a C++ style or single line comments

3.3.2 C-Style Comments


C-style comments or also called multiline comments starts with a /* and ends with a */.
All text in between the two delimeters are treated as comments. Unlike C++ style
comments, it can span multiple lines. For example,

/* this is an exmaple of a
C style or multiline comments */

4.3.3 Special Javadoc Comments


Special Javadoc comments are used for generating an HTML documentation for your
Java programs. You can create javadoc comments by starting the line with /** and
ending it with */. Like C-style comments, it can also span lines. It can also contain
certain tags to add more information to your comments. For example,
/**
This is an example of special java doc comments used
for \n generating an html documentation. It uses tags
like:
@author Florence Balagtas
@version 1.2
*/
3.4 Java Statements and blocks
A statement is one or more lines of code terminated by a semicolon. An example of a
single statement is,

System.out.println(Hello world);

A block is one or more statements bounded by an opening and closing curly braces
that groups the statements as one unit. Block statements can be nested indefinitely.
Any amount of white space is allowed. An example of a block is,

public static void main( String[] args ){


System.out.println("Hello");
System.out.println("world");
}

Coding Guidelines:
1. In creating blocks, you can place the opening curly brace in line with the
statement, like for example,

public static void main( String[] args ){

or you can place the curly brace on the next line, like,

public static void main( String[] args )


{

2. You should indent the next statements after the start of a block, for example,

public static void main( String[] args ){


System.out.println("Hello");
System.out.println("world");
}

3.5 Java Identifiers


Identifiers are tokens that represent names of variables, methods, classes, etc.
Examples of identifiers are: Hello, main, System, out.

Java identifiers are case-sensitive. This means that the identifier: Hello is not the same
as hello. Identifiers must begin with either a letter, an underscore _, or a dollar sign
$. Letters may be lower or upper case. Subsequent characters may use numbers 0 to
9.

Identifiers cannot use Java keywords like class, public, void, etc. We will discuss more
about Java keywords later.
Coding Guidelines:
1. For names of classes, capitalize the first letter of the class name. For names of
methods and variables, the first letter of the word should start with a small letter.
For example:

ThisIsAnExampleOfClassName
thisIsAnExampleOfMethodName

2. In case of multi-word identifiers, use capital letters to indicate the start of the
word except the first word. For example, charArray, fileNumber, ClassName.

3. Avoid using underscores at the start of the identifier such as _read or _write.

3.6 Java Keywords


Keywords are predefined identifiers reserved by Java for a specific purpose. You cannot
use keywords as names for your variables, classes, methods etc. Here is a list of the
Java Keywords.

We will try to discuss all the meanings of these keywords and how they are used in our
Java programs as we go along the way.

Note: true, false, and null are not keywords but they are reserved words, so
you cannot use them as names in your programs either.

3.7 Java Literals


Literals are tokens that do not change or are constant. The different types of literals in
Java are: Integer Literals, Floating-Point Literals, Boolean Literals, Character Literals
and String Literals.
3.7.1 Integer Literals
Integer literals come in different formats: decimal (base 10), hexadecimal (base 16),
and octal (base 8). In using integer literals in our program, we have to follow some
special notations.

For decimal numbers, we have no special notations. We just write a decimal number as
it is. For hexadecimal numbers, it should be preceded by 0x or 0X. For octals, they
are preceded by 0.

For example, consider the number 12. Its decimal representation is 12, while in
hexadecimal, it is 0xC, and in octal, it is equivalent to 014.

Integer literals default to the data type int. An int is a signed 32-bit value. In some
cases, you may wish to force integer literal to the data type long by appending the l or
L character. A long is a signed 64-bit value. We will cover more on data types later.

3.7.2 Floating-Point Literals


Floating point literals represent decimals with fractional parts. An example is 3.1415.
Floating point literals can be expressed in standard or scientific notations. For example,
583.45 is in standard notation, while 5.8345e2 is in scientific notation.

Floating point literals default to the data type double which is a 64-bit value. To use a
smaller precision (32-bit) float, just append the f or F character.

3.7.3 Boolean Literals


Boolean literals have only two values, true or false.

3.7.4 Character Literals


Character Literals represent single Unicode characters. A Unicode character is a 16-bit
character set that replaces the 8-bit ASCII character set. Unicode allows the inclusion of
symbols and special characters from other languages.

To use a character literal, enclose the character in single quote delimiters. For example,
the letter a, is represented as a.

To use special characters such as a newline character, a backslash is used followed by


the character code. For example, \n for the newline character, \r for the
carriage return, \b for backspace.

3.7.5 String Literals


String literals represent multiple characters and are enclosed by double quotes. An
example of a string literal is, Hello World.
3.8 Primitive data types
The Java programming language defines eight primitive data types. The following are,
boolean (for logical), char (for textual), byte, short, int, long (integral), double and float
(floating point).

3.8.1 Logical - boolean


A boolean data type represents two states: true and false. An example is,

boolean result = true;

The example shown above, declares a variable named result as boolean type and
assigns it a value of true.

3.8.2 Textual char


A character data type (char), represents a single Unicode character. It must have its
literal enclosed in single quotes( ). For example,

a //The letter a
\t //A tab

To represent special characters like ' (single quotes) or " (double quotes), use the
escape character \. For example,

'\'' //for single quotes


'\"' //for double quotes

Although, String is not a primitive data type (it is a Class), we will just introduce String in
this section. A String represents a data type that contains multiple characters. It is not a
primitive data type, it is a class. It has its literal enclosed in double quotes(). For
example,

String message=Hello world!

3.8.3 Integral byte, short, int & long


Integral data types in Java uses three forms decimal, octal or hexadecimal. Examples
are,
2 //The decimal value 2
077 //The leading 0 indicates an octal value
0xBACC //The leading 0x indicates a hexadecimal value

Integral types have int as default data type. Integral data type has the following ranges:
3.8.4 Floating Point float and double
Floating point types has double as default data type. Floating-point literal includes either
a decimal point or one of the following,

E or e //(add exponential value)


F or f //(float)
D or d //(double)

Examples are,

3.14 //A simple floating-point value (a double)


6.02E23 //A large floating-point value
2.718F //A simple float size value
123.4E+306D //A large double value with redundant D

In the example shown above, the 23 after the E in the second example is implicitly
positive. That example is equivalent to 6.02E+23. Floating-point data types have the
following ranges:

3.9 Variables
A variable is an item of data used to store state of objects.

A variable has a data type and a name. The data type indicates the type of value that
the variable can hold. The variable name must follow rules for identifiers.
3.9.1 Declaring and Initializing Variables
To declare a variable is as follows,

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

Note: Values enclosed in <> are required values, while those values enclosed in [] are
optional.

Here is a sample program that declares and initializes some variables,

public class VariableSamples


{
public static void main( String[] args ){
//declare a data type with variable name
// result and boolean data type
boolean result;

//declare a data type with variable name


// option and char data type
char option;
option = 'C'; //assign 'C' to option

//declare a data type with variable name


//grade, double data type and initialized
//to 0.0
double grade = 0.0;
}
}

Coding Guidelines:
1. It always good to initialize your variables as you declare them.
2. Use descriptive names for your variables. Like for example, if you want to have
a variable that contains a grade for a student, name it as, grade and not just
some random letters you choose.
3. Declare one variable per line of code. For example, the variable declarations,

double exam=0;
double quiz=10;
double grade = 0;

is preferred over the declaration,

double exam=0, quiz=10, grade=0;


3.9.2 Outputting Variable Data
In order to output the value of a certain variable, we can use the following commands,

System.out.println()
System.out.print()

Here's a sample program,

public class OutputVariable


{
public static void main( String[] args ){
int value = 10;
char x;
x = A;
System.out.println( value );
System.out.println( The value of x= + x );
}
}

The program will output the following text on screen,

10
The value of x=A

3.9.3 System.out.println() vs. System.out.print()


What is the difference between the commands System.out.println() and
System.out.print()? The first one appends a newline at the end of the data to output,
while the latter doesn't.

Consider the statements,

System.out.print("Hello ");
System.out.print("world!");

These statements will output the following on the screen,

Hello world!

Now consider the following statements,

System.out.println("Hello ");
System.out.println("world!");
These statements will output the following on the screen,

Hello
world!

3.9.4 Reference Variables vs. Primitive Variables


We will now differentiate the two types of variables that Java programs have. These are
reference variables and primitive variables.

Primitive variables are variables with primitive data types. They store data in the
actual memory location of where the variable is.

Reference variables are variables that store the address in the memory location. It
points to another memory location of where the actual data is. When you declare a
variable of a certain class, you are actually declaring a reference variable to the object
with that certain class.

For example, suppose we have two variables with data types int and String.

int num = 10;


String name = "Hello"

Suppose, the illustration shown below is the actual memory of your computer, wherein
you have the address of the memory cells, the variable name and the data they hold.

As you can see, for the primitive variable num, the data is on the actual location of
where the variable is. For the reference variable name, the variable just holds the
address of where the actual data is.

3.10 Operators
In Java, there are different types of operators. There are arithmetic operators, relational
operators, logical operators and conditional operators. These operators follow a certain
kind of precedence so that the compiler will know which operator to evaluate first in
case multiple operators are used in one statement.
3.10.1 Arithmetic operators
Here are the basic arithmetic operators that can be used in creating your Java
programs,

Here's a sample program in the usage of these operators:

public class ArithmeticDemo


{
public static void main(String[] args)
{
//a few numbers
int i = 37;
int j = 42;
double x = 27.475;
double y = 7.22;
System.out.println("Variable values...");
System.out.println(" i = " + i);
System.out.println(" j = " + j);
System.out.println(" x = " + x);
System.out.println(" y = " + y); //adding numbers
System.out.println("Adding...");
System.out.println(" i + j = " + (i + j));
System.out.println(" x + y = " + (x + y));

//subtracting numbers
System.out.println("Subtracting...");
System.out.println(" i - j = " + (i - j));
System.out.println(" x - y = " + (x - y));

//multiplying numbers
System.out.println("Multiplying...");
System.out.println(" i * j = " + (i * j));
System.out.println(" x * y = " + (x * y));
//dividing numbers
System.out.println("Dividing...");
System.out.println(" i / j = " + (i / j));
System.out.println(" x / y = " + (x / y));

//computing the remainder resulting from dividing numbers


System.out.println("Computing the remainder...");
System.out.println(" i % j = " + (i % j));
System.out.println(" x % y = " + (x % y));

//mixing types
System.out.println("Mixing types...");
System.out.println(" j + y = " + (j + y));
System.out.println(" i * x = " + (i * x));
}
}

Here is the output of the program,

Variable values...
i = 37
j = 42
x = 27.475
y = 7.22
Adding...
i + j = 79
x + y = 34.695
Subtracting...
i - j = -5
x - y = 20.255
Multiplying...
i * j = 1554
x * y = 198.37
Dividing...
i / j = 0
x / y = 3.8054
Computing the remainder...
i % j = 37
x % y = 5.815
Mixing types...
j + y = 49.22
i * x = 1016.58

Note: When an integer and a floating-point number are used as operands to a single
arithmetic operation, the result is a floating point. The integer is implicitly converted to a
floating-point number before the operation takes place.
3.10.2 Increment and Decrement operators
Aside from the basic arithmetic operators, Java also includes a unary increment
operator (++) and unary decrement operator (--). Increment and decrement operators
increase and decrease a value stored in a number variable by 1.

For example, the expression,

count = count + 1; //increment the value of count by 1

is equivalent to,

count++;

The increment and decrement operators can be placed before or after an operand.

When used before an operand, it causes the variable to be incremented or


decremented by 1, and then the new value is used in the expression in which it
appears. For example,

int i = 10,
int j = 3;
int k = 0;
k = ++j + i; //will result to k = 4+10 = 14

When the increment and decrement operators are placed after the operand, the old
value of the variable will be used in the expression where it appears. For example,

int i = 10,
int j = 3;
int k = 0;
k = j++ + i; //will result to k = 3+10 = 13
Coding Guideline:
Always keep expressions containing increment and decrement operators simple and
easy to understand.

3.10.3 Relational operators


Relational operators are used to compare two values and determine the relationship
between those values. The output of evaluation is the boolean values true or false.

Here's a sample program that uses relational operators,

public class RelationalDemo


{
public static void main(String[] args) {
//a few numbers
int i = 37;
int j = 42;
int k = 42;
System.out.println("Variable values...");
System.out.println(" i = " + i);
System.out.println(" j = " + j);
System.out.println(" k = " + k);

//greater than
System.out.println("Greater than...");
System.out.println(" i > j = " + (i > j)); //false
System.out.println(" j > i = " + (j > i)); //true
System.out.println(" k > j = " + (k > j)); //false

//greater than or equal to


System.out.println("Greater than or equal to...");
System.out.println(" i >= j = " + (i >= j)); //false
System.out.println(" j >= i = " + (j >= i)); //true
System.out.println(" k >= j = " + (k >= j)); //true
//less than
System.out.println("Less than...");
System.out.println(" i < j = " + (i < j)); //true
System.out.println(" j < i = " + (j < i)); //false
System.out.println(" k < j = " + (k < j)); //false

//less than or equal to


System.out.println("Less than or equal to...");
System.out.println(" i <= j = " + (i <= j)); //true
System.out.println(" j <= i = " + (j <= i)); //false
System.out.println(" k <= j = " + (k <= j)); //true

//equal to
System.out.println("Equal to...");
System.out.println(" i == j = " + (i == j)); //false
System.out.println(" k == j = " + (k == j)); //true

//not equal to
System.out.println("Not equal to...");
System.out.println(" i != j = " + (i != j)); //true
System.out.println(" k != j = " + (k != j)); //false
}
}

Here's the output from this program:

Variable values...
i = 37
j = 42
k = 42
Greater than...
i > j = false
j > i = true
k > j = false
Greater than or equal to...
i >= j = false
j >= i = true
k >= j = true
Less than...
i < j = true
j < i = false
k < j = false
Less than or equal to...
i <= j = true
j <= i = false
k <= j = true
Equal to...
i == j = false
k == j = true
Not equal to...
i != j = true
k != j = false

3.10.4 Logical operators


Logical operators have one or two boolean operands that yield a boolean result. There
are six logical operators: && (logical AND), & (boolean logical AND), || (logical OR), |
(boolean logical inclusive OR), ^ (boolean logical exclusive OR), and ! (logical NOT).

The basic expression for a logical operation is,

x1 op x2

where x1, x2 can be boolean expressions, variables or constants, and op is either &&,
&, ||, | or ^ operator. The truth tables that will be shown next, summarize the result of
each operation for all possible combinations of x1 and x2.

3.10.4.1 && (logical AND) and & (boolean logical AND)


Here is the truth table for && and &,

The basic difference between && and & operators is that && supports short-circuit
evaluations (or partial evaluations), while & doesn't. What does this mean?

Given an expression,

exp1 && exp2

&& will evaluate the expression exp1, and immediately return a false value is exp1 is
false. If exp1 is false, the operator never evaluates exp2 because the result of the
operator will be false regardless of the value of exp2. In contrast, the & operator always
evaluates both exp1 and exp2 before returning an answer.
Here's a sample source code that uses logical and boolean AND,

public class TestAND


{
public static void main( String[] args ){
int i = 0;
int j = 10;
boolean test= false;

//demonstrate &&
test = (i > 10) && (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);

//demonstrate &
test = (i > 10) & (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
}
}

The output of the program is,

0
10
false
0
11
false

Note, that the j++ on the line containing the && operator is not evaluated since the first
expression (i>10) is already equal to false.

3.10.4.2 || (logical OR) and | (boolean logical inclusive OR)


Here is the truth table for || and |,
The basic difference between || and | operators is that || supports short-circuit
evaluations (or partial evaluations), while | doesn't. What does this mean?

Given an expression,

exp1 || exp2

|| will evaluate the expression exp1, and immediately return a true value is exp1 is true.
If exp1 is true, the operator never evaluates exp2 because the result of the operator will
be true regardless of the value of exp2. In contrast, the | operator always evaluates both
exp1 and exp2 before returning an answer.

Here's a sample source code that uses logical and boolean OR,

public class TestOR


{
public static void main( String[] args ){
int i = 0;
int j = 10;
boolean test= false;

//demonstrate ||
test = (i < 10) || (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);

//demonstrate |
test = (i < 10) | (j++ > 9);
System.out.println(i);
System.out.println(j);
System.out.println(test);
}
}

The output of the program is,


0
10
true
0
11
true

Note, that the j++ on the line containing the || operator is not evaluated since the first
expression (i<10) is already equal to true.
3.10.4.3 ! (logical NOT)
The logical NOT takes in one argument, wherein that argument can be an expression,
variable or constant. Here is the truth table for !,

Here's a sample source code that uses the logical NOT operator,

public class TestNOT


{
public static void main( String[] args ){
boolean val1 = true;
boolean val2 = false;
System.out.println(!val1);
System.out.println(!val2);
}
}

The output of the program is,

false
true

3.10.4 Conditional Operator (?:)


The conditional operator ?: is a ternary operator. This means that it takes in three
arguments that together form a conditional expression. The structure of an expression
using a conditional operator is,

exp1?exp2:exp3

wherein exp1 is a boolean expression whose result must either be true or false.

If exp1 is true, exp2 is the value returned. If it is false, then exp3 is returned.

For example, given the code,

public class ConditionalOperator


{
public static void main( String[] args ){
String status = "";
int grade = 80;
//get status of the student
status = (grade >= 60)?"Passed":"Fail";

//print status
System.out.println( status );

}
}

The output of this program will be,


Passed

3.11 Exercises

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

The following should be the expected screen output,

Number = 10
letter = a
result = true
str = hello

2. Create a program that outputs the average of three numbers. Let the values of
the three numbers be, 10, 20 and 45. The expected screen output is,

number 1 = 10
number 2 = 20
number 3 = 45
Average is = 25

3. Given three numbers, write a program that outputs the number with the greatest
value among the three. Use the conditional ?: operator that we have studied so
far (HINT: You will need to use two sets of ?: to solve this). For example, given
the numbers 10, 23 and 5, your program should output,
number 1 = 10
number 2 = 23
number 3 = 5
The highest number is = 23

4 Getting Input from the Keyboard

4.1 Objectives
Now that we've studied some basic concepts in Java and we've written some simple
programs, let's make our programs more interactive by getting some input from the
user. In this section, we'll be discussing two methods of getting input, the first one is
through the use of the BufferedReader class and the other one involves a graphical
user interface by using JOptionPane.

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


Create an interactive Java program that gets input from the keyboard
Use the BufferedReader class to get input from the keyboard using a console
Use the JOptionPane class to get input from the keyboard using a graphical user
interface

4.2 Using BufferedReader to get input


In this section, we will use the BufferedReader class found in the java.io package in
order to get input from the keyboard.

Here are the steps to get input from the keyboard:

1. Add this at the top of your code:

import java.io.*;

2. Add this statement:

BufferedReader dataIn = new BufferedReader( new


InputStreamReader( System.in) );

3. Declare a temporary String variable to get the input, and invoke the
readLine() method to get input from the keyboard. You have to type it inside a
try-catch block.
try{
String temp = dataIn.readLine();
}
catch( IOException e ){
System.out.println(Error in getting input);
}
Here is the complete source code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class GetInputFromKeyboard
{
public static void main( String[] args ){
BufferedReader dataIn = new BufferedReader(new
InputStreamReader( System.in) );
String name = "";
System.out.print("Please Enter Your Name:");

try{
name = dataIn.readLine();
}catch( IOException e ){
System.out.println("Error!");
}

System.out.println("Hello " + name +"!");


}
}

Now let's try to explain each line of code:


The statements,

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

indicate that we want to use the classes BufferedReader, InputStreamReader


and IOException which is inside the java.io package. The Java Application
Programming Interface (API) contains hundreds of predefined classes that you
can use in your programs. These classes are organized into what we call packages.

Packages contain classes that have related purpose. Just like in our example, the
java.io package contains classes that allow programs to input and output data. The
statements can also be rewritten as,

import java.io.*;

which will load all the classes found in the package, and then we can use those classes
inside our program.

The next two statements,


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

were already discussed in the previous lesson. This means we declare a class named
GetInputFromKeyboard and we declare the main method.

In the statement,

BufferedReader dataIn = new BufferedReader(new


InputStreamReader( System.in) );

we are declaring a variable named dataIn with the class type BufferedReader. Don't
worry about what the syntax means for now. We will cover more about this later in the
course.

Now, we are declaring a String variable with the identifier name,

String name = "";

This is where we will store the input of the user. The variable name is initialized to an
empty String "". It is always good to initialize your variables as you declare them.

The next line just outputs a String on the screen asking for the user's name.

System.out.print("Please Enter Your Name:");

Now, the following block defines a try-catch block,

try{
name = dataIn.readLine();
}catch( IOException e ){
System.out.println("Error!");
}

This assures that the possible exceptions that could occur in the statement

name = dataIn.readLine();

will be catched. We will cover more about exception handling in the latter part of this
course, but for now, just take note that you need to add this code in order to use the
readLine() method of BufferedReader to get input from the user.

Now going back to the statement,

name = dataIn.readLine();
the method call, dataIn.readLine(), gets input from the user and will return a
String value. This value will then be saved to our name variable, which we will use in our
final statement to greet the user,

System.out.println("Hello " + name + "!");

4.3 Using JOptionPane to get input


Another way to get input from the user is by using the JOptionPane class which is found
in the javax.swing package. JOptionPane makes it easy to pop up a standard dialog box
that prompts users for a value or informs them of something.

Given the following code,


import javax.swing.JOptionPane;
public class GetInputFromKeyboard
{
public static void main( String[] args ){
String name = "";
name = JoptionPane.showInputDialog("Please
enter your name");

String msg = "Hello " + name + "!";

JOptionPane.showMessageDialog(null, msg);
}
}

This will output,

Getting Input

Inputted Name
Showing message Using JOptionPane

The first statement,

import javax.swing.JOptionPane;

indicates that we want to import the class JOptionPane from the javax.swing package.

We can also write this as,

import javax.swing.*;

The statement,

name = JOptionPane.showInputDialog("Please enter your


name");

creates a JOptionPane input dialog, which will display a dialog with a message,
a textfield and an OK button as shown in the figure. This returns a String which we will
save in the name variable.

Now we create the welcome message, which we will store in the msg variable,

String msg = "Hello " + name + "!";

The next line displays a dialog which contains a message and an OK button.

JOptionPane.showMessageDialog(null, msg);
4.4 Exercises

Last 3 words (BufferedReader version)


1. Using BufferedReader, ask for three words from the user and output those three
words on the screen. For example,

Enter word1:Goodbye
Enter word2:and
Enter word3:Hello
Goodbye and Hello

Last 3 words (JOptionPane version)


2. Using JOptionPane, ask for three words from the user and output those three
words on the screen. For example,

First Input

Second Input

Third Input
Show Message

5 Control Structures

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

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


Use decision control structures (if, else, switch) which allows selection of specific
sections of code to be executed
Use repetition control structures (while, do-while, for) which allow executing
specific sections of code a number of times
Use branching statements (break, continue, return) which allows redirection
of program flow

6.2 Decision Control Structures


Decision control structures are Java statements that allows us to select and execute
specific blocks of code while skipping other sections.

6.2.1 if statement
The if-statement specifies that a statement (or block of code) will be executed if and
only if a certain boolean statement is true.

The if-statement has the form,

if( boolean_expression )
statement;
or
if( boolean_expression ){
statement1;
statement2;
. . .
}
where, boolean_expression is either a boolean expression or boolean variable.

For example, given the code snippet,

int grade = 68;


if( grade > 60 ) System.out.println("Congratulations!");

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

Coding Guidelines:
1. The boolean_expression part of a statement should evaluate to a boolean
value. That means that the execution of the condition should either result to a
value of true or a false.
2. Indent the statements inside the if-block.For example,

if( boolean_expression ){
//statement1;
//statement2;
}

5.2.2 if-else statement


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

The if-else statement has the form,

if( boolean_expression )
statement;
else
statement;

or can also be written as,

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

For example, given the code snippet,

int grade = 68;


if( grade > 60 ) System.out.println("Congratulations!");
else System.out.println("Sorry you failed");

or

int grade = 68;


if( grade > 60 ){
System.out.println("Congratulations!");
System.out.println("You passed!");
}
else{
System.out.println("Sorry you failed");
}

Coding Guidelines:
1. To avoid confusion, always place the statement or statements of an if or if-else
block inside brackets {}.
2. You can have nested if-else blocks. This means that you can have other if-else
blocks inside another if-else block. For example,

if( boolean_expression ){
if( boolean_expression ){
. . .
}
}
else{ . . .
}

5.2.3 if-else-if statement


The statement in the else-clause of an if-else block can be another if-else structures.
This cascading of structures allows us to make more complex selections.
The if-else if statement has the form,

if( boolean_expression1 )
statement1;
else if( boolean_expression2 )
statement2;
else
statement3;

Take note that you can have many else-if blocks after an if-statement. The else-block is
optional and can be omitted. In the example shown above, if boolean_expression1 is
true, then the program executes statement1 and skips the other statements. If
boolean_expression2 is true, then the program executes statement 2 and skips to the
statements following statement3.

For example, given the code snippet,

int grade = 68;


if( grade > 90 ){
System.out.println("Very good!");
}
else if( grade > 60 ){
System.out.println("Very good!");
}
else{
System.out.println("Sorry you failed");
}

5.2.4 Common Errors when using the if-else statements:


1. The condition inside the if-statement does not evaluate to a boolean
value. For example,

//WRONG
int number = 0;
if( number ){
//some statements here
}
The variable number does not hold a Boolean value.

2. Using = instead of == for comparison. For example,


//WRONG
int number = 0;
if( number = 0 ){
//some statements here
}
This should be written as,

//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}

3. Writing elseif instead of else if.

5.2.5 Example for if-else-else if


public class Grade
{
public static void main( String[] args )
{
double grade = 92.0;
if( grade >= 90 ){
System.out.println( "Excellent!" );
}
else if( (grade < 90) && (grade >= 80)){
System.out.println("Good job!" );
}
else if( (grade < 80) && (grade >= 60)){
System.out.println("Study harder!" );
}
else{
System.out.println("Sorry, you failed.");
}
}
}

5.2.6 switch statement


Another way to indicate a branch is through the switch keyword. The switch construct
allows branching on multiple outcomes.
The switch statement has the form,

switch( switch_expression ){
case case_selector1:
statement1; //
statement2; //block 1
. . . //
break;
case case_selector2:
statement1; //
statement2; //block 2
. . . //
break;
. . .
default:
statement1; //
statement2; //block n
. . . //
}

where, switch_expression is an integer or character expression and, case_selector1,


case_selector2 and so on, are unique integer or character constants.

When a switch is encountered, Java first evaluates the switch_expression, and jumps to
the case whose selector matches the value of the expression. The program executes
the statements in order from that point on until a break statement is encountered,
skipping then to the first statement after the end of the switch structure.

If none of the cases are satisfied, the default block is executed. Take note however, that
the default part is optional. A switch statement can have no default block.

NOTES:
Unlike with the if statement, the multiple statements are executed in the switch
statement without needing the curly braces.
When a case in a switch statement has been matched, all the statements
associated with that case are executed. Not only that, the statements associated
with the succeeding cases are also executed.
To prevent the program from executing statements in the subsequent cases, we
use a break statement as our last statement.

Coding Guidelines:
1. Deciding whether to use an if statement or a switch statement is a judgment call.
You can decide which to use, based on readability and other factors.
2. An if statement can be used to make decisions based on ranges of
values or conditions, whereas a switch statement can make decisions based
only on a single integer or character value. Also, the value provided to each case
statement must be unique.

5.2.7 Example for switch

public class Grade


{
public static void main( String[] args )
{
int grade = 92;
switch(grade){
case 100:
System.out.println( "Excellent!" );
break;
case 90:
System.out.println("Good job!" );
break;
case 80:
System.out.println("Study harder!" );
break;
default:
System.out.println("Sorry, you failed.");
}
}
}

5.3 Repetition Control Structures


Repetition control structures are Java statements that allows us to execute
specific blocks of code a number of times. There are three types of repetition control
structures, the while, do-while and for loops.

5.3.1 while loop


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

The while statement has the form,

while( boolean_expression ){
statement1;
statement2;
. . .
}

The statements inside the while loop are executed as long as the boolean_expression
evaluates to true.

For example, given the code snippet,

int i = 4;
while ( i > 0 ){
System.out.print(i);
i--;
}

The sample code shown will print 4321 on the screen. Take note that if the line
containing the statement i--; is removed, this will result to an infinite loop, or a loop that
does not terminate. Therefore, when using while loops or any kind of repetition control
structures, make sure that you add some statements that will allow your loop to
terminate at some point.

You might also like