Introduction To Java
Introduction To Java
Before Java: C
Designed by Dennis Ritchie in 1970s.
Before C, there was no language to reconcile: easeof-use versus power,safety versus efficiency, rigidity
versus extensibility.
BASIC, COBOL, FORTRAN, PASCAL optimized
one set of traits, but not the other.
C- structured, efficient, high-level language that
could replace assembly code when creating systems
programs.
Designed, implemented and tested by programmers,
not scientists.
2
Java History
Designed by James Gosling, Patrick Naughton, Chris Warth,
Ed Frank and Mike Sheridan at Sun Microsystems in 1991.
The original motivation is not Internet: platform-independent
software embedded in consumer electronics devices.
With Internet, the urgent need appeared to break the fortified
positions ofIntel, Macintosh and Unix programmer
communities.
Java as an Internet version of C++? No.
Java was not designed to replace C++, but to solve a different
set of problems. There are significant practical/philosophical
differences.
4
Java Technology
There is more to Java than the language.
Java Technology consists of:
1) Java Programming Language
2) Java Virtual Machine (JVM)
3) Java Application Programming Interfaces
(APIs)
Execution Platform
What is an execution platform?
1) An execution platform is the hardware or software
environment in which a program
runs, e.g.
Windows 2000, Linux, Solaris or MacOS.
2) Most platforms can be described as a
combination of the operating system and hardware.
10
12
14
Java API
What is Java API?
1) a large collection of ready-made software
components that provide many useful capabilities,
e.g. graphical user interface
2) grouped into libraries (packages) of related
classes and interfaces
3) together with JVM insulates Java programs
from the hardware and operating system
variations
15
17
21
Main Method
The main method must be present in every Java application:
1) public static void main(String[] args) where:
a)public means that the method can be called by any object
b)static means that the method is shared by all instances
c)void means that the method does not return any value
2) When the interpreter executes an application, it starts by
calling its main method which in turn invokes other methods
in this or other classes.
3) The main method accepts a single argument a string array,
which holds all command-line parameters.
22
Java Syntax
On the most basic level, Java programs consist of:
a) whitespaces
b) identifiers
c) comments
d) literals
e) separators
f) keywords
g) operators
Each of them will be described in order.
24
Whitespaces
A whitespace is a space, tab or new line.
Java is a form-free language that does not require special
indentation.
A program could be written like this:
class MyProgram {
public static void main(String[] args) {
System.out.println(First Java program.");
}
}
It could be also written like this:
class MyProgram { public static void main(String[] args)
{ System.out.println(First Java program."); } }
25
Identifiers
Java identifiers:
a) used for class names, method names, variable names
b) an identifier is any sequence of letters, digits, _ or $
characters that do not begin with a digit
c) Java is case sensitive, so value, Value and VALUE are all
different.
Seven identifiers in this program:
class MyProgram {
public static void main(String[] args) {
System.out.println(First Java program.");
}
}
26
Comments
Three kinds of comments:
1) Ignore the text between /* and */:
/* text */
2) Documentation comment (javadoc tool uses this kind
of comment to automatically generate software
documentation):
/** documentation */
3) Ignore all text from // to the end of the line:
// text
27
Comments
/**
* MyProgram implements application that displays
* a simple message on the standard output device.
*/
class MyProgram {
/* The main method of the class.*/
public static void main(String[] args) {
//display string
System.out.println(First Java program.");
}
}
28
Literals
A literal is a constant value of certain type.
It can be used anywhere values of this type are allowed.
Examples:
a)100
b)98.6
c)X
d)test
class MyProgram {
public static void main(String[] args) {
System.out.println(My first Java program.");
}
29
}
Literals
Literals express constant values.
The form of a literal depends on its type:
1) integer types
2) floating-point types
3) character type
4) boolean type
5) string type
30
31
Two notations:
1) standard 2000.5
2) scientific 2.0005E3
Floating-point literals are of type double by default.
Floating-point literal written with F
(e.g. 2.0005E3F) are of type float.
32
Literals: Boolean
Two literals are allowed only: true and false.
Those values do not convert to any numerical
representation.
In particular:
1) true is not equal to 1
2) false is not equal to 0
33
Literals: Characters
Character literals belong to the Unicode character set.
Representation:
1) visible characters inside quotes, e.g. a
2) invisible characters written with escape sequences:
a) \ddd octal character ddd
b) \uxxxx hexadecimal Unicode character xxxx
c) \
single quote
d) \ double quote
e) \\
backslash
f) \r
carriage return
g) \n
new line
h) \f
form feed
i) \t
tab
j) \b
backspace
34
Literals: String
String is not a simple type.
String literals are character-sequences enclosed in double
quotes.
Example:
Hello World!
Notes:
1) escape sequences can be used inside string literals
2) string literals must begin and end on the same line
3) unlike in C/C++, in Java String is not an array of
characters
35
Separators
()
parenthesis
{}
braces
[]
Brackets
semicolon
comma
period
Keywords
Keywords are reserved words recognized by Java that cannot
be used as identifiers. Java defines 49 keywords as follows:
37
Operators Types
Java operators are used to build value expressions.
Java provides a rich set of operators:
1) assignment
2) arithmetic
3) relational
4) logical
5) bitwise
6) other
38
Assignment Operator
A binary operator:
variable = expression;
It assigns the value of the expression to the variable.
The types of the variable and expression must be
compatible.
The value of the whole assignment expression is the
value of the expression on the right, so it is possible
to chain assignment expressions as follows:
int x, y, z;
x = y = z = 2;
39
Arithmetic Operators
Java supports various arithmetic operators for:
1) integer numbers
2) floating-point numbers
There are two kinds of arithmetic operators:
1) basic: addition, subtraction, multiplication,
division and modulo
2) shortcut: arithmetic assignment, increment and
decrement
40
41
43
Increment/Decrement Operators
Two unary operators:
1) ++ increments its operand by 1
2) -- decrements its operand by 1
The operand must be a numerical variable.
Each operation can appear in two versions:
prefix version evaluates the value of the operand after
performing the increment/decrement operation
postfix version evaluates the value of the operand
before performing the increment/decrement operation
44
Table: Increment/Decrement
45
Example: Increment/Decrement
class IncDec {
public static void main(String args[]) {
int a = 1; int b = 2; int c, d;
c = ++b;
d = a++;
c++;
System.out.println(a= + a);
System.out.println(b= + b);
System.out.println(c= + c);
}
}
46
Relational Operators
Relational operators determine the relationship that
one operand has to the other operand, specifically
equality and ordering.
The outcome is always a value of type boolean.
They are most often used in branching and loop
control statements.
47
48
Logical Operators
Logical operators act upon boolean operands only.
The outcome is always a value of type boolean.
In particular, 1 and 2 and 1 or 2 logical operators
occur in two forms:
1) full op1 & op2 and op1 | op2 where both op1 and
op2 are evaluated
2) short-circuit - op1 && op2 and op1 || op2 where
op2 is only evaluated if the value of op1 is
insufficient to determine the final outcome
49
50
Strong Typing
Java is a strongly-typed language:
a) every variable and expression has a type
b) every type is strictly defined
c) all assignments are checked for type-compatibility
d) no automatic conversion of non-compatible,
conflicting types
e) Java compiler type-checks all expressions and
parameters
f) any typing errors must be corrected for compilation to
succeed
52
Simple Types
Java defines eight simple types:
1) byte 8-bit integer type
2) short 16-bit integer type
3) int 32-bit integer type
4) long 64-bit integer type
5) float 32-bit floating-point type
6) double 64-bit floating-point type
7) char symbols in a character set
8) boolean logical values true and false
53
54
55
57
58
59
Example: double
// Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi = 3.1416; // approximate pi value
double r = 10.8; // radius of circle
double a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
} O/p =Area of circle is 366.436224
60
Example: char
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}O/p ch1 and ch2 : X Y
62
64
Example: boolean
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
if (b) System.out.println("executed");
b = false;
if (b) System.out.println(not executed");
System.out.println("10 > 9 is " + (10 > 9));
}
65
}
Variables
1) declaration how to assign a type to a variable
2) initialization how to give an initial value to a variable
3) scope how the variable is visible to other parts of the
program
4) lifetime how the variable is created, used and destroyed
5) type conversion how Java handles automatic type
conversion
6) type casting how the type of a variable can be narrowed
down
7) type promotion how the type of a variable can be
expanded
66
67
Variable Declaration
We can declare several variables at the same time:
type identifier [=value][, identifier [=value] ]; ];
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte hog = 22;
double pi = 3.14159;
char kat = 'x';
68
Constant Declaration
A variable can be declared as final:
final double PI = 3.14;
The value of the final variable cannot change after it
has been initialized:
PI = 3.13;
69
Variable Identifiers
Identifiers are assigned to variables, methods and classes.
An identifier:
1) starts with a letter, underscore _ or dollar $
2) can contain letters, digits, underscore or dollar characters
3) it can be of any length
4) it must not be a keyword (e.g. class)
5) it must be unique in its scope
Examples: identifier, userName, _sys_var1, $change
The code of Java programs is written in Unicode, rather than
ASCII, so letters and digits have considerably wider
definitions than just a-z and 0-9.
70
Naming Conventions
Conventions are not part of the language.
Naming conventions:
1) variable names begin with a lowercase letter
2) class names begin with an uppercase letter
3) constant names are all uppercase
If a variable name consists of more than one word,
the words are joined together, and each word after the
first begins with an uppercase letter.
The underscore character is used only to separate
words in constants, as they are all caps and thus
cannot be case-delimited.
71
Variable Initialization
During declaration, variables may be optionally
initialized.
Initialization can be static or dynamic:
1) static initialize with a literal:
int n = 1;
2) dynamic initialize with an expression composed of
any literals, variables or method calls available at the
time of initialization:
int m = n + 1;
The types of the expression and variable must be the
same.
72
73
Variable Scope
Scope determines the visibility of program elements
with respect to other program elements.
In Java, scope is defined separately for classes and
methods:
1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
We consider the scope of method variables only; class
variables will be considered later.
74
Variable Scope
75
Scope Definition
A scope is defined by a block:
{
}
A variable declared inside the scope is not visible
outside:
{
int n;
}
n = 1;
76
Variable Lifetime
Variables are created when their scope is entered by
control flow and destroyed when their scope is left:
1) A variable declared in a method will not hold its
value between different invocations of this method.
2) A variable declared in a block looses its value when
the block is left.
3) Initialized in a block, a variable will be re-initialized
with every re-entry.
Variable3s lifetime is confined to its scope!
78
Type Differences
Suppose a value of one type is assigned to a variable
of another type.
T1 t1;
T2 t2 = t1;
What happens? Different situations:
1) types T1 and T2 are incompatible
2) types T1 and T2 are compatible:
a) T1 and T2 are the same
b) T1 is larger than T2
c) T2 is larger than T1
80
Type Compatibility
When types are compatible:
1) integer types and floating-point types are compatible
with each other
2) numeric types are not compatible with char or boolean
3) char and boolean are not compatible with each other
Examples:
byte b;
int i = b;
char c = b;
81
82
85
Control Flow
Java control statements cause the flow of execution to
advance and branch based on the changes to the state
of the program.
Control statements are divided into three groups:
1. selection statements allow the program to choose
different parts of the execution based on the
outcome of an expression
2. Iteration statements enable program execution to
repeat one or more statements.
3. Jump statements enable your program to execute in
a non-linear fashion
86
Selection Statements
Java selection statements allow to control the
flow of programs execution based upon
conditions known only during run-time.
Java provides four selection statements:
1.
2.
3.
4.
if
if-else
if-else-if
switch
87
if Statement
General form:
if (expression) statement;
If expression evaluates to true, execute
statement, otherwise do nothing.
The expression must be of type boolean.
88
Simple/Compound Statement
The component statement may be:
1) simple
if (expression) statement;
2) compound
if (expression) {
statement;
}
89
Simple/Compound Statement
90
Simple if Statement
Example:
class IfStat{
public static void main(String args[]) {
boolean b;
b = true;
System.out.println("b is " + b);
if (b) System.out.println("executed");
b = false;
if (b) System.out.println("not executed");
}
}
91
Compound if Statement
Example:
class IfState1{
public static void main(String args[]) {
int a=10;
if ( a>0) {
System.out.println( a is +ve num");
}
}
}
92
if-else Statement
If the conditional expression is true, the target
of the if will be executed;
otherwise, if it exists,the target of the else will
be executed.
At no time will both of them be executed.
The conditional expression controlling the if
must produce a boolean result.
93
if-else Statement
Syntax:
if(conditional_expression){
<statements>;
...;
...;
}
else{
<statements>;
....;
....;
}
94
if-else Statement
95
if else Statement
Example:
class IfElse{
public static void main(String args[]) {
int a=10;
if ( a>0) {
System.out.println( a is +ve num");
}
else{
System.out.println( a is - ve num");
}
}
96
}
Nested if Statement
A nested if is an if statement that is the target
of another if or else.
Nested ifs are very common in programming.
When you nest ifs, the main thing to remember
is that an else statement always refers to the
nearest if statement that is within the same
block as the else and that is not already
associated with an else.
97
Nested if Statement
class Example4_2{
public static void main(String Args[]){
int a = 3;
if (a <= 10 && a > 0){
System.out.println("Number is valid.");
if ( a < 5)
System.out.println("From 1 to 5");
else
System.out.println("From 5 to 10");
}
else
System.out.println("Number is not valid");
}
98
}
100
101
switch Statement
switch provides a better alternative than if-else-if
when the execution follows several branches
depending on the value of an expression.
The switch provides for a multiway branch. Thus,
it enables a program to select among several
alternatives.
the value of an expression is successively tested
against a list of constants.
When a match is found, the statement sequence
associated with that match is executed.
103
switch Statement
The general form of the switch statement is
switch (expression) {
case constant1:
statement sequence
break;
case constant2:
statement sequence
break;
case constant3:
statement sequence
break;
...
default:
statement sequence
}
104
switch Statement
105
switch Statement
Assumptions:
1. expression must be of type byte, short, int or char
2. each of the case values must be a literal of the compatible
type
3. case values must be unique
Semantics:
4. expression is evaluated
5. its value is compared with each of the case values
6. if a match is found, the statement following the case is
executed
7. if no match is found, the statement following default is
executed
. break makes sure that only the matching statement is executed.
. Both default and break are optional.
106
switch Statement
class SwitchDemo {
public static void main(String args[]) {
int i;
i = Integer.parseInt(args[0]);
switch(i) {
case 0: System.out.println("i is zero"); break;
case 1: System.out.println("i is one"); break;
case 2: System.out.println("i is two") ;break;
case 3: System.out.println("i is three"); break;
case 4: System.out.println("i is four"); break;
default: System.out.println("i is five or more");
}
}
}
107
For Loop
For loop executes group of Java statements as
long as the boolean condition evaluates to true.
For loop combines three elements which we
generally use: initialization statement, boolean
expression and increment or decrement
statement.
108
For Loop
For loop syntax
for( <initialization> ; <condition> ; <statement> )
{
.
<Block of statements>;
.
}
109
For Loop
110
For Loop
The initialization statement is executed before the
loop starts.
It is generally used to initialize the loop variable.
Condition statement is evaluated before each time the
block of statements are executed.
Block of statements are executed only if the boolean
condition evaluates to true.
Statement is executed after the loop body is done.
Generally it is being used to increment or decrement
the loop variable.
111
For Loop
Following example shows use of simple for loop.
for(int i=0 ; i < 5 ; i++)
{
System.out.println(i is : + i);
}
It is possible to initialize multiple variable in the
initialization block of the for loop by separating it by
comma as given in the below example.
For(i=0,j=5;i<5;i++)
It is also possible to have more than one increment or
decrement section as well as given below.
112
for(int i=0; i < 5 ; i++, j--)
114
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
115
do-while Loop
general form is
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes
the body of the loop and then evaluates the
conditional expression.
If this expression is true, the loop will repeat.
Otherwise, the loop terminates. As with all of
Javas loops, condition must be a Boolean
expression.
116
do-while Loop
117
do-while Loop
The do-while loop always executes its body at least
once, because its conditional expression is at the
bottom of the loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
118
}
Jump Statements
Java jump statements enable transfer of control to
other parts of program.
Java provides three jump statements:
1) break
2) continue
3) return
In addition, Java supports exception handling that
can also alter the control flow of a program.
119
1. break Statement
The break statement has three uses:
1) to terminate a case inside the switch
statement
2) to exit an iterative statement
3) to transfer control to another statement
(1) has been described.
We continue with (2) and (3).
120
Used inside nested loops, break will only terminate the innermost
loop:
class NestedLoopBreak {
public static void main(String args[]) {
for (int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for (int j=0; j<100; j++) {
if (j == 10) break; System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}
123
}
Labeled break
General form:
break label;
where label is the name of a label that
identifies a block of code:
label: { }
The effect of executing break label; is to
transfer control immediately after the block of
code identified by label.
125
127
continue Statement
The break statement terminates the block of code, in
particular it terminates the execution of an iterative
statement.
The continue statement forces the early termination of
the current iteration to begin immediately the next
iteration.
Like break, continue has two versions:
1) unlabelled continue with the next iteration of the
current loop
2) labeled specifies which enclosing loop to
continue
129
class LabeledContinue {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for (int j=0; j<10; j++) {
if (j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
131
Return Statement
The return statement is used to return from the
current method: it causes program control to transfer
back to the caller of the method.
Two forms:
1) return without value
return;
2) return with value
return expression;
132
Example: Return
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if (t) return; // return to caller
System.out.println("This won't execute.");
}
}
133
Arrays
An array is a group of liked-typed variables referred
to by a common name, with individual variables
accessed by their index.
Arrays are:
1) declared
2) created
3) initialized
4) used
Also, arrays can have one or several dimensions
134
Array Declaration
Array declaration involves:
1) declaring an array identifier
2) declaring the number of dimensions
3) declaring the data type of the array elements
Two styles of array declaration:
type array-variable[];
or
type [] array-variable;
135
Array Creation
After declaration, no array actually exists.
In order to create an array, we use the new operator:
type array-variable[];
array-variable = new type[size];
This creates a new array to hold size elements of type,
which reference will be kept in the variable arrayvariable.
136
Array Indexing
Later we can refer to the elements of this array
through their indexes:
array-variable[index]
The array index always starts with zero!
The Java run-time system makes sure that all array
indexes are in the correct range, otherwise raises a
run-time error.
137
monthDays[12] = 31;
System.out.print(April has );
System.out.println(monthDays[3] + days.);
}
}
138
Array Initialization
Arrays can be initialized when they are declared:
int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
Comments:
1) there is no need to use the new operator
2) the array is created large enough to hold all specified elements
139
140
Multidimensional Arrays
Multidimensional arrays are arrays of arrays:
1) declaration
int array[][];
2) creation
int array = new int[2][3];
3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };
141