Java Language
Naorem Karline Singh
Outline
Java Language Basics:
1. Syntax
2. Types
3. Variables
4. Arrays
5. Operators
6. Control flow
Control Flow
• Writing a program means typing statements into a file.
• Without control flow, the interpreter would execute these statements in the
order they appear in the file, left-to-right, top-down.
• Control flow statements, when inserted into the text of the program,
determine in which order the program should be executed.
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
Control Flow
Java selection statements allow to control the flow of program’s execution
based upon conditions known only during run-time.
Java provides four selection statements:
1) if
2) if-else
3) if-else-if
4) switch
if statement
General form:
if (expression) statement
If expression evaluates to true, execute statement, otherwise do
nothing.
The expression must be of type boolean.
Simple or Compound if statement
The component statement may be:
1) simple
if (expression) statement;
2) compound
if (expression) {
statement;
}
if-else statement
Suppose you want to perform two different statements depending on the
outcome of a boolean expression. if-else statement can be used.
General form:
if (expression) statement1
else statement2
Again, statement1 and statement2 may be simple or compound.
if-else-if statement
General form:
if (expression1) statement1
else if (expression2) statement2
else if (expression3) statement3
…
else statement
Semantics:
1) statements are executed top-down
2) as soon as one expressions is true, its statement is executed
3) if none of the expressions is true, the last statement is executed
Example: if-else-if
class IfElse {
public static void main(String args[]) {
int month = 4;
String season;
if (month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Switch Statement
switch provides a better alternative than if-else-if when the execution
follows several branches depending on the value of an expression.
General form:
switch (expression) {
case value1: statement1; break;
case value2: statement2; break;
case value3: statement3; break;
…
default: statement;
}
Switch Statement
Nested switch Statement
A switch statement can be nested within another switch statement:
switch(count) {
case 1:
switch(target) {
case 0:System.out.println(“target is zero”);
break;
case 1:System.out.println(“target is one”);
break;
}
break;
case 2: …
}
Since, every switch statement defines its own block, no conflict arises between the case
constants in the inner and outer switch statements.
Comparing switch and if
Two main differences:
1) switch can only test for equality, while if can evaluate any kind of boolean expression
2) Java creates a “jump table” for switch expressions, so a switch statement is usually more
efficient than a set of nested if statements
Iteration Statements
Java iteration statements enable repeated execution of part of a program until a certain termination
condition becomes true.
Java provides three iteration statements:
1) while
2) do-while
3) for
While Statements
General form:
while (expression) statement
where expression must be of type boolean.
Semantics:
1) repeat execution of statement until expression becomes false
2) expression is always evaluated before statement
3) if expression is false initially, statement will never get executed
Simple / Compound Statement
The component statement may be:
1) simple
while (expression) statement;
2) compound
while (expression) {
statement;
}
Example: while
class MidPoint {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
while(++i < --j) {
System.out.println(“i is " + i);
System.out.println(“j is " + j);
}
System.out.println(“The midpoint is " + i);
}
}
do-while Statement
If a component statement has to be executed at least once, the do-while statement is more
appropriate than the while statement.
General form:
do statement
while (expression);
where expression must be of type boolean.
Semantics:
1) repeat execution of statement until expression becomes false
2) expression is always evaluated after statement
3) even if expression is false initially, statement
Example: do-while
class DoWhile {
public static void main(String args[]) {
int i;
i = 0;
do
i++;
while ( 1/i < 0.001);
System.out.println(“i is “ + i);
}
}
for statement
When iterating over a range of values, for statement is more suitable to use
then while or do-while.
General form:
for (initialization; termination; increment)
statement
where:
1) initialization statement is executed once before the first iteration
2) termination expression is evaluated before each iteration to
determine when the loop should terminate
3) increment statement is executed after each iteration
for statement Semantics
This is how the for statement is executed:
1) initialization is executed once
2) termination expression is evaluated:
1) if false, the statement terminates
2) otherwise, continue to (3)
3) increment statement is executed
4) component statement is executed
5) control flow continues from (2)
Loop Control Variable
The for statement may include declaration of a loop control variable:
for (int i = 0; i < 1000; i++) {
…
}
The variable does not exist outside the for statement.
Loop Control Variable
The for statement may include declaration of a loop control variable:
for (int i = 0; i < 1000; i++) {
…
}
The variable does not exist outside the for statement.
Example: for
class FindPrime {
public static void main(String args[]) {
int num = 14;
boolean isPrime = true;
for (int i=2; i < num/2; i++) {
if ((num % i) == 0) {
isPrime = false;
break;
}
}
if (isPrime) System.out.println("Prime");
else System.out.println("Not Prime");
}
}
Many Initialization/Iteration Parts
The for statement may include several initialization and
iteration parts.
Parts are separated by a comma:
int a, b;
for (a = 1, b = 4; a < b; a++, b--) {
…
}
skipping iteration Parts
The for statement need not have all components:
class ForVar {
public static void main(String args[]) {
int i = 0;
boolean done = false;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}
}
}
Empty for
In fact, all three components may be omitted:
public class EmptyFor {
public static void main(String[] args) {
int i = 0;
for (; ;) {
System.out.println(“Infinite Loop “ + i);
}
}
}
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. Exception handling will be explained in its own section.
break Statements
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).
Loop Exit with break
When break is used inside a loop, the loop terminates and control is
transferred to the following instruction.
class BreakLoop {
public static void main(String args[]) {
for (int i=0; i<100; i++) {
if (i == 10) break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Break in Nested Loops
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.");
}
}
Control Transfer with break
Java does not have an unrestricted “goto” statement, which tends to produce code that is
hard to understand and maintain.
However, in some places, the use of gotos is well justified. In particular, when breaking out
from the deeply nested blocks of code.
break occurs in two versions:
1) unlabelled
2) labeled
The labeled break statement is a “civilized” replacement for goto.
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.
Example: Labeled break
class Break {
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(“After second block.");
}
}
}
Example: Labeled break
class Break {
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(“After second block.");
}
}
}
Example: Nested Loop break
class NestedLoopBreak {
public static void main(String args[]) {
outer: for (int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for (int j=0; j<100; j++) {
if (j == 10) break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}
Break Without Label
It is not possible to break to any label which is not defined for an enclosing block. Trying to do so will
result in a compiler error.
class BreakError {
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;
System.out.print(j + " ");
}
}
}
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
Example: Unlabeled continue
class Continue {
public static void main(String args[]) {
for (int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}
Example: Labeled continue
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();
}
}
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;
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.");
}
}
Exercise: Control Flow
1) Write a program that prints all the prime numbers between 1 and 49 to the console.
2) Write a program that prints the first 20 Fibonacci numbers.
The Fibonacci numbers are defined as follows:
The zeroth Fibonacci number is 1.
The first Fibonacci number is also 1.
The second Fibonacci number is 1 + 1 = 2.
The third Fibonacci number is 1 + 2 = 3.
In other words, except for the first two numbers each Fibonacci number
is the sum of the two previous numbers.