You are on page 1of 21

Unit – I

Basic Syntactical Constructs in Java


What is Java
Java is a programming language and computing platform first released by Sun Microsystems in 1995. It has evolved from
humble beginnings to power a large share of today’s digital world, by providing the reliable platform upon which many services
and applications are built. New, innovative products and digital services designed for the future continue to rely on Java, as

well.
Java ही एक प्रोग्रॅमिंग भाषा आणि संगणकीय प्लॅटफॉर्म आहे जी सन मायक्रोसिस्टम्सने 1995 मध्ये प्रथम प्रसिद्ध के ली आहे. ती विनम्र सुरुवातीपासून विकसित झाली आहे, ज्यामुळे आजच्या डिजिटल जगाचा मोठा वाटा आहे, ज्यावर अनेक सेवा आणि अनुप्रयोग तयार के ले

जातात. भविष्यासाठी डिझाइन के लेली नवीन, नाविन्यपूर्ण उत्पादने आणि डिजिटल सेवा देखील Java वर अवलंबून राहतील.

1.1 Java Features


Basic needs behind developing java language were portability and security. But
other features also add potential to the language. They make java first application language
of the World Wide Web. Apart from this, java is one of the important languages for
developing stand-alone applications also.
These important features of java are,
- Simple
- Object-Oriented
- Compiled & Interpreted
- Platform independent or Architecture-neutral or Portable
- Robust
- Secure
- Dynamic
- Distributed
- Multi-threaded
- High performance

1.1.1 Simple
Java is a simple programming language. It is easy for programmer to learn and use.
For a programmer who knows C, learning java is easy. For a programmer having
experience of C++, very less energy will be required for learning and using java.
Also some of the confusing concepts in C/C++ are either removed in java or are
made simpler. (e.g. pointers, preprocessor header files, goto, operator overloading,
multiple inheritance)

1.1.2 Object-Oriented
Java is a true object-oriented language. Everything in java is in the form of classes
and objects. Even main( ) method is also a method of a class. Object model in java is
simple and easy to extend.

1.1.3 Compiled and Interpreted


Generally a computer programming language is either compiled or interpreted. In
java both these styles are combined. In a two-stage system of java, initially source code is
translated by a java compiler into an intermediate code known as byte-code. In the
second stage, this byte-code is interpreted (converted [line-by-line] to machine code and
executed) by java interpreter. Java

5-1
byte-code can run on any system that provides Java Virtual Machine. Thus java enables
creation of cross-platform programs.

1.1.4 Platform-independent or Architecture-neutral or Portable


बहुतेक प्रोग्रामरना भेडसावणारी मुख्य समस्या ही होती की एकदा लिहिलेला आणि
चाचणी के लेला प्रोग्राम नंतर वेगवेगळ्या मशीनवर किं वा त्याच मशीनवर चालेल याची
त्यांना कोणतीही हमी नव्हती. वेगवेगळ्या मशीन्ससाठी, प्रोसेसर, ऑपरेटिंग सिस्टम
इत्यादीसारखे आर्कि टेक्चरल फरक आहेत
Even for the same machine, there may be some upgrades in operating system,
system resources or even processor. So, the main goal while designing java programming
language was making it platform independent (program may run on any platform),
architecture-neutral (program may run on any processor-operating_system combination)
and portable (program developed on one architecture/machine may run on any other
architecture/machine).
Java provides portability in two ways. Byte-code generated by java compiler is
machine-independent. Also, sizes of primitive data types of java are machine-independent.

1.1.5 Robust
As java is application language for World Wide Web, the program needs to be run
reliably on any platform at any web location. To bring this robustness, java forces
programmer to find the mistakes in the program at early stage of program development. As
java is strictly typed language, it strictly checks the code at compile-time. The code is
again checked at run-time.
The main reasons for failure of any program are memory management mistakes
and mishandled exceptions. In java dynamic memory allocation and de-allocation is not
needed to be handled by programmer, it is handled by java itself. Also java provides object
oriented exception handling for dealing with the exceptions. Due to this risk of crashing of
the program is eliminated.

1.1.6 Secure
Security is an important concern for the languages that are used for programming
on Internet. Java system verifies all memory accesses. It also ensures that no virus is
communicated through applet.

1.1.7 Dynamic
Java is a dynamic language. Java program carries significant amount of run-time
information, which is used to verify and resolve accesses to objects at run-time. Due to
this, code can be linked dynamically in a safe manner.

1.1.8 Distributed
Java is designed for distributed environment of Internet. Using Remote Method
Invocation (RMI) package of java, procedures can be called from remote locations. Thus
multiple programmers at multiple locations can may collaborate on the same project.

1.1.9 Multi-threaded
Java supports multi-threaded programming. It allows writing a program that does
many things simultaneously.

5-2
1.1.10 High performance
Java performs well even on low-power CPUs. Java byte-code is designed so that it
can be easily translated to machine-code for high performance using Just-In-Time
compiler.
Also, java architecture is designed to reduce overheads during run-time.

1.2 Classes, Objects

1.2.1 Defining a class


As we know, class is wrapping of data and code operating on that data in a single
unit. Most real-world classes contain both data and code. But simple classes may contain
only data or only code.
Data in the class are called instance variables (because each instance of class
[i.e. object] contains its own copy of these variables) whereas codes in the class are called
methods. Both, instance variable and methods are members of the class. General form
or syntax of class definition is shown below.

class classname
{
data-type instance-variable1;

data-type instance-variable2;
---
data-type instance-variableN;

return-type methodname1(parameter-list)
{
// Body of method
}
return-type methodname2(parameter-list)
{
// Body of method
}
---
return-type methodnameN(parameter-list)
{
// Body of method
}
5-3
}

In java methods can be defined within class only (not like C++ where we
can de
fine the member functions outside the class). In C++ class definition ends
with a semicolon. But in java class definition ends with mere closing brace.

Example:
class point
{
int x;

5-4
int y;
void getd( )
{
//body of getd( )
}
void putd( )
{
//body of putd( )
}
}

1.2.2 Creating object


Class is just a declaration. It does not create actual object. Creating an object is a
two-step process. In first step, variable of class type is declared with following syntax.

class-name variable-name;

e.g. point p;
This is not an object. It is just a variable which can refer to an object. In second
step we have to acquire actual object and assign it to the variable with following syntax.

variable-name = new class-name( );

e.g. p = new point( );


The new operator allocates memory required for an object of the specified class
and returns reference to it.
The above two steps may be combined together for object creation as,

class-name variable-name = new class-name( );

e.g. point p = new point( );

1.2.3 Accessing class member


For accessing a member of a class from outside of the class, we should have object
of that class. The members can be accessed through the object by using member access
operator (‘.’ operator).

Examples:
p.x=10;
p.display( );

1.3.1 Java tokens


Smallest individual unit in a program is called as token. Compiler identifies these
tokens and work on them for conversion of source program into byte-code. Java language
has following types of tokens.
- Keywords

5-5
- Identifiers
- Literals
- Operators
- Separators

1.3.1.1 Keywords
The reserved words whose meaning is predefined with Java are called keywords.
There are 50 keywords in Java. All keywords are in lower-case only. As the keywords are
having specific meaning, we cannot use them as identifiers. The keywords in Java are
listed below.

1.3.1.2 Identifiers
They are used for naming classes, methods, variables, objects, labels, packages and
interfaces. Rules for defining identifiers are as follows,
- Allowed characters in identifiers are: alphabets (A-Z, a-z), digits (0-9),
underscore (_) and dollar ($). No any other character can be used in identifier.
- Identifiers should not begin with a digit.
- They can be of any length.
- Keyword cannot be used as identifier.

1.3.1.3 Literals
Sequence of characters (may contain digits, alphabets or other characters) that
represent constant values to be stored in variables are called literals. There can be different
types of literals as integer literals, floating-point literals, character literals, string literals
and Boolean literals.

1.3.1.4 Operators
Operator is a symbol(s) that takes one or more arguments (operands) and performs
an operation on the operands. Operators will be discussed in detail in 1.4.

1.3.1.5 Separators
The symbols that are used identifying the separation of group of code are called
separators. Various separators in Java are shown in table 1.1,

Table 1.1: Separators in Java


Separator Name Use
() Parentheses For enclosing parameters (arguments) in function
definition or function call
{} Braces For enclosing a block of code or for containing
values of automatically initialized arrays
[] Brackets For declaring array and for dereferencing array elements

; Semicolon For separating statements


, Comma For separating identifiers in declaration
. Period For separating package name from sub-packages and
classes.

5-6
1.3.2 Constants
The thing of which value cannot be changed throughout the execution of a program
is called a constant. In Java constants are classified as numeric constants and string
constants. Numeric Constants can be either integer constants or real constants. String
constants can be either single character constants or string constants.
Integer constants are the constants of integer type. They can contain only
digits and/or sign (in case of hexadecimal constants ‘x’ or ‘X’ is allowed along with ‘a’ to
‘f’ or ‘A’ to ‘F’). Some of the examples of integer constants are,
172 -53 0x3A 0x4bc
Real constants are the constants of values that represent real-world entities like
price, temperature etc. They can contain digits, decimal point and/or sign. We can also
have constants in exponential representation.
72.54 -53.0 0.67 1.23e-4 0.51E8
Single character constants contain single character enclosed within single
quotation marks.
‘M’ ‘y’ ‘&’ ‘3’
String constants contain sequence of characters enclosed within double
quotation marks.
“Sanjivani” “Java 2 Programming” “b4u”
Java also supports escape sequences. Some of escape sequences are listed
below.
‘\b’ Backspace
‘\n Newline
‘\t’ Horizontal tab
‘\’ ‘ Single quote ‘\”
‘ Double quote
‘\\’ Backslash

In addition to above constants, java also supports symbolic constants.


Syntax for declaring symbolic constants in java is as follows. final
data-type symbolic-constant-name = value;
They cannot be declared inside methods. They must be declared at the beginning of
class as member of class. Preferably (not as a rule), names of constants are written in all
caps.
Some valid examples are, final
int SIZE = 20;
final float PI = 3.14159;

1.3.3 Variables
The thing of which value can be changed throughout the execution of a program is
called a variable. We have already discussed about rules for naming variables in Java in
1.3.1.2. Syntax for declaring variable is as follows,
data-type identifier-name[,identifier-name[,…]];

1.3.4 Dynamic Initialization


Java allows variables to be initialized dynamically with the help of expressions
also. Following examples of initialization of variables are valid.
float a=10.5;

5-7
int x=-145;

double r=Math.sqrt(a*a+b*b); //Dynamic initialization float


result=a/x; //Dynamic initialization

1.3.5 Data types


Java is a strongly typed language. This fact makes Java more robust. Every variable
and expression has a type. Also, all the assignments (direct assignments or indirectly
through parameter passing) are checked for type- compatibility. Automatic conversions are
not done. Java compiler strictly checks for type compatibility and forces such errors (if
any) to be corrected before successful compiling.
Primary data types of Java can be classified in two categories as numeric and non-
numeric data types. Numeric data types can further be classified as Integers and Floating
point numbers (real numbers). Non-numeric data types can further be classified as
characters and Boolean. Java supports four integer data types as byte, short, int and long.
Two floating point data types are float and double. Let us discuss about all the above data
types.

byte
- It is smallest integer data type which can hold signed whole numbers.
- Memory required is 1 byte or 8 bits
- Range: -128 to 127
- Keyword: byte
- Example: byte a,b;
- Default value is 0.

short
- It is integer data type which can hold signed whole numbers.
- Memory required is 2 bytes or 16 bits
- Range: -32768 to 32767
- Keyword: short
- Example: short x,y;
- Default value is 0.

int
- It is integer data type which can hold signed whole numbers.
- Memory required is 4 bytes or 32 bits
- Range: -2147483648 to 2147483647
- Keyword: int
- Example: int m,n;
- Default value is 0.

long
- It is integer data type which can hold signed whole numbers.
- Memory required is 8 bytes or 64 bits
- Range: -9223372036854775808 to 9223372036854775807
- Keyword: long
- Example: long e,f;

5-8
- Default value is 0.

float
- It is floating point data type which can hold single-precision floating point
numbers.
- Memory required is 4 bytes or 32 bits
- Range: 1.4e-45 to 3.4e+38
- Keyword: float
- Example: float result;
- Default value is 0.0.

double
- It is floating point data type which can hold double-precision floating point
numbers.
- Memory required is 8 bytes or 64 bits
- Range: 4.9e-324 to 1.8e+308
- Keyword: double
- Example: double r,a;
- Default value is 0.0.

char
- It is non-numeric data type which can hold single character. Java used Unicode
to represent characters. Unicode defines a fully international character set that
can represent all the characters found in all human languages.
- Memory required is 2 bytes or 16 bits
- Range: 0 to 65535 (Standard ASCII characters range within 0 to 127 of this
range)
- Keyword: char
- Example: char ch1,ch2;
- Default value is null.

boolean
- It is Boolean data type which can hold logical values as true or false.
- Memory required is 8 bytes or 64 bits
- Range: true or false
- Keyword: boolen
- Example: boolean temp;
- Default value is false.

1.3.6 Scope of variable


A block starts with an opening curly brace and ends with a closing curly brace. A
block defines scope. So, if a variable is declared in a method, its scope is within that
method only. It is like concept of local variable in C. Variable declared inside a scope are
not visible to the code written outside the scope.
In Java, we cannot have global variables. This is because java is truly object
oriented and everything should be within classes.

5-9
1.3.7 Arrays
Array is a collection of elements of same data type. All the elements of array are
referred by same name. Arrays can have one or more dimensions.
Arrays in java work somewhat different as compared to C/C++.
One-dimensional array can be declared as,
data-type arr-name[ ];
Here arr-name is a reference only. No any memory is allocated to this array.
Memory allocation may be done with the help of new as follows,
arr-name = new data-type[size];

Example:
int a[ ]; //reference creation
a = new int[15]; //Reference is referring to array of 15 integers
We may combine the two statements as, int
a[ ] = new int[15];
We may also use array-initializer for initializing the arrays as follows. int a[ ]
= {12, 14, 5, 78, 35, 25};
//creates array of six integers with the values mentioned
//as their initial values.
Similarly, a multi-dimensional array may be declared as, int a[ ]
[ ] = new int[3][3];
//creates 2D array of size 3X3
It is possible in Java to have different value of second dimension for each row as,
int b[ ][ ] = new int[3][ ];
b[0] = new int[2];
b[1] = new int[4];
b[2] = new int[3];
The above array has 3 rows. Row 0 has 2 elements, row 1 has 4 elements
and row 2 has 3 elements.

1.3.8 Strings
In Java, string is neither a primary data type nor an array of characters. Rather,
String defines an object. String type is used to declare string variables. It may be done as
follows,
String str;
str = new String( );
We may also initialize the string at the time of creation only as follows, String
str;
str = new String(“Sanjivani”); //str contains “Sanjivani” Java
strings may be concatenated using ‘+’ operator as follows,
String s3 = s1 + s2;
String str = “Kopargaon” + “Bet”
String class supports various methods. Some of them are explained in table 1.2.

5-10
Table 1.2: Some Methods of String class
Method Call Use
s2 = s1.toLowerCase( ); Converts string s1 to lowercase and stores result in s2
s2 = s1.toUpperCase( ); Converts string s1 to uppercase and stores result in s2
s1.equals(s2) Returns true if s1 is equal to s2
s1.equalsIgnoreCase(s2) Returns true if s1 is equal to s2 (ignoring case)
s2=s1.trim( ); Removes white spaces at the beginning and end of string s1
and copies it to s2
s1.length( ) Returns length of s1
s1.charAt(n) Returns character at ‘n’ location
s1.compareTo(s2) Returns negative value (<0), if s1<s2
Returns positive value (>0), if s1>s2
Return zero, if s1 = s2
s1.concat(s2) Concatenates s1 and s2
s1.substring(n) Returns substring starting from nth character
s1.substring(n,m) Returns substring starting from nth character up to mth character
(not including mth character)

1.4.1 Operators
Operators of Java can be classified as,
- Arithmetic operators
- Relational operators
- Logical operators
- Assignment operators
- Increment/decrement operators
- Conditional operator
- Bit-wise operators
- Special operators

1.4.1.1 Arithmetic Operators


Java provides all the basic arithmetic operators. They are shown in Table
1.3. These operators can operate on built-in data types of Java.
Table 1.3: Arithmetic Operators
Operator Meaning
+ Addition or unary plus
– Subtraction or unary minus
* Multiplication
/ Division
% Modulo Division (used with only integers)

1.4.1.2 Relational Operators


For taking certain decisions, we have to compare two entities. This can be
done with the help of relational operators shown in Table 1.4.
An expression containing relational operator is called as relational
expression. Value of relational expression is either true or false.

5-11
Table 1.4: Relational Operators
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to

1.4.1.3 Logical Operators


If we want to combine two relational expressions or if we want to negate a
relational expression, logical operators are used. They are shown in Table 1.5.
Table 1.5: Logical Operators
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Truth table for above logical operators is shown in table 1.6.
Table 1.6: Truth Table for Logical Operators
exp1 exp2 Value of
! exp1 exp1 && exp2 exp1 || exp2
true true false true true
true false false false true
false true true false true
false false true false false

1.4.1.4 Assignment Operators


These operators are used for assigning result of an expression to a variable.
The assignment operators supported by Java are shown in Table 1.7.
Table 1.7: Assignment Operators
Operator Meaning
= Normal assignment
+= x+=12; → x=x+12;
–= x– =7; → x=x–7;
*= x*=2; → x=x*2;
/= x/=2; → x=x/2;

1.4.1.5 Increment and Decrement Operators


Table 1.8: Increment and Decrement Operators
Operator Meaning
++ Post-increment or Pre-increment
–– Post-decrement or Pre-decrement

5-12
These operators are used for increasing or decreasing value of a variable by
1. These operators are unary operators and require a variable as their operand.
When postfix ++ (or – –) is used with a variable in an expression, the
expression is evaluated with original value of variable and then the variable is
incremented (or decremented).
When prefix ++ (or – –) is used with a variable in an expression, the
variable is incremented (or decremented) and then the expression is evaluated with
new value of variable.

1.4.1.6 Conditional Operators


Java provides a ternary conditional operator pair as ‘? :’ which can be used
in the following form.
exp1 ? exp2 : exp3
Here exp1 is relational expression. At first, exp1 is evaluated. If the result of
exp1 is TRUE, exp2 is evaluated. If the result of exp1 is FALSE, exp3 is evaluated.
e.g.
interest_rate = (age >= 60) ? 9.5 : 8.75;
If value of variable age is greater than or equal to 60, 9.5 is assigned to
variable interest_rate. Otherwise, 8.75 is assigned to variable interest_rate.

1.4.1.7 Bitwise Operators


Java provides bit-wise operators for manipulation of data at bit- level. These
operators operate on integers.
Table 1.9: Bitwise Operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift Left
>> Shift Right
>>> Shift Right with zero fill

1.4.1.8 Special Operators


Java supports some special operators as instanceof operator and dot operator
(member selection operator).
The instanceof operator returns true if object on its left side is an instance of
class on its right side. Otherwise it returns false.
e.g.
If p1 is instance of class person, p1
instanceof person
returns true. Otherwise it returns false.

1.4.2 Operator precedence and associativity


When an expression contains multiple operators, operator precedence is used to
determine how the expression is evaluated. Operator precedence is

5-13
defined in the form of different levels of precedence. Operators at higher level of
precedence are evaluated first. The operators in the same level of precedence are evaluated
according to defined associativity in that level (either left to right or right to left).
Table 1.10: Operator precedence and associativity
Precedence Operator Description Associativity
1 [] array index method Left -> Right
() call member access
.
2 ++ pre or postfix increment pre Right -> Left
-- or postfix decrement unary
plus, minus bitwise NOT
+- logical NOT
~
!
3 (type cast) type cast object Right -> Left
new creation
4 * multiplication Left -> Right
/ division
modulus (remainder)
%
5 +- addition, subtraction Left -> Right
+ string concatenation
6 << left shift Left -> Right
>> signed right shift
>>> unsigned or zero-fill right shift
7 < less than Left -> Right
<= less than or equal to
> greater than
greater than or equal to
>=
reference test
instanceof
8 == equal to Left -> Right
!= not equal to
9 & bitwise AND Left -> Right
10 ^ bitwise XOR Left -> Right
11 | bitwise OR Left -> Right
12 && logical AND Left -> Right
13 || logical OR Left -> Right
14 ? : conditional (ternary) Right -> Left
15 = assignment and short hand Right -> Left
+= assignment operators
-=
*=
/=
%=
&=
^=
|=
<<=
>>=
>>>=

5-14
Table 1.10 shows almost all the operators in Java, their precedence level and
associativity. First priority is the highest level of precedence and 15 th priority is the lowest
level of precedence.

1.4.3 Evaluation of expressions


All the expressions in Java are evaluated by considering operator precedence and
associativity. Expression takes a general form as,
variable = expression;
The expression on right hand side is evaluated first. Then the resultant value is stored in
the variable on left hand side.

1.4.4 Typecasting in evaluation


While writing programs it is very common to assign value of one type of variable
into another type. Also one type of variable is also used in an expression which is assigned
to variable of another type. In such cases it is necessary to convert the type of such
variable to expected data type. This is done automatically. It is called automatic type
conversion. Automatic type conversion happens if,
- Source type and destination types are compatible.
- Destination type is larger than source type.

Automatic type conversion is very much helpful. But it does not always fulfill the
requirements. In many situations there is a need to change data type of a value temporarily.
This may be required while assigning value to other variable or in evaluation of an
expression. It is achieved through typecasting. (In case of compatible types, it may happen
automatically.) Typecasting is explicit type conversion between two
incompatible types. Syntax of typecasting is as follows,
(target-type) value

Value gets converted to target-type.

Example:
int i=10;
short s=(short)i;

During the type conversion, some changes may occur as,


- float to int – truncation of fractional part
- long to int – dropping of excess higher order bits
- double to float – rounding of digits

1.4.5 Mathematical functions (methods)


Java supports basic mathematical functions through Math class defined in java.lang
package. These functions (methods) should be used as,
Math.method-name( )

Various supported mathematical functions are listed in table 1.11.

5-15
Table 1.11: Important Methods of Math class
Method Use
min(a,b) Returns minimum of a and b
max(a,b) Returns maximum of a and b
sqrt(x) Returns square root of a
pow(x,y) Returns x raised to the power y (xy)
exp(x) Returns e raised to the power x (ex)
round(x) Returns closest integer to x
floor(x) Returns largest whole number less than or equal to x (Rounding down)

ceil(x) Returns smallest whole number greater than or equal to x


(Rounding up)
abs(a) Returns absolute value of x
log(x) Returns natural logarithm of x
sin(x) Returns sine value of angle x in radians
cos(x) Returns cosine value of angle x in radians
tan(x) Returns tangent value of angle x in radians
asin(y) Returns sine inverse of y
acos(y) Returns cosine inverse of y
atan(y) Returns tangent inverse of y

1.5 Decision making and looping


The execution of statements is always done in sequential order. But practically,
there is a need to change the sequence of execution. This can be achieved through various
ways as
- Decision making (Selection Statements/ Branching statements)
- Looping (Iteration Statements)

1.5.1 Decision making (Selection) Statements


Java supports different decision making statements. They are-
- if
- switch-case
- conditional operator

1.5.1.1 if statement
We can use selection statement if in different ways as,
- if
- if-else
- nested if
- if-else-if ladder

Most important branching statement in Java is ‘if’. Its syntax is as follows,


if(test-condition)
{
Statement-block
}

5-16
The Statement-block gets executed if and only if the test-condition gives true
result.
If the selection is to be done between two opposite criteria, we may use ‘if- else’.
Its syntax is as follows,
if(test-condition)
{
Statement-block A
}
else
{
Statement-block B
}
The Statement-block A gets executed if the test-condition gives true result.
Otherwise Statement-block B gets executed.
There might be a need where we have to nest different if-else statements within one
another. Such statements are called nested if. Syntax for the same is given below.
if(test-condition1)
{
if(test-condition2)
{
Statement-block A
}
else
{ Statement-block B
} }
else
{
if(test-condition3)
{
Statement-block C
}
else
{ Statement-block D
}
}

Sometimes we have to take alternate decisions on the previous tes conditions. This
can be achieved with the help of if-else-if ladder. Syntax for the same is given below.
if(test-condition1)
{
Statement-block A
}
else if(test-condition2)

5-17
{
Statement-block B
}
else if(test-condition3)
{
Statement-block C
}
else
{ Statement-block D
}

1.5.1.2 switch statement


We can use switch statement for selection among multiple choices. Syntax for
switch-case is given below.
switch(choice)
{
case value1:
Stament-block A
break;
case value2:
Stament-block B
break;
--
default:
Stament-block Z
}

One may also use nested switch-case. i.e. one switch-case in another.

1.5.1.3 Conditional operator (? : operator)


This operator is already discussed in 1.4.1.6.

1.5.2 Looping Statements


When we want iterative execution of some code, loops are used. Java supports different
looping statements. They are-
- while
- do-while
- for
- for each

1.5.2.1 while
Syntax of while loop is as follows.
Initialization of loop variables
while(test-condition)
{
Code to be repeated
Increment/ Decrement of loop variables
}

5-18
1.5.2.2 do-while
Syntax of do-while loop is as follows.
Initialization of loop variables do
{
Code to be repeated
Increment/ Decrement of loop variables
} while(test-condition);

1.5.2.3 for
Syntax of for loop is as follows.

for(Initialization of loop variables ; test-condition ; Incr/Decr of variables)


{
Code to be repeated
}

1.5.2.4 for each


This is enhanced for loop. This loop helps in handling the array elements efficiently
without using a loop variable. Syntax of for each loop is as follows.

for(type var : array)


{
Code to be repeated.
//Here var will contain each element of array iteratively
}

Example:
int a[ ] = {21,42,63,84,105};
for(int x : a)
{
System.out.println(x);
}
Output:
21
42
63
84
105

1.5.2.5 break statement


We can use break statement if we want to exit prematurely from the loop. When the
break statement is executed, the execution of loop stops immediately and control goes to
the statement after the loop.

Example:
//Code for deciding whether given number is prime or not int
n=23;
int i;

5-19
for(i=2;i<=n/2;i++)
{
if(n%i==0)
{
break;
}
}
if(i>n/2)
{
System.out.println(“Numer is prime”);
}
else
{ System.out.println(“Numer is not prime”);
}

1.5.2.6 continue statement


We can use continue statement if we want to skip remaining part of current
iteration and continue to next iteration of the loop.

Example
//import java.io.*;
//Code for summing five integers (should be non-negative) int
sum=0;
int i,x;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
for(i=0;i<5;i++)
{
x=0;
try
{
System.out.println(“Enter a value: ”); x =
Integer.parseInt(br.readLine( )); if(x<=0)
{
continue;
}
}
catch(IOException e)
{
System.out.println(e);
}
sum=sum+x;
}
System.out.println(“Summation of non-negative numbers is: ”+sum);

5-20
1.5.2.7 return statement
The return statement immediately terminates the method in which it is executed
and returns to the caller of that method. The return statement may or may not return a
value to the caller of the method.

1.5.2.8 Nested loops


We may use a loop within another loop. This concept is called as nested
loops.

1.5.2.9 Labeled loops


We can give a label to a block of statements in Java. Similarly, we can give label to
a loop block also.

Example:
L1: for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{

}
}

The labeled loops help in jumping the control of execution to any loop. In the
following example, control of execution is continuing to outer loop instead of inner loop.

Outer: for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i>j)
{
continue Outer;
}
}
}

5-21

You might also like