Java Hand Outs
Java Hand Outs
Java Hand Outs
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.
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
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.
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.
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.
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.
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.
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.
Finally, on the Create Main Class textfield, type in Hello as the main class' name, and
then click on the FINISH button.
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!");
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:
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.
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:
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
*/
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.
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 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.
/* this is an exmaple of a
C style or multiline comments */
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,
Coding Guidelines:
1. In creating blocks, you can place the opening curly brace in line with the
statement, like for example,
or you can place the curly brace on the next line, like,
2. You should indent the next statements after the start of a block, for example,
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.
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.
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.
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.
To use a character literal, enclose the character in single quote delimiters. For example,
the letter a, is represented as a.
The example shown above, declares a variable named result as boolean type and
assigns it a value of true.
a //The letter a
\t //A tab
To represent special characters like ' (single quotes) or " (double quotes), use the
escape character \. For example,
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,
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,
Examples are,
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,
Note: Values enclosed in <> are required values, while those values enclosed in [] are
optional.
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;
System.out.println()
System.out.print()
10
The value of x=A
System.out.print("Hello ");
System.out.print("world!");
Hello world!
System.out.println("Hello ");
System.out.println("world!");
These statements will output the following on the screen,
Hello
world!
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.
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,
//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));
//mixing types
System.out.println("Mixing types...");
System.out.println(" j + y = " + (j + y));
System.out.println(" i * x = " + (i * x));
}
}
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.
is equivalent to,
count++;
The increment and decrement operators can be placed before or after an operand.
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.
//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
//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
}
}
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
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.
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,
&& 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,
//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);
}
}
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.
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,
//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);
}
}
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,
false
true
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.
//print status
System.out.println( status );
}
}
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.
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.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.
import java.io.*;
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!");
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
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.
were already discussed in the previous lesson. This means we declare a class named
GetInputFromKeyboard and we declare the main method.
In the statement,
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.
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.
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.
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,
JOptionPane.showMessageDialog(null, msg);
}
}
Getting Input
Inputted Name
Showing message Using JOptionPane
import javax.swing.JOptionPane;
indicates that we want to import the class JOptionPane from the javax.swing package.
import javax.swing.*;
The statement,
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,
The next line displays a dialog which contains a message and an OK button.
JOptionPane.showMessageDialog(null, msg);
4.4 Exercises
Enter word1:Goodbye
Enter word2:and
Enter word3:Hello
Goodbye and Hello
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.
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.
if( boolean_expression )
statement;
or
if( boolean_expression ){
statement1;
statement2;
. . .
}
where, boolean_expression is either a boolean expression or boolean variable.
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;
}
if( boolean_expression )
statement;
else
statement;
if( boolean_expression ){
statement1;
statement2;
. . .
}
else{
statement1;
statement2;
. . .
or
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{ . . .
}
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.
//WRONG
int number = 0;
if( number ){
//some statements here
}
The variable number does not hold a Boolean value.
//CORRECT
int number = 0;
if( number == 0 ){
//some statements here
}
switch( switch_expression ){
case case_selector1:
statement1; //
statement2; //block 1
. . . //
break;
case case_selector2:
statement1; //
statement2; //block 2
. . . //
break;
. . .
default:
statement1; //
statement2; //block n
. . . //
}
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.
while( boolean_expression ){
statement1;
statement2;
. . .
}
The statements inside the while loop are executed as long as the boolean_expression
evaluates to true.
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.