0% found this document useful (0 votes)
4 views86 pages

Java Unit 1 Up To Control Statements

The document outlines the syllabus for an introductory unit on Java programming, covering topics such as object-oriented programming principles, differences between C and Java, and the structure of Java programs. It details key concepts like classes, objects, data encapsulation, inheritance, and polymorphism, as well as features of Java such as platform independence and security. Additionally, it discusses the evolution of Java, its applications, and the differences between procedural and object-oriented programming.

Uploaded by

arunaggu22
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views86 pages

Java Unit 1 Up To Control Statements

The document outlines the syllabus for an introductory unit on Java programming, covering topics such as object-oriented programming principles, differences between C and Java, and the structure of Java programs. It details key concepts like classes, objects, data encapsulation, inheritance, and polymorphism, as well as features of Java such as platform independence and security. Additionally, it discusses the evolution of Java, its applications, and the differences between procedural and object-oriented programming.

Uploaded by

arunaggu22
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit -1 Syllabus

⚫ Introduction: Basics of object-oriented programming, comparison of


procedure-oriented and object oriented programming paradigms;
⚫ Difference between C and Java Programming languages;
⚫ Features of Java; Objects and classes in Java, Structure of a Java program;
⚫ Data Types, variables and operators in java; Control structures-
Branching and looping; Methods & Constructors in java;
⚫ Java Development Kit (JDK); Built-in classes in Java; Math, Character,
String, String Buffer and Scanner;
⚫ Wrapper classes;
⚫ Usage of this keyword;
⚫ Arrays in Java.
⚫ The abstract, static and final classes; Casting objects; The instance of
operator; ( we study in inheritance unit)

1
UNIT 1
INTRODUCTION
⚫ Computer is an electronic device that accepts instructions in
a specific language.
⚫ Computer understands machine language only.
⚫ In day today’s life change in technology takes place to fulfil
the end user needs using computer.
⚫ The humans can’t understand machine [Link] is the
reason behind developing the S/W using human
understanding language s such as C, C++, JAVA, and
C#(Latest).
2
⚫ ‘C’ was introduced in 1980s as a structured language by Brain
Kernighan and Dennis Ritchie. As technology grew
complex problems are not efficiently solved using POP.
⚫ To overcome drawback of POP, the OOP’s language were
introduced to reduce complexity.
⚫ OOP facilitate reliability and maintainability
⚫ The OOP, C++ was introduced by Bjarne Stroustrup.
⚫ Java is another pure object oriented language developed by
James Gosling and His colleagues at Sun Micro
Systems.

3
⚫ JAVA was initially called Oak(Oak trees outside Gosling
office)
⚫ JAVA is the most significant language has capability of
moving from one device to another easily.
⚫ JAVA was designed to execute applets( the programs
executed using web browser).
⚫ Gradually JAVA accepted as wide programming language,
replacing C or C++.

4
Java ?
⚫ It is a high level object oriented programming
language. It is designed to be platform
independent due to Java Virtual
Machine(JVM), meaning that java programs can run
on different machines without modification.

⚫ Java Compiler- It converts source code to


intermediate code called as “Byte Code”.

⚫ JVM- It has nature to convert Java and non java source


code’s “byte code” into machine code is referred as a
“VIRTUAL MACHINE”.
5
Object Oriented Paradigm(View-point)

OBJECT Data +

⚫ OOP eliminate flaws(fault) encountered in pop.


⚫ OOP does not allow the “data to flow freely” around the
system.
⚫ It ties data more closely to functions and protects it from
unintentional modification by other functions.
⚫ The data of an object can be accessed only by the methods
associated with that object.
6
Object oriented program features

⚫ Emphasis on data rather than procedure.


⚫ It makes the complete program simpler by dividing it into
a number of objects.
⚫ Objects are used as bridge to have data flow from one
function to another.
⚫ The concept of data hiding enhances the security in
programs.
⚫ It is highly beneficial to solve complex problems.
⚫ Follows bottom up approach in program design.
7
Basic principles of oops
The general concepts which form the heart of JAVA language.

1. Object.
2. Class.
3. Data encapsulation.
4. Data abstraction.
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing

8
1. Object

 Object is unique entity, which contains data and


functions (Characteristics and behaviour) together in an
OOP Language.

 The objects,We experience or use in our day today life is


called “Real World Objects”.
EX-person , pen, car etc.
 Software object- it is created while writing java program.
This object contains Data members and Member
Methods.
EX- Person has Data members(name, age, Salary) and
Methods(Salary(),Tax(), Display() ).

9
2. Class

 The class is a template or blue print for similar type of


objects.

 Each object of class possesses some attributes and common


behaviour as defined within the [Link], Class is referred as
‘Blue print’ or ‘Prototype of an Object’.

 Class is user defined data type, any number of similar type


objects can be created once class is defined is termed known
as ‘Object Factory’.

10
3. Data encapsulation

 The system of wrapping ‘data and functions’ into a single


unit is known as data encapsulation. 
 It is another feature of OOP, which restricts the free flow
of data from one object to another.
 It hides data and cannot be accessed directly outside the
object, instead facilitate the access to data through
‘associated functions’ only.

 EX- Remote- Here, the buttons(members) and it’s


corresponding functions are wrapped in an object i.e
Remote.
11
4. Data abstraction
 It is an act of representing essential features without
knowing the background details or internal working
is called “Data Abstraction”.
 It includes reduced complexity, code reusability, and
improved security.
EX- Camera can be operated by any body using buttons,
even though he/she may not be aware of technology
that how works.

12
5. Inheritance
 It is the process by which object of one class acquire
the properties of objects of another class.
 Inheritance means to link and share some common
properties of one class with the other class from
which it is derived, is also referred as “Reusability”.
 Base class- It gets inherited to another class. It is also
known as ‘existing’ class
 Derived class(Sub Class)- It is inherited from Base
Class.

13
6. Polymorphism
 The word ‘polymorphism’ means ‘many-forms’.
 The term ‘polymorphism’ is defined as the process
of using a function/method for more than one
purposes.
 An operation exhibit different behaviour in different
instances.
Ex1- 2+3=5, Addition
a+b=ab, Concatenation
note : an operator used with different parameters called
Operator Overloading

14
 Ex2- ‘volume’ is a method to calculate different
shapes
I. volume(side)-It is used to find volume of cube.
II. volume(l,b,h)-It is used to find volume of cuboid.

Note : A same ‘function’ or ‘method’ name used with


different parameters called as ‘Function
Overloading’.

15
7. Dynamic binding
 Binding refers to the linking a procedure call to
the code to be executed in response to the call.
 It is also known as ‘Late binding’ or ‘Runtime
Polymorphism’.
 It improves flexibility.
 Supports extensibility to the code without modifying
existing code.

16
8. Message passing
 Objects can communicate with each others by
passing messages same as people passing
message with each other.
STEPS
I. Creating classes that define objects and their
behaviour.
II. Creating objects from class definitions.
III. Establishing communication among objects.

17
Benefits of oop or advantages of
oop
i. The reusability of program code is enhanced.
ii. The software quality and performance are improved.
iii. Modularity is achieved.
iv. Data abstraction makes the software easier to handle
v. Software for complex tasks can easily be developed.
vi. It is easy to partition the work in a project based on
objects.

18
Applications of oop’s

⚫ Real time systems


⚫ Simulation and modelling
⚫ Object oriented database
⚫ Hypertext , hypermedia.
⚫ AI and expert systems.
⚫ neural networks and parallel programming.
⚫ CAD/CAM system.

19
Difference between pop and oop
OOP
Emphasis on functions rather Emphasis on data rather than
than data. the function.
It allows data flow freely The data is restricted to be used
throughout the program. in a specific program area.

It follows top –down approach It follows bottom – up


approach
Code can be repetitive, low Code cannot be repetitive, high
reusability. reusability.
Less modular High modularity
Less secured High secured
Best for small program Best for large and complex
program
20
Chapter 2: java evolution
⚫ Java is another pure object oriented language developed by
James Gosling and His colleagues at Sun Micro
Systems of USA in 1991 .
⚫ JAVA was initially called Oak(Oak trees outside Gosling
office)
⚫ JAVA is the most significant language has capability of
moving from one device to another easily.
⚫ Java S/W was developed for consumer electronic devices
like TVs,Video Cassette Recorder(VCR).
⚫ JAVA was designed to execute applets( the programs
executed using web browser).
⚫ Gradually JAVA accepted as wide programming language,
replacing C or C++
21
Java features
⚫ Simple: Java is easy to learn because of its syntax
similar to c/c++, but with simplified memory
management (no pointers).

⚫ Object oriented: All program code and data reside


within objects and [Link] set of classes arranged
in packages.

⚫ Platform independent: Java programs run on any


system with a Java Virtual Machine(JVM). Java is
referred as portable language.
22
⚫ Secure: Java removes security risks like pointers and
supports ‘Bytecode’Verification to prevent malicious
code.

⚫ Robust : Java is strong and reliable,Which is


automatic garbage collection(removes unused
objects from memory). Facilitate Exception
handling to catch errors.

⚫ Multithreading(Concurrency Support): Java allows


multiple tasks to run simultaneously using threads,
improving efficiency.
23
⚫ High performance: Java is not as fast as c/c++ but achieve
high performance with JIT(Just In Time) Compiler.
Which converts “bytecode” into native machine
code at run time.

⚫ Distributed : Java supports networking and distributed


computing using RMI(Remote Method Invocation)

⚫ Dynamic & Extensible : Java supports dynamic memory


allocation and runtime modifications
Ex : loading classes dynamically
supports third party libraries for extended functionalities.
24
Difference between c and java
C JAVA
It has pre-processors starts with It has packages
#
It is POP It is OOP
Platform Dependent Platform Independent
Compiles to machine code Compiles to byte code
Less secure More secure
no multithreading Supports multithreading
It contains ‘struct’ & ‘union’ It does not contain ‘struct’ &
data types ‘union’ data types

25
Structure of Java compiler and interpreter
Intermediate code
Interpreter
Code

OS/2 UnIX

• Java treats compiler and interpreter differently.

• Compiler converts the source code into binary form called byte
code.

• Interpreter converts binary code to machine code, suitable to specific


platform.
26
Significance of Objects and classes in java
The objects and classes play vital(essential) role in
programming.
1. Object : It is instance of a class that represents a
real world entity.
3 Characteristics Of Object
1. State(Attribute): It represents the data(value) of an
object.
Ex- name, age of a person.
2. Behavior(Methods): It defines functions of an object
that what object can do.
27
Ex-run(), eat().
3. Identity: Each object has a unique identity(memory
address) which is used by JVM to identify each object.

2. Class: A class is blueprint or template for creating


objects(instances).
1. Fields(Instance Variables): Variables that stores the
object’s state.
2. Methods: Functions that define the object’s behavior.
3. Constructors: Special member methods to initialize
objects.
4. Blocks: static and instance blocks for initialization .

28
5. Access Modifiers: Control the visibility ( public,
private, etc).
STRUCTURE OF JAVA PROGRAM

Package Statement
Import statements
Interface statements
Class definitions
main method class
{
main method definition
29 }
 Documentation Section: It refers to the comments at
the beginning of a java program. This section provides
information about author, program, purpose.
Supports 3 Types of comments and which are not executed
by JVM.
1. Single-Line Comment(//): Used for short descriptions.

2. Multi-Line Comment(/*...*/): Used for detailed


explanation.

3. Documentation Comment(/**...*/) : it is document


includes @author, @version, and @param.

30
 Package Statement: it is optionally user defined and placed
after documentation [Link] use ‘keyword’ package to
declare the package name.
Ex: import [Link];// import single class
Ex: import [Link].*;//Import the whole package

 Import Statements: it is defined after ‘package’ declaration


and before ‘class ’ declaration. ‘import ‘ is a keyword used to
access classes and interfaces from other packages.
Ex: import [Link]; //imports scanner class only.
Ex: import [Link].*;// imports all the class of the [Link]
package

31
 Interface Statements: It is optional section and created by
using keyword i.e ‘interface’. It contains only constants and
method.
Ex: interface car
{
void start();
void stop();
}
 Class Definition: We cannot create java program except
‘class’. Every java program must have minimum one class
using the keyword class, which contains ‘main()’ method.
Ex: class Student
{
}
32
 main method():
⚫ It is essential for all java programs. Because actual execution of
programs takes place from main().
⚫ It is defined inside the [Link] objects are created and
methods are called in main().
Sample Java Program
public class Simple
{
public static void main(String args[])
{
void display()//method
{
[Link](“Welcome”)
}
}
}

33
Rules to ‘class’ Name.
⚫ Class name must start with ‘UPPERCASE’ . Ex: class Simple
but not class simple.

⚫ However JVM accepts class name starting with ‘lowercase’,


But not recommended as java follows naming convention.

⚫ Do not use java keywords(reserved) such as public, if,


break etc.

⚫ Use meaningful names such as ‘Employee’ instead ‘Emp’.

34
Data types, variables and operators in java
 Data types define the kind of values a variable can
[Link] every variable must have a declared type.
Types
1. Primitive data type :These are basic building blocks in
java, directly operated upon machine level instructions.
Ex: int, float, long, char, boolean , byte, double etc are of 8
types.
2. non- Primitive data type: these are complex data types
derived from primitive data type.
Ex: String, Array, Classes, Interfaces, Objects.
35
DATA TYPES,VARIABLES AND OPERATORS IN JAVA
Data type

Primitive non-Primitive

Boolean Numeric
string array etc
boolean Character Integral

char Integer Floating

byte short int long float double

36
1. Boolean Data Type:
 It is primitive data type used to store only two values either
‘True’ or ‘False’.
 It stores one bit of information.

2. Byte data type:


 It is primitive data type used to store small integer values.
 Default value is 0
 Its is of 8 bits size representation where ranges from -128 to
127

37
3. Short data type:
 It is primitive data type used to store small integer values.
 Default value is 0
 Its is of 16 bits size representation where value ranges from
-32768 to 32767.
 Ex : short s=1000;

4. Int data type:


 It is most commonly used data type to store whole numbers.
 Default value is 0
 Its is of 32 bits size representation where value ranges from
-2,147,483,648 to 2,147,483,647
Ex : int a=150;

38
5. Long data type:
 It is primitive data type to store larger integer values.
 Default value is 0L(used for long Literals)
 Its is of 64 bits size representation, where value ranges from -
263 TO 263-1
 Used to store factorial of large number.
Ex long a=1000L;

6. Float data type:


 It is primitive data type to store decimal numbers with
single precision.
 Default value is 0.0f
 Its is of 32 bits size representation, where value ranges from
± 1.4 * 10-45 to ± 3.4 * 1038
Ex: float pi=3.142;

39
7. Double data type
 It is primitive data type to store decimal numbers with
higher precision than float.
 Default value is 0.0d.
 Its is of 64 bits size representation, where value ranges from ±
4.9 * 10-324 to ± 1.8 * 10308
Ex: double num1=10.25;
8. Char data type
 It is primitive data type to store single character.
 Default value is ‘\u0000’(null character).
 Char is 1 byte but java uses 2 byte size representation, where
value ranges from \u0000 to \uffff(65,535)
Ex char letter=‘A’;
Ex char digit=‘7’;
40
JAVA VARIABLES & OPERATORS
 A variable is a named memory location, which is used
to store data values such as ‘name’,‘type’, and ‘value’.
 It is a reserved space in memory.
 It acts as a container for values that can change during the
programs.

Syntax :
<data type><space> <variable name>
Ex : int a;// here ‘a’ is variable.

41
TYPES OF VARIABLES
1. Local Variable
2. Instance Variable
3. Static Variable
Local Variable
 A variable declared inside the body of the method,
constructor, or block is called local variable.
 Must be initialized before use.
 Variable ‘Scope’ is limited to the method/block
and accessible only within that method.
 not accessible outside the method/function.

42
Local Variable Example
class Local
{
public static void main(String[] args)
{
int num=10;//Local variable
[Link](“Number :” +num)
}
}
note : ‘String[] args’ Or ‘String args[]’ both type arguments
are valid in main () function.

43
Instance Variable
 These variables are declared within class and
outside of any method is said to be instance
variable.
 Instance variables are also called as data members.
 These variables can easily be accessed in all the
members of the class.
 These are allocated as individual copy of each
object(instance) of the class.

44
Instance Variable Example
class Person
{
String name;//instance variable
int age; //instance variable
public void display()
{
[Link](“Name:” + name +”Age:” +age);
}
}

45
Static Variable
 A variable is declared as ‘static’ within the
class and also known as class Variable.

 it is ‘static variable’ and a separate


common copy for all objects.

 It is independent variable and does not


belong to any particular object.

46
Static Variable Example
class Sample
{
static String college=“Akash College”;//Static variable
void display()
{
[Link](“college” +college);
}
}
public class StaticExample
{
public static void main(String[] args)
{
Sample ob1=new Sample();// ob1 object created using ‘new’ opeartor
Sample ob2=new Sample();
[Link]();
[Link]();
}
47 }
STEPS TO EXECUTE
C:\Users\Admin>cd C:\Users\Admin\Desktop\BCA CLASSES

C:\Users\Admin\Desktop\BCA CLASSES>javac [Link]

C:\Users\Admin\Desktop\BCA CLASSES>java StaticExample

college:Akash College
college:Akash College

48
Rules For Naming The Variable
 Start with a letter, underscore(_), or $ (but not number).
 Cannot be a java keyword i.e int, class, float etc.
 Case sensitive, where age and Age are different.
 Variable name should be meaningful, which easily depicts
its purpose.
 Ex: int age; and int $price; are valid variables.
 Ex: int 1number; and int double; are invalid
variables

49
Operators In Java
An Operator is a symbol that is used to perform
operations.
Types
1. Arithmetic Operator
a. Unary operator.
b. Binary operator.
c. Ternary operator.
2. Assignment operator
3. Relational operator
4. Logical operator
5. Bitwise operator
6. Shift operator

50
1. Arithmetic Operator
⚫ Used to perform basic mathematical operations.
⚫ Examples: + (addition), - (subtraction), * (multiplication), /
(division), % (modulus).
⚫ The values which are used in operations known as operands.
Ex: a+b, where a and b are operands.
Arithmetic Operations: a=10,b=5
⚫ Addition: a+b=15
⚫ Subtraction: a-b=5
⚫ Division: a/b=2
⚫ Multiplication: a*b= 50

51
a. Unary operator
 Operate on a single operand to perform various operations.
 Ex: + , - , ++, - -, ! (logical nOT).
1. ‘+’ : It is unary operator used before the operand, which
results in the same value of the variable.
Ex: if a=5, then +a will result in 5.
if a= -10 , then +a will result as +(-10)= -10.

2. ‘-’ : It is unary operator used before the operand, unary


minus (-) operator reverses the sign of an operand.
Ex: if a=5, then - a will result in -5.
if a= -10 , then - a will result as -(-10)= 10.
if a=0, then –a will result in 0 (It is sign less value)

52
3. ‘++’ : It is unary increment operator increases the
value of an operand by one(1).
TWO TYPES
Prefix
 Prefix:When increment operator is used before
the operand is called prefix operator.
 Prefix operator means the value of variable changes
before the action takes place.
 Ex: M=4;
M=++M;
M will Result as : 5.

53
Postfix
 Postfix:When increment operator is used after an
operand is called postfix operator.
 Postfix operator means the value of variable changes
after the action takes place.
 Ex: M=4;
M=M++;
M will Result as : 4.
note: an incremented value of M will be affected after an
action and included in next appearing variable M.
Ex: M=4;
M=M++ +M; // M=4++ +5; // M will Result as : 9

54
4. ‘- -’ : It is unary decrement operator decreases the value of an
operand by one(1).
TWOTYPES
Prefix
 Prefix:When decrement operator is used before
the operand is called prefix operator.
 Prefix operator means the value of variable changes
before the action takes place.
 Ex: M=4;
M=- -M;
M will Result as : 3

55
Postfix
 Postfix:When decrement operator is used after an
operand is called postfix operator.
 Postfix operator means the value of variable changes
after the action takes place.
 Ex: M=4;
M=M- -;
M will Result as : 4.
note: an decremented value of M will be affected after an
action and included in next appearing variable M.
Ex: M=4;
M=M- - +M; // M=4- - +3; // M will Result as : 7

56
b. Binary Operators
 An Operator, operates on Two Operands to
perform various operations.
 Ex: + , - , *, / and %.
⚫ Addition: a+b.
⚫ Subtraction: a-b.
⚫ Division: a/b.
⚫ Multiplication: a*b.
⚫ Modules/Remainder: a%b.

57
c. Ternary Operator(Conditional Assignment):
 This operators deals with three operands.
 Syntax:
variable=(test expression)? expression1:expression2
Ex: a=5; b=3;
Max=(a>b)? a : b
Here, the value 5 is stored in Max, as a>b is true.
Min=(b>a)? a : b
Here, the value 3 is stored in Main, as b>a is false.
Note1: if (condition), becomes true Means ‘a’ is stored else
‘b’ is stored.
Note2:Ternary Operator is equivalent to the ‘if-else’
construct in java language.

58
2. Assignment Operator
⚫ Used to assign values to variables.
⚫ Examples: = (simple assignment),
⚫ Short Hand Assignment operators are, +=
(addition assignment), -= (subtraction assignment),
*= (multiplication assignment), /= (division
assignment), %= (modulus assignment)
⚫ It assigns the value on its right to the operand on its
left.
⚫ Ex: a=b; a+=b; a -=b etc
59
3. Relational Operator
 These operators compares the values of two operands
and determine the relationship between them.
 It always returns a boolean type value either True or
False.
 Symbols are : < , >, <=, >=, = =, ! =.
 Examples: a>b; a<b; a>=b; a<=b;
a==b; a!=b;
If a=3; b=5;
 If(a>b), returns false.
 If(a<=b) , if any one condition is satisfied, which
returns true as ‘less than ’is valid condition.

60
4. Logical operator
 These operations are used to perform logical
operations on ‘boolean’ values(true or false).
 These operators yield true or false depending
upon the outcome of different conditions.
 Logical operators are : AnD(&&), OR(||),
NOT(!).
 a=2, b=3;
 (a>b) && (b<a) => (F)&&(T) , results as False.
 (a>b) || (b<a) => (F)||(T) , results as True.
 !(5>3) => !(True) , results as False

61
5. Bitwise Operator
 These operators performed on bits representation.
 Bitwise AND (&)operation: Returns 1 only if both bits
are 1, otherwise returns 0.
Ex: 0101 & 0011, result is 0001.
 Bitwise OR(|) operation : Returns 1 if any one bit is 1,
otherwise returns 0.
Ex: 0101 | 0011, result 0111.
 Bitwise NOT (~)operation: Inverts all bits i.e 1->0, 0->
1.
Ex: 0011, result is 1100.
62
6. Shift Operator
 Perform operations at the bit level.
 Examples: Left Shift(<<), Right Shift(>>).
 Left Shift: It shifts bits to the left and adds 0’s to on
the right.
Ex: 0101(5) => 1010=10.
 Right Shift: It shifts bits to the right and adds 0’s to
on the left.
Ex: 0101(5) => 0010=2.

63
CONTROL STRUCTURE
⚫ Control structures in java determines the flow of control in
condition based operations.
⚫ Executing statements sequentially unless end of the program
is reached is called flow of control.
CATEGORIES
a. Normal flow of control.
b. Decision making statements.
⚫ Simple if statement
⚫ if- else statement
⚫ if- else-if ladder
⚫ Nested if statement
⚫ Switch case statement(Multiple branching of control)
64
c. Loop Statements
⚫ for loop.
⚫ While loop.
⚫ do – while loop.
d. Jump statement
⚫ break statement
⚫ continue statement

65
NORMAL FLOW OF CONTROL:
⚫ It is the control keeps on executing each and every statement
of the program on the basis of top down approach.
⚫ Ex:
public class Expressions
{
public static void main(String args[] )
{
int a=2, b=3, ans1, ans2;
ans1=a*a+2*a*b+b*b;// (a+b) the whole square
ans2=a*a-2*a*b+b*b;// (a-b) the whole square
[Link](“The first answer =” +ans1);
[Link](“The second answer =” +ans2);
}
}
66
DECISION MAKING STATEMENTS
⚫ Block of statements executed when the given
condition holds true.

⚫ In case the given condition is false, the execution


of the current block should be ignored and the
control should move to execute another block.

67
⚫ If statement
Syntax:
If(condition)
{
statement 1;
}

⚫ If-else
Syntax:
If(condition)
{
statement 1;
}
else
{
statement 2;
}
68
⚫ if-elseif-else ladder
Syntax:
if(condition)
{
statement 1;
}
else if(condition)
{
statement 2;
}
else
{
statement 3;
69 }
⚫ Nested if-statement
Syntax:
if(condition 1)
{
if(condition 1)
{
statement 1;
}
else
{
statement 2;
}
}
70
⚫ Switch case
Syntax:
Switch(expression)
{
case 1:
statement 1;
break;
case 2:
statement 2;
break;
case n:
statement n;
break;
default: statement;
}
71
Loop Statements: A construct is a Set of statements which
are repeatedly executed till the condition is satisfied such a
construct is said to be a loop.

LOOP

Loop Loop

for

fixed iterative loop


unfixed iterative loop
72
Fixed iterative loop is a construct used
to repeat the execution of block of
statements for a fixed number of times.

Unfixed iterative loop is a construct in


which user may not be aware of the number
of iterations, uncertain repetitive structure
referred as Unfixed iteration or Unknown
Iteration
73
1. For loop:
⚫ This loop is used when user is aware of iterations.
⚫ Syntax:
for(initial value; test condition ; update)
{
statements;
}
⚫ It executes block of statements by updating the control
variable unless the given condition is false.
⚫ Example:
for(i=1; i<=5; i++)// 5 time fixed iterations
{
[Link](i);
}
74
Cond
initialization Check Statement

If

Terminate

75
2. While loop:
⚫ This loop is used when user is not aware of
iterations.
⚫ Decision is made at the beginning point only.
⚫ Syntax:
While(Test Condition )
{
statements;
}
⚫ It executes block of statements until the condition is
true, if false it will terminate the loop.
⚫ Number of iterations takes place during the process.

76
Example: While Loop
public class SampleWhile {
public static void main(String args[])
{
int r=10,t=1;
double p=100.0, si=0.0;
while(p<=150.0)//executed until ‘p<=150’ and unknown iterations
}
si=(p*r*t)/100.0;
p=p+si;
[Link](p);
}
}
77
}
while loop output
C:\Users\Admin\Desktop\JavaPrograms>java SampleWhile
110.0
121.0
133.1
146.41
161.051

Note : Above 5 iterations are not defined in ‘while


loop’ instead executed at run time

78
3. Do-While loop:
⚫ This loop is used when user is not aware of iterations.
⚫ Decision is made at the end point only(Exit Control)
⚫ Syntax:
do
{
statements;
} While(Test Condition );
⚫ It executes block of statements until the condition is
true, if ‘false’ it will terminate the while loop with
semicolon(;) at end.
⚫ Minimum ‘once executed’ before Number of iterations
takes place during the process.

79
Example: do-while ;
public class SampleDoWhile {
public static void main(String args[]) {
int r=10,t=1;
double p=100.0,
si=0.0; do
}
si=(p*r*t)/100.0;
p=p+si;
[Link](p);
} while(p<=150.0);

}
}

80
Do-while output
C:\Users\Admin\Desktop\JavaPrograms>javac
[Link]
C:\Users\Admin\Desktop\JavaPrograms>java SampleDoWhile
110.0
121.0
133.1
146.41
161.051

Note : Above 1st iteration executed first and then by


checking the condition, 4 iterations are executed at run
time
81
JUMP STATEMENTS
⚫ These are statements used to transfer the control
to another part of the program.
⚫ Leaving some of the statements unexecuted.
break:
⚫ It is used in looping construct for unnatural
termination of the loop.
⚫ When we use ‘break’, it forces the control to skip
the remaining iterations of the loop and exit the
loop block, even though loop is not yet over.

82
Example: break
public class SampleBreak
{
public static void main(String args[])
{
int i;
for(i=1; i<=10;
i++) {
if(i==5)
break;
[Link](i);
}
}
}
Output for break
C:\Users\Admin\Desktop\JavaPrograms>javac
[Link]
C:\Users\Admin\Desktop\JavaPrograms>java SampleBreak
1
2
3
4
Note: ‘i<=10’, i values to be printed from 1to 10, but
where the ‘i==5’ condition ‘break’ the other
iterations from printing. After using ‘break’ , no
statement is executed.

84
continue:
⚫ When we use ‘continue’, the control will skip the current
iteration of the loop and will resume back for the next
iteration.
Example: continue
public class SampleContinue
{
public static void main(String args[])
{
int i;
for(i=1; i<=5; i++)
{
if(i==3)
continue; // skips ‘3’ and continue to print from 4
[Link](i);
}
}
}
85
Output for‘continue’
C:\Users\Admin\Desktop\JavaPro
grams>javac
[Link]
C:\Users\Admin\Desktop\Java
Programs>java
SampleContinue
1
2
4
5
Note : Above output is generated
from 1 to 5, where by skipping
number ‘3’ .

86

You might also like