Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 51

LECTURE TWO

JAVA PROGRAM

Java Source
Code

Java Compiler

Applet Type Application Type

Java Enabled
Browser Java Interpreter

Output
Output
SIMPLE JAVA PROGRAM-EXAMPLE 1
/*This is a simple java program*/
class Example
{
public static void main (String args[])
{
System.out.println (“This is a simple Java program”);
}
}
SIMPLE JAVA PROGRAM-SOME
IMPORTANT POINTS
 public: Access specifier. main() must be made public,
since it must be called by code defined outside it’s class.
 Static: It is required because main() is called without
creating an object of it’s class
 String args[]: An array of objects of type String class.
Each object of type string contains a character string. It
is used to manipulate command line argument.
 Java is case sensitive.
 System predefined class that refers to system.
out It is static data member of System class
println() It is a member of out object
JRE AND JDK
 JRE: Java Runtime Environment
 provides
 libraries,

 Java virtual machine,

 other components necessary for you to run applets


and applications
 JDK: Java Development Kit
 includes
 JRE

 command-line development tools such as compilers


and debuggers
IMPLEMENTING A JAVA PROGRAM
1. Creating a java program
2. Compiling a java program
3. Running the program

Creating a Java Program:


1. All java source file has an extension .java.
2. If a program contains multiple classes, the file name
must be the class name of the class containing the
main method.
IMPLEMENTING A JAVA PROGRAM
Compiling a Java Program:
 To compile a java program, execute the java compiler
javac, specifying the name of the source file on the
command line. C:\> javac Example.java
 When java source code is compiled, each individual
class is put into it’s own output file named after the class
and using the .class extension.
 Each file with .class extension contains the bytecode
corresponding to that class
IMPLEMENTING A JAVA PROGRAM
 To run the program, interpreter java is used the name of
the class that contains the main function.
c:\> java Example
 Actually it searches for Example. class file.
SIMPLE JAVA PROGRAM – EXAMPLE 2
import java.lang.Math
class SquareRoot
{
public static void main (String args [])
{
double x=5, y;
y = Math.sqrt(x);
System.out.println(“y = “+y);
}
}
THE PRIMITIVE TYPES
 There are exactly eight primitive data types in Java
 Four of them represent whole valued signed numbers:
 byte, short, int, long
 Two of them represent floating point numbers:
 float, double
 One of them represents characters:
 char
 And one of them represents boolean values:
 boolean
NUMERIC PRIMITIVE TYPES
 The difference between the various numeric primitive
types is their size, and therefore the values they can
store:

Type Storage Min Value Max Value

byte 8 bits -128 127


short 16 bits -32,768 32,767
int 32 bits -2,147,483,648 2,147,483,647
long 64 bits < -9 x 1018 > 9 x 1018

float 32 bits
double 64 bits
CHAR
 It uses unicode to represent character.
 The char type is unsigned 16 bit values ranging from 0 to 65536.
 ASCII still ranges from 0 to 127.

Example:
class test
{
public static void main (String args[])
{
char ch1, ch2;
ch1=88;
ch2=‘Y’;
System.out.println (“ch1 and ch2: “ + ch1+” “+ch2);
}
}
Output: ch1 and ch2: X Y
BOOLEANS
 Size is 1 bit – two value: true and false.
 This type is returned by all relational operators.
 Example:
boolean b;
b= true;
1. System.out.println(“b is “+b);
2. System.out.println(“10>9 is “ +(10>9));

Output:
b is true
10>9 is true
VARIABLES
 Variable is a name for a location in memory.
 Declaring a variable:
type identifier [=value][,identifier [=value]….];
 The initialization expression must result in a value of the
same or compatible type as that specified for the
variable.
 Dynamic Initialization: initialization expression may use
any element valid at the time of initialization, including
calls to methods, other variables, or literals.
 When a variable is not initialized, the value of that
variable is undefined.
SCOPE AND LIFETIME OF A
VARIABLE
 A block begins with an opening curly brace and ends by
a closing curly brace.
 A block determines scope, that defines which objects are
visible to other parts of your program.
 Variables declared within a block localize themselves.
 In case of nested block, the outer block encloses the
inner block. The variables declared in the outer block is
visible to the inner block but the reverse is not true.
 A variable will not hold it’s value once it has gone out of
it’s scope.
 In an inner block, it is not possible to declare a variable
of the same name as in outer block.
SCOPE AND LIFETIME OF A
VARIABLE
Example:
public static void main( String args[])
{
int x =10;
if ( x == 10)
{
int y =20;
System.out.println(“x and y: “ +x +” “+y);
x= y * 2;
}
y= 100; //Error
System.out.println (“x is “+x);
}
AUTOMATIC TYPE
CONVERSION
 When one type of data is assigned to another type of
variable, an automatic type conversion will take place if:
1. Two types are compatible.
2. The destination type is larger than the source type.
 It is known as widening conversion.
 The numeric types, including integer and floating point
types are compatible.
 Numeric types are not compatible with char or boolean.
 Char and boolean are not compatible with each other.
CASTING TYPE
 Problem: assigning int value to a byte type variable.
 This type of conversion is known as narrowing conversion.
 A cast is simply an explicit type conversion : (target_type) value
 Example:
int a;
byte b;
….
b = (byte) a;

Contains the remainder of an integer division by byte’s range.


CASTING TYPE
class test
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
b=(byte)i;
System.out.println (“Conversion of int to byte: ” + i +” “+ b);
i = (int)d;
System.out.println(“Conversion of double to int: “ +d+” “+i);
b=(byte)d;
System.out.println(“Conversion of double to byte: “ +d+” “+b);
}
};
CASTING TYPE
 Output:
Conversion of int to byte: 257 1
Conversion of double to int: 323.142 323
Conversion of double to byte: 323.142 67
CONTROL STATEMENT
 Java’s control statements can be put into following categories:
 Selection statement

 Iteration statement

 Jump statement

 Three decision making statements:

1. if statement

2. switch statement

3. conditional operator statement


THE IF STATEMENT
 The if statement has the following syntax:

The condition must be a boolean expression.


if is a Java It must evaluate to either true or false.
reserved word

if (condition)
statement;
Statement x;

If the condition is true, the statement is executed. 22


If it is false, the statement is skipped.
THE IF-ELSE STATEMENT
 An else clause can be added to an if statement to make an
if-else statement
if ( condition )
statement1;
else
statement2;
Statement x;

If the condition is true, statement1 is executed; if the


condition is false, statement2 is executed
One or the other will be executed, but not both 23
NESTED IF….ELSE
STATEMENTS
 The if..else statement can be contained in another if or else
statement.
if (test condition1)
{
if (test condition2)
statement-1;
else
statement-2;
}
else
statement-3;
statement-x;
24
NESTED IF….ELSE
STATEMENTS
 An else clause is matched to the last unmatched if (no
matter what the indentation implies!)
 Example:
if(data)
if(rate>5000)
taka = 0.05 * rate;
else
taka = 0.02 * rate;
rate = rate + taka;
 Braces can be used to specify the if statement to which
an else clause belongs
THE IF-ELSE-IF LADDER
 Sometime you want to select one option from several
alternatives
true
conditon1
if (conditon1) evaluated
statement1
statement1;
false
else if (condition2)
statement2; conditon2 true
statement2
else if (condition3) evaluated

statement3; false
else true
conditon3 statement3
statement4; evaluated

false

statement4
THE SWITCH STATEMENT
 The switch statement provides another means to decide which
statement to execute next
 The switch statement evaluates an expression, then attempts to
match the result to one of several possible cases
 The expression of a switch statement must result in an integral
type (byte, short, int, char etc)

Note: JDK 7 allows expression can be of type String.


 The flow of control transfers to statement associated with the
first value that matches 27
THE SWITCH STATEMENT
 The general syntax of a switch statement is:

switch (expression) {
case value1:
statement-list1
switch break;
and case value2:
case statement-list2
are break;
reserved case value3:
words statement-list3 If expression
break; matches value2,
case default: control jumps
statement-list4 from here
}
THE SWITCH STATEMENT
 A break statement causes control to transfer to the end of the
switch statement
 If a break statement is not used, the flow of control will
continue into the next case
 Sometimes this can be appropriate, but usually we want to
execute only the statements associated with one case
THE SWITCH STATEMENT
 A switch statement can have an optional default case
 The default case has no associated value and simply uses
the reserved word default
 If the default case is present, control will transfer to it if
no other case value matches
 If there is no default case, and no other value matches,
control falls through to the statement after the switch
SWITCH EXAMPLE
char letter = 'b'; char letter = 'b';

switch (letter) { switch (letter) {


case 'a': case 'a':
System.out.println("A"); System.out.println("A");
break; case 'b':
case 'b': System.out.println("B");
System.out.println("B"); case 'c':
break; System.out.println("C");
case 'c': break;
System.out.println("C"); case 'd':
break; System.out.println("D");
case 'd': break;
System.out.println("D"); default:
break; System.out.println(”?");
default: }
System.out.println(”?");
}

B B
C
ITERATION STATEMENTS
 Iteration statements allow us to execute a statement multiple times until a
termination condition is met.
 Often they are referred to as loops
 Java has three kinds of iteration statements:
 the while loop
 the do-while loop
 the for loop
THE WHILE STATEMENT
 The while statement has the following syntax:

while (condition)
while is a
statement;
reserved word

If the condition is true, the statement is executed.


Then the condition is evaluated again.

The statement is executed repeatedly until 33


the condition becomes false.
LOGIC OF A WHILE LOOP

condition
evaluated

true false

statement

Note that if the condition of a while statement is false


initially, the statement is never executed. Therefore, the body
of a while loop will execute zero or more times
WHILE LOOP EXAMPLE
int LIMIT = 5;
int count = 1;
Output:
while (count <= LIMIT) {
1
System.out.println(count); 2
3
count += 1;
4
} 5

--Null statements are valid in java.


NESTED LOOPS
 Similar to nested if statements, loops can be nested as
well
 That is, the body of a loop can contain another loop
 Each time through the outer loop, the inner loop goes
through its full set of iterations
THE DO-WHILE
STATEMENT
 The do-while statement has the following syntax:

do and do{
while are statement;
reserved } while (condition);
words

The statement is executed once initially,


and then the condition is evaluated

The statement is executed repeatedly


until the condition becomes false
DO-WHILE EXAMPLE
int LIMIT = 5;
int count = 1;
Output:
do {
System.out.println(count); 1
count += 1; 2
3
} while (count <= LIMIT);
4
5
COMPARING WHILE AND DO-
WHILE
while loop Do-while loop

statement
condition
evaluated
true

true false condition


evaluated
statement
false
THE FOR STATEMENT
 The for statement has the following syntax:

The initialization The statement is


Reserved
is executed once executed until the
word
before the loop begins condition becomes false

for (initialization; condition; increment)


statement;

The increment portion is executed at the


end of each iteration
The condition-statement-increment cycle is
executed repeatedly
THE FOR STATEMENT
 A for loop is functionally equivalent to the following
while loop structure:

initialization;
while (condition) {
statement;
increment;
}
LOGIC OF A FOR LOOP
initialization

condition
evaluated

true false

statement

increment
FOR EXAMPLE
int LIMIT = 5;
for (int count = 1; count <= LIMIT; count++) {
System.out.println(count);
}

Output:

1
2
3
4
5
THE FOR STATEMENT
 Each expression in the header of a for loop is optional

 If the initialization is left out, no initialization is


performed
 If the condition is left out, it is always considered to
be true, and therefore creates an infinite loop
 If the increment is left out, no increment operation is
performed

 Both semi-colons are always required in the for loop


header
JUMP STATEMENTS-
BREAK
 The break statement has three uses:
 It terminates a statement sequence in a switch statement.
 It can be used to exit a loop.
 It can be used as a civilized form of goto.
 Civilized Form of Goto Statement
 break lable;

where label is the name of the block enclosing the break


statement.
• Labled break is used to transfer control from a set of nested
blocks.
EXAMPLE-BREAK STATEMENT
class test_break1
{ public static void main(String args[])
{
boolean t =true;
first:{
second:{
third:{
System.out.println("Before the break.");
if(t)
break second;
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
EXAMPLE-BREAK STATEMENT
class test_break2
{
public static void main(String args[])
{
one: for(int i=0;i<3;i++)
{
System.out.print("Pass: "+i+": ");
}

for(int j=0; j<100;j++)


{
if(j==10) break one; //Wrong
System.out.print(j+" ");
}
}
}
JUMP STATEMENT-
CONTINUE
 Continue statement is used to run a loop but stop
processing the remainder of the code in its body for a
particular iteration.
 In while and do-while loop, a continue statement causes
control to be transferred directly to the conditional
expression. In a for loop, control goes first to the
iteration portion of the for statement and then to the
conditional expression.
EXAMPLE-CONTINUE
STATEMENT
class test_continue Output:
{ public static void main(String args[]) 0
{ outer: for(int i=0; i<4;i++){ 01
024
for(int j=0;j<4;j++) {
0369
if(j>i) {
System.out.println();
continue outer;
}
System.out.print(" "+(i*j));
}
}
System.out.println();
}
}
JUMP STATEMENT-
RETURN
class test{
public static void main (String args[])
{
boolean t =true;
System.out.println(“Before the return”);
if(t) return;

System.out.println(“This won’t execute.”);


}
}
NESTED LOOP
 Read and practice by yourself.

You might also like