JavaTM Education & Technology Services
Java Programming
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 1
Course Outline
• Lesson 1: Introduction to Java
• Lesson 2: Basic Java Concepts
• Lesson 3: Applets
• Lesson 4: Data Types & Operators
• Lesson 5: using Arrays & Strings
• Lesson 6: Controlling Program Flow
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 2
Course Outline
• Lesson7: Java Exception
• Lesson 8: Interfaces
• Lesson 9: Multi-Threading
• Lesson 10: Inner class
• Lesson 11: Event Handling
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 3
Lesson 4
Data Types & Operators
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 4
Identifiers
• An identifier is the name given to a feature
(variable, method, or class).
• An identifier can begin with either:
– a letter,
– $, or
– underscore.
• Subsequent characters may be:
– a letter,
– $,
– underscore, or
– digits.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 5
Data types
• Data types can be classified into two types:
Primitive Reference
Boolean boolean 1 bit (true/false)
Arrays
byte 1B (-27 27-1) (-128 +127)
short 2B (-215 215-1) (-32,768 to +32,767)
Integer
int 4B (-231 231-1) Classes
long 8B (-263 263-1)
Floating float 4B Standard: IEEE 754 Specification
Point double 8B Standard: IEEE 754 Specification Interfaces
Character char 2B unsigned Unicode chars (0 216-1)
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 6
Literals
• A literal is any value that can be assigned to a primitive
data type or String.
boolean true false
char ‘a’ …. ’z’ ‘A’ …. ‘Z’
‘\u0000’ …. ‘\uFFFF’
‘\n’ ‘\r’ ‘\t’
Integral data 15 Decimal (int)
type 15L Decimal (long)
017 Octal
0XF Hexadecimal
Floating point 73.8 double
data type 73.8F float
5.4 E-70 5.4 * 10-70
5.4 e+70 5.4 * 1070
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 7
Wrapper Classes
• Each primitive data type has a corresponding
wrapper class.
boolean Boolean
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 8
Wrapper Classes cont’d
• There are three reasons that you might use a
wrapper class rather than a primitive:
1. As an argument of a method that expects an object.
2. To use constants defined by the class,
• such as MIN_VALUE and MAX_VALUE, that provide the
upper and lower bounds of the data type.
3. To use class methods for
• converting values to and from other primitive types,
• converting to and from strings,
• converting between number systems (decimal, octal,
hexadecimal, binary).
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 9
Wrapper Classes cont’d
• They have useful methods that perform some
general operation, for example:
primitive xxxValue() convert wrapper object to primitive
primitive parseXXX(String) convert String to primitive
Wrapper valueOf(String) convert String to Wrapper
Integer i2 = new Integer(42);
byte b = i2.byteValue();
double d = i2.doubleValue();
String s3 = Integer.toHexString(254);
System.out.println("254 is " + s3);
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 10
Wrapper Classes cont’d
• They have special static representations, for
example:
POSITIVE_INFINITY
In class Float & Double
NEGATIVE_INFINITY
NaN Not a Number
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 11
Reference Data types: Classes
• General syntax for creating an object:
MyClass myRef; // just a reference
myRef = new MyClass(); // construct a new object
• Or on one line:
MyClass myRef = new MyClass();
• An object is garbage collected when there is no reference
pointing to it.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 12
Reference Data types: Classes cont’d
String str1; // just a null reference
str1 = new String(“Hello”); // object construction Memory
Heap
String str2 = new String(“Hi”); “Hello”
String s = str1; //two references to the same object
“Hi”
str1 = null;
s = null; // The object containing “Hello” will
// now be eligible for garbage collection.
str1 str2 s
Stack
str1.anyMethod(); // ILLEGAL!
//Throws NullPointerException
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 13
Operators
• Operators are classified into the following
categories:
Unary Operators.
Arithmetic Operators.
Assignment Operators.
Relational Operators.
Shift Operators.
Bitwise and Logical Operators.
Short Circuit Operators.
Ternary Operator.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 14
Operators cont’d
• Unary Operators:
+ - ++ -- ! ~ ()
positive negative increment decrement boolean bitwise casting
complement inversion
Widening
(implicit casting)
byte short int long float double
Narrowing
char (requires explicit casting)
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 15
Operators cont’d
• Arithmetic Operators:
+ - * / %
add subtract multiply division modulo
• Assignment Operators:
= += -= *= /= %= &= |= ^=
• Relational Operators:
< <= > >= == != instanceof
Operations must be performed on homogeneous data types
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 16
Operators cont’d
• Shift Operators:
>> << >>>
right shift left shift unsigned right shift
• Bitwise and Logical Operators:
& | ^
AND OR XOR
• Short Circuit Operators:
&& ||
(condition1 AND condition2) (condition1 OR condition2)
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 18
Operators cont’d
• Ternary Operator:
condition ?true statement:false statement
int y = 15; If(y<z)
int z = 12; x=10;
int x = y<z? 10 : 11; else
x=11;
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 19
Operators cont’d
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
Bitwise and Logical AND &
bitwise exclusive OR ^
Bitwise and Logical inclusive OR |
Short Circuit AND &&
Short Circuit OR ||
ternary ?:
assignment = op=
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 20
Lesson 5
Using Arrays & Strings
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 21
What is Array?
• An Array is a collection of variables of the same
data type.
• Each element can hold a single item.
• Items can be primitives or object references.
• The length of the array is determined when it is
created.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 22
What is Array?
• Java Arrays are homogeneous.
• You can create:
– An array of primitives,
– An array of object references, or
– An array of arrays.
• If you create an array of object references, then
you can store subtypes of the declared type.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 23
Declaring an Array
• General syntax for creating an array:
Datatype[] arrayIdentifier; // Declaration
arrayIdentifier = new Datatype [size]; //
Construction
• Or on one line, hard coded values:
Datatype[] arrayIdentifier = { val1, val2, val3,
val4 };
• To determine the size (number of elements) of an array
at runtime, use:
arrayIdentifier.length
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 24
Declaring an Array cont’d
• Example1: Array of Primitives:
Memory
int[] myArr;
myArr = new int[3]; [0] 15
Heap
[1] 30
myArr[0] = 15 ;
[2] 45
myArr[1] = 30 ;
myArr[2] = 45 ;
Stack myArr
System.out.println(myArr[2]);
myArr[3] = … ; // ILLEGAL!
//Throws ArrayIndexOutOfBoundsException
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 25
Declaring an Array cont’d
• Example2: Array of Object References:
Memory
String[] namesArr;
“Hello”
namesArr = new String[3]; [0]
Heap “James”
namesArr[0].anyMethod() // ILLEGAL! [1]
//Throws NullPointerException [2]
“Gosling”
namesArr[0] = new String(“Hello”);
namesArr[1] = new String(“James”); Stack
namesArr
namesArr[2] = new String(“Gosling”);
System.out.println(namesArr[1]);
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 26
String Operations
• Although String is a reference data type (class),
– it may figuratively be considered as the 9th data type
because of its special syntax and operations.
– Creating String Object:
String myStr1 = new String(“Welcome”);
String sp1 = “Welcome”;
String sp2 = “ to Java”;
– Testing for String equality:
if(myStr1.equals(sp1))
if(myStr1.equalsIgnoreCase(sp1))
if(myStr1 == sp1)
// Shallow Comparison (just compares the references)
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 27
Strings Operations cont’d
• The ‘+’ and ‘+=‘ operators were overloaded for class String
to be used in concatenation.
String str = myStr1 + sp2; // “Welcome to Java”
str += “ Programming”; // “Welcome to Java Programming”
str = str.concat(“ Language”); // “Welcome to Java Programming Language”
• Objects of class String are immutable
– you can’t modify the contents of a String object after construction.
• Concatenation Operations always return a new String
object that holds the result of the concatenation. The
original objects remain unchanged.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 28
String Pool
• String objects that are created without using the
“new” keyword are said to belong to the “String
Pool”.
Memory
“Hello”
String s1 = new String(“Hello”);
“Welcome”
String s2 = new String(“Hello”); Heap
“Hello”
String strP1 = “Welcome” ;
String strP2 = “Welcome” ;
Stack s1 s2 strP1 strP2
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 29
String Pool cont’d
• String objects in the pool have a special behavior:
– If we attempt to create a fresh String object with exactly the same
characters as an object that already exists in the pool (case
sensitive), then no new object will be created.
– Instead, the newly declared reference will point to the existing
object in the pool.
• Such behavior results in a better performance and saves
some heap memory.
• Remember: objects of class String are immutable.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 30
Lesson 6
Controlling Program Flow
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 31
Flow Control: Branching - if, else
• The if and else blocks are used for binary branching.
• Syntax:
if(boolean_expr)
{
…
… //true statements
…
}
[else]
{
…
… //false statements
…
}
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 32
if, else Example
int grade = 48;
int grade = 48;
if(grade > 60)
System.out.println(“Pass”);
Grade>60 false else
? {
System.out.println(“Fail”);
}
true
print(“Pass”); print(“fail”);
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 33
Flow Control: Branching - switch
• The switch block is used for multiple branching.
• Syntax:
switch(myVariable){ • byte
case value1: • short
…
… • int
break; • char
case value2:
… • enum
… • String “Java 7”
break;
default:
…
}
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 34
Flow Control: Branching – switch (EX.)
public class StringSwitchDemo {
public int getMonthNumber(String month) {
int monthNumber = 0;
switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
.......
default:
monthNumber = 0;
break;
} return monthNumber;
}}
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 35
Flow Control: Iteration – while loop
• The while loop is used when the termination condition
occurs unexpectedly and is checked at the beginning.
• Syntax:
while (boolean_condition)
{
…
…
…
}
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 36
while loop Example
int x = 0;
while (x<10) {
System.out.println(x);
int x = 0;
x++;
}
false
x<10?
true
print(x);
x++;
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 37
Flow Control: Iteration – do..while loop
• The do..while loop is used when the termination condition
occurs unexpectedly and is checked at the end.
• Syntax:
do
{
…
…
…
}
while(boolean_condition);
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 38
do..while loop Example
int x = 0;
do{
int x = 0; System.out.println(x);
x++;
} while (x<10);
print(x);
x++;
false
x<10?
true
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 39
Flow Control: Iteration – for loop
• The for loop is used when the number of iterations is
predetermined.
• Syntax:
for (initialization ; loop_condition ; step)
{
…
…
…
} for (int i=0 ; i<10 ; i++)
{
…
…
}
• You may use the break and continue keywords to skip
or terminate the iterations.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 40
Flow Control: Iteration –Enhanced for loop
for (type identifier : iterable_expression)
{
// statements
}
• The first element:
– is an identifier of the same type as the
iterable_expression
• The second element:
– is an expression specifying a collection of objects or
values of the specified type.
• The enhanced loop is used when we want to
iterate over arrays or collections.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 42
Flow Control: Iteration –Enhanced for loop example
double[] samples = new double[50];
double average = 0.0;
for(int i=0;i<samples.length;i++)
{
average += samples[i];
}
average /= samples.length;
double average = 0.0;
for(double value : samples)
{
average += value;
}
average /= samples.length;
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 43
The break statement
• The break statement can be used in loops or
switch.
• It transfers control to the first statement after the
loop body or switch body.
......
while(age <= 65)
{
balance = payment * l;
if (balance >= 25000)
break;
}
......
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 44
The continue statement
• The continue statement can be used Only in
loops.
• Abandons the current loop iteration and jumps to
the next loop iteration.
......
for(int year=2000; year<= 2099; year++){
if (year % 100 == 0)
continue;
}
......
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 45
Comments in Java
• To comment a single line:
// write a comment here
• To comment multiple lines:
/* comment line 1
comment line 2
comment line 3 */
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 46
Lesson 7
Modifiers-Access Specifiers
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 47
Modifiers and Access Specifiers
• Modifiers and Access Specifiers are a set of keywords that
affect the way we work with features (classes, methods, and
variables).
• The following table illustrates these keywords and how they are
used.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 49
Modifiers and Access Specifiers cont’d
Keyword Top Level Class Methods Variables
public Yes Yes Yes
default Yes Yes Yes
protected - Yes Yes
private - Yes Yes
final Yes Yes Yes
static - Yes Yes
abstract Yes Yes -
synchronized - Yes -
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 50
Lab Exercise
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 51
1. Command Line Calculator
• Create a simple non-GUI Application that carries out the
functionality of a basic calculator (addition, subtraction,
multiplication, and division).
• The program, for example, should be run by typing the
following at the command prompt:
java Calc 70 + 30
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 52
2. String Separator
• Create a non-GUI Application that accepts a well formed IP
Address in the form of a string and cuts it into separate parts
based on the dot delimiter.
• The program, for example, should be run by typing the
following at the command prompt:
java IPCutter 163.121.12.30
• The output should then be:
163
121
12
30
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 53
• Write a program that print the following patterns:
1. * 2.
**
***
****
*****
******
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 54