0% found this document useful (0 votes)
13 views25 pages

M-1 Notes

Module I provides an overview of Java, focusing on object-oriented programming principles, data types, variables, arrays, operators, and control statements. It explains key concepts such as encapsulation, inheritance, and polymorphism, along with Java's lexical issues and class libraries. The module also includes examples of variable declaration, type conversion, and the structure of a simple Java program.

Uploaded by

xoxo1234xoxoa
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)
13 views25 pages

M-1 Notes

Module I provides an overview of Java, focusing on object-oriented programming principles, data types, variables, arrays, operators, and control statements. It explains key concepts such as encapsulation, inheritance, and polymorphism, along with Java's lexical issues and class libraries. The module also includes examples of variable declaration, type conversion, and the structure of a simple Java program.

Uploaded by

xoxo1234xoxoa
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
You are on page 1/ 25

MODULE I

MODULE I
Contents
An Overview of Java:
 Object-Oriented Programming (Two Paradigms, Abstraction, The Three OOP
Principles),Using Blocks of Code,
 Lexical Issues (Whitespace, Identifiers, Literals, Comments, Separators, The
Java Keywords
Data Types, Variables, and Arrays:
 The Primitive Types (Integers, Floating-Point Types, Characters, Booleans),
Variables.
 Type Conversion and Casting.
 Automatic Type Promotion in Expressions.
 Arrays, Introducing Type Inference with Local Variables.
Operators:

 Arithmetic Operators, Relational Operators, Boolean Logical Operators, The


Assignment Operator, The ? Operator, Operator Precedence, Using
Parentheses.

Control Statements:

 Java’s Selection Statements (if, The Traditional switch).


 Iteration Statements (while, do-while, for, The For-Each Version of the for
Loop, Local Variable Type Inference in a for Loop, Nested Loops)
 Jump Statements (Using break, Using continue, return).

Object-Oriented Programming - OOP


 Object oriented programming is the core of Java programming.
 Java is a general purpose, object- oriented programming language developed by Sun
Microsystems. It was invented by James Gosling and his team and was initially called as
Oak.
 The most important feature that made Java very popular was the Platform -
Independent‖ approach.
 It was the first programming language that did not tie up with any particular operating
system( or hardware) rather Java programs can be executed anywhere and on any system.

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

1
MODULE I

Two Paradigms:

 Every program contains 2 components code and data.


 Two approaches are there to solve the problem and in program writing: Procedure
oriented and object-oriented. Procedure Oriented:
 Procedure-oriented programs are written based on ―what happening around them,
where the code acts on data. Ex: C etc
 Problems increase in procedure-oriented as the program grows larger and more
complex. Object Oriented:
 Object-oriented programs are written based on ―Who is being affected, which
manages the increasing complexity.
 It organises program around data and well defined interfaces of that data.
 Characterised as data controlling access to code. Ex: C++, JAVA ….

The Three OOPs Principles


The three important features of OOP are:
 Encapsulation .
 Inheritance.
 Polymorphism.

Encapsulation:
 Encapsulation is the mechanism that binds together code and data it manipulates,
and keeps both safe from outside interference and misuse.
 In Java the basis of encapsulation is the class. A class defines the state and
behaviour(data & code) that will be shared by set of objects.
 Each object contains the structure and behaviour defined by the class. The data
defined by the class are called instance variables(member variables), the code that
operates on that data are called methods(member functions).

Inheritance:
 Inheritance is the process by which one object acquires the properties of another
object. This is important as it supports the concept of hierarchical classification.
 By the use of inheritance, a class has to define only those qualities that make it
unique. The general qualities can be derived from the parent class or base class.
 Ex: A child inheriting properties from parents.

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

2
MODULE I

Polymorphism
 Polymorphism (meaning many forms) is a feature that allows one interface to be
used for a general class of actions. The specific action determined by the exact nature
of the situation. This concept is often expressed as ― one interface, multiple
methods‖.
 Ex: The operator + can be used for addition of 2 numbers and also concatenation of
2 strings. System.out.println(2+4); output is 6 as answer.
System.out.println(“Hello ” + “Gautham”); output is Hello Gautham

Objects and Class in JAVA


Objects
 An object can be any real world entity.
 Ex: an animal, bank, human, box, fan etc
 An object is a software bundle of related state and behaviour.
 An object is an instance of class

Class
A class is a blueprint or prototype from which objects are created.

 Its just a template for an object, which describes an object.

 Ex: a class describes how an animal looks like.

 A class is a user defined data type.

Abstraction:

 Data abstraction refers to providing only essential information to the outside world
and hiding their background details i.e., to represent the needed information in program
without presenting the details.

 Ex: a database system hides certain details of how data is stored and created and
maintained

Polymorphism, Encapsulation and Inheritance work Together


 The 3 principles of OOP Polymorphism, Encapsulation and Inheritance combines
together to make the programming robust and scalable.

 Encapsulation allows to migrate the implementation without disturbing the code


that depends on class.

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

3
MODULE I

 Polymorphism allows to create clean, sensible, readable, resilient code.

.  Inheritance, mainly deals with the code reusability.

A First Simple Program


public class Example

public static void main(String args[])

System.out.println(“Welcome to Programming in Java”);

Out Put : Welcome to Programming in Java

Description:

 Class declaration: class Example declares a class, which is an object- oriented


construct.
 Opening braces: Every class definition of Java starts with opening braces and ends
with matching one.
 The main line: the line public static void main(String args[]) ― defines a method
name main. Java application program must include this main. This is the starting point
of the interpreter from where it starts executing. A Java program can have any number
of classes but only one class will have the main method.
 Public: This key word is an access specifier that declares the main method as
unprotected and therefore makes it accessible to all other classes.
 Static: Static keyword defines the method as one that belongs to the entire class and
not for a particular object of the class. The main must always be declared as static.
 Void: the type modifier void specifies that the method main does not return any value.
 The println: It is a method of the object out of the system class. It is similar to the
printf in c. This always appends a newline character to the end of the string i.e., any
subsequent output will start on a new line.

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

4
MODULE I

Lexical Issues in JAVA


It is very important to describe the atomic elements of JAVA. Java programs are a
collection of whitespace, identifiers, Literals, comments, operators, separators, and keywords.

 Whitespace - In Java, whitespace includes a space, tab, newline, or form


feed.
 Identifiers - Identifiers in Java are a sequence of characters to identify
something in a program. They are names given to a class, variable, package,
method, or interface and allow the programmer to refer to the specific item
from any place in the program.
Example: int a=10 or Class Example

 Literals - are a synthetic representation of boolean, character, numeric, or


string data. The five main Literal types are:

Integer Literal
Float/Double Literal
Character Literal
Boolean Literal
String Literal
 Comments - Comments can be used to explain Java code, and to make it more
readable. It can also be used to prevent execution when testing alternative
code.
Single-line comments - start with two forward slashes (//). Any text
between // and the end of the line is ignored by Java (will not be
executed).

Java Multi-line Comments- Multi-line comments start with /* and


end with */. Any text between /* and */ will be ignored by Java.

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

5
MODULE I

 Separators - characters that separate different parts of a code statement or


expression. They play an important role in defining the language's syntax and
help to organize and structure code in a readable and understandable way. The
separators are shown in the following table.

Encloses arguments in methods definitions and calling; adjusts


() precedence in arithmetic expressions; surrounds cast kinds and
delimits test expressions in flow control statements.

Describe blocks of code and automatically initializes arrays


{}
Declares array kinds and dereferences array values
[]
terminates statements
;
separates successive identifiers within variable declarations;
, chains statements within the test, expression of a for loop

Selects a field or methods from an object; separates package


.
names from sub-package and class names
Begins an annotation
@
Separators and their Purpose

 Keywords - Java keywords are also known as reserved words. Keywords are
particular words that act as a key to a code. These are predefined words by
Java so they cannot be used as a variable or object name or class name. There
are 51 Java keywords. We have listed a few for reference.
Abstract assert Boolean break byte case
Catch char class Enum continue default
Do double else for exports extends
Final finally instance of int goto if
implements import new open interface long
Module static provides public opens package
Private throw throws super requires return
Short uses void to switch transitive
This try native volatile while with

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

6
MODULE I

JAVA Class Libraries - The Java Class Library (JCL) is a set of dynamically loadable
libraries that Java Virtual Machine (JVM) languages can call at run time. Because the Java
Platform is not dependent on a specific operating system, applications cannot rely on any of
the platform-native libraries.

Data Types, Variables, and Arrays


Data Types - Data types are divided into two groups:

 Primitive data types - include byte, short, int, long, float, double, Boolean, and char
 Non-primitive data types - such as String, Arrays, and Classes (you will learn more
about these in a later chapter)

Integer Data Types

Primitive Memory Allocation Range


data types
Byte 1 byte(1 byte – 8 -128 to 127
bits)
Short 2 bytes(16 bits) -32768 to 32767
Long 8 bytes(64 bits) -9223372036854775808 to
9223372036854775807

Floating Point Data Types

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

7
MODULE I

Primitive Memory Allocation Range


data types
Float 4 bytes(32 bits) 0.14012985e-44 to
0.34028235e39
Double 8 bytes(64 bits) .11125369292536009e-307
to .17976931348623155e+309

Character Data Type – char - Memory Allocation - 2 bytes- 16 bits

Boolean Data Type - Memory Allocation - 1 byte – 8 bits.

Declaring a Variable - The basic form of variable declaration is

data type identifier = value;

Example: int number=30; String mystring=”Life is Beautifull”;

Dynamic Initialization – Java allows variables to be initialized dynamically, using any


expression valid at the time the variable is declared. In this method, the variable is assigned a
value at the run-time. The value is either assigned by the function in the program or by the
user at the time of running the program. The value of these variables can be altered every
time the program runs.

public class
public class DynamicInitialization
DynamicInitialization {{

public static
public static void
void main(String[]
main(String[] args)
args) {{
double a=3;
double a=3;
double b=4;
double b=4;
double cc == Math.sqrt(a*a
double Math.sqrt(a*a ++ b*b);
b*b);
// The above variable c will
// The above variable c will be be initialized
initialized during
during the
the run timerun time

}
}
}
}
Types of Variables and its Scope

1. Instance Variables - A variable that is declared inside a class, but is declared outside
any methods and blocks is known as an instance variable.

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

8
MODULE I

Scope: Throughout the class except in the static methods.


Lifetime: Until the object of the class stays in the memory.
2. Class Variables - A variable that is declared inside a class, outside all the blocks, and
is declared as static is known as a class variable.
Scope: Throughout the class.
Lifetime: Until the end of the program.
3. Local Variables- All variables which are not instance or class variables are known
as local variables.
Scope: Within the block, it is declared.
Lifetime: Until control leaves the block in which it is declared.

Demonstration of three variables

public class Scope_and_lifetime


{
int num1, num2; //Instance Variables
static int result; //Class Variable
int add(int a, int b)
{ //Local Variables
num1 = a;
num2 = b;
return a+b;
}
public static void main(String args[])
{
scope_and_lifetime ob = new scope_and_lifetime();
result = ob.add(10, 20);
System.out.println("Sum = " + result);
}
}

Type Conversion & Casting - Type casting is when you assign a value of one primitive data
type to another type. In Java, there are two types of casting,

 Widening Casting (automatically) - converting a smaller type to a larger type size.


Widening casting is done automatically when passing a smaller size type to a larger
size type:
byte -> short -> char -> int -> long -> float -> double
 Narrowing Casting (manually) - converting a larger type to a smaller size type.
Narrowing casting must be done manually by placing the type in parentheses in front
of the value:
double -> float -> long -> int -> char -> short -> byte

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

9
MODULE I

public class TypeCasting {

public static void main(String[] args) {


//Below code Demostrate automatic Type conversion
byte a=40;
byte b = 50;
b=a ;
System.out.println("The value of b is " + b);
/*Below code Demostrate automatic Type conversion
Here destination type is larger than the
source type. Here Widening Happened*/
byte c=40;
byte d=50;
float e=(c*d)/3;
System.out.println("THe value of e is " + e);
//Below Code Demontrating Casting incompatible Types
int aa=20;
byte bb=35;
//bb=aa;
/*This will throw error bb=aa; since in smaller
data types, we are saving a bigger Data Type. So we have
to Narrow the Type*/
bb=(byte)aa;
System.out.println("The value of bb " + bb);
//Another Example of Narrowing
byte x;
int y=400;
double z= 600.75d;
x=(byte)z;
//Another Example
byte aaaa=20;
//aaaa= aaaa *2;
/*The above code throws error,
because automatically it will take as
integer*/
aaaa= (byte)(aaaa *2);
System.out.println("The value of aaaa " + aaaa);
}
}

Arrays : An array is a group of like-typed variables that are referred to by a common name.
Arrays of any type can be created and many have one or more dimensions. A specific

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

10
MODULE I

element of the array can be accessed by its index. Arrays offer a convenient means of
grouping related information.

Demonstration of One-Dimensional Array

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars[0]);

// Outputs Volvo

/* Here created an array of strings with array name


cars. cars[0] is giving us the 0th index element
from the array. We can not see the array elements
as it is . For that we have to run it through a
loop

Alternative Array Declaration Syntax

Operators

Java provides a rich operator environment. Most of the operators can be divided into 4
groups: Arithmetic, bitwise, relational, and logical.

Arithmetic Operators – Arithmetic operators are used in mathematical expressions


used in Algebra. The following table lists the Arithmetic Operators.

Operator Result
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
+= Assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

11
MODULE I

Demonstration of Arithmetic Operations

public class BasicArithmeticOperations {


public static void main(String[] args) {
int x=40;
System.out.println("Modulus value is " + (x%10));
//The above code displays the remainder when 40 is divided by
10
x+=4;
System.out.println("The value of x is " + x);
//4 is added to current x value and became 44
int a= 10;
a++;
System.out.println("The value of a is " + a);
//1 is added to the current value of a 10
int b=20;
--b;
System.out.println("The value of b is " + b);
//1 is subtracted from the current value of b 20, b
is now 19
int c=5;
c*=4;
System.out.println("The value of c is " + c);
//Output is 20
int d=30;
d/=5;
System.out.println("The value of d is " + d);
//Output is 20
}
}

Bitwise Operators – Java defines several bitwise operators that can be applied to the integer
types: long, int, short, char, and byte. They are summarized in the below table.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

12
MODULE I

Relational Operators – Java defines several bitwise operators that can be applied to the
integer types: long, int, short, char, and byte. They are summarized in the below table.

Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to

Assignment Operators –We have been using the assignment operator from the beginning. It
is the time to have a formal look at it. The assignment operator is the single equal sign ‘=’ .

Example int a=10;

The? Operators - Java includes a special ternary(three-way) operator that can replace
certain types of if – then – else statements. This operator is ‘?’.The general form of this is
Expression 1 ? Expression 2 ? Expression 3

Demonstration of ? operator
public class DemonstrationOfQuestionMarkOperator {

public static void main(String[] args) {


int i,k;
i=10;
k=i<0 ? -i: i; //Take the absolute value of i
System.out.println("The absolute value of " + i + "is" + k);
i=-10;
k=i<0 ? -i: i; //Take the absolute value of i
System.out.println("The absolute value of " + i + "is" + k);
}

}
Output: The absolute value of 10is10
The absolute value of -10is10

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

13
MODULE I

Control Statements

 Java’s program control statements can be put into the following categories: selection,
iteration, and jump.

 Selection statements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable.

 Iteration statements enable program execution to repeat one or more statements (that is,
iteration statements form loops).

 Jump statements allow your program to execute in a nonlinear fashion.

Java’s Selection Statements


 Java supports two selection statements: if and switch.

The if statement
 The if statement executes a block of code only if the specified expression is true.

 If the value is false, then the if block is skipped and execution continues with the rest of
the program.

 You can either have a single statement or a block of code within an if statement.

 Note that the conditional expression must be a Boolean expression.


Syntax:

if (<conditional Expression >)

<statements>

Demonstration of if

public class DemonstrationOfIF {

public static void main(String[] args) {


int a=10;
int b=20;
if(a>b) {
am. System.out.println("a is bigger than b");
}
if(a<b) {
System.out.println("a is smaller than b");
}
Department of Artificial Intelligence & Data Science , DBIT Bangalore.
}

14
MODULE I

The if else statement


 The if statement is Java’s conditional branch statement. It can be used to route program
execution through two different paths.
 Here is the general form of the if statement:
 Here, each statement may be a single statement or a compound statement enclosed in curly
braces (that is, a block).
 The condition is any expression that returns a Boolean value. The else clause is optional.
 The if works like this: If the condition is true, then statement1 is executed. Otherwise,
statement 2 (if it exists) is executed.

Syntax:
if (condition){
statement1; }
else {
statement2;}

Demonstration of if – else

public class IfElse{

public static void main(String[] args) {


//DEMONSTRATION OF IF - TO CHECK A PERSON IS ELIGIBLE FOR
VOTING
int age =16;
if (age>=18)
{System.out.println(" Eligible for voting");
}
else
{System.out.println(" Not Eligible for voting");
}
}
}

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

15
MODULE I

Nested ifs
 A nested if is an if statement that is the target of another if or else.
 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.

Demonstration of Nested if
public class NestedIF {

public static void main(String[] args) {


int a=10;
int b=19;
int c=30; int d=75;
int j=55; int k=105;
int i =10;
if(i==10) {
if(j<20) {
a=b;
}
if(k>100) {
c=d;
}
else {
a=d;
}
System.out.println("The value of a is "+ a);
System.out.println("The value of c is "+ c);
}
}
}

Output: The value of a is 10


The value of c is 75

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

16
MODULE I

If- else – if Ladder


 A common programming construct that is based upon a sequence of nested ifs
is the if-else-if ladder.
 The if statements are executed from the top down.
 s soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed.
 If none of the conditions is true, then the final else statement will be executed.
Syntax: if(condition)
{ Statements; }
else if(condition)
{ Statements; }
else if(condition)
{ Statements; }
……..
else
{ Statements; }
Demonstration of if – else - if Ladder
Demonstration Of if – else - if Ladder - to check the tax payer in which slab

public class Elseif_ladder {

public static void main(String[] args) {

long salary=7400000000l;
if (salary >=70000)
{
System.out.println("Tax Third Slab");
}
else if(salary >=60000)
{
System.out.println("Tax Second Slab");
}
else
{
System.out.println("Tax no Slab");
}
The switch statement
}

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

17
MODULE I

 The switch case statement is a multi-way branch with several choices. A switch is
easier to implement than a series of if/else statements. Structure of Switch:
 The switch statement begins with a keyword, followed by an expression that equates
to a no long integral value.
 Following the controlling expression is a code block that contains zero or more
labelled cases.
 Each label must equate to an integer constant and each must be unique.

Working of switch case:


 When the switch statement executes, it compares the value of the controlling
expression to the values of each case label.
 The program will select the value of the case label that equals the value of the
controlling expression and branch down that path to the end of the code
block.
 If none of the case label values match, then none of the codes within the
switch statement code block will be executed. Java includes a default label to
use in cases where there are no matches.
 We can have a nested switch within a case block of an outer switch.

Syntax:

switch (Expression)

case value 1:
{ Statements; break; }
case value 2:
{Statements; break; }
……
default: { Statements; }
}

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

18
MODULE I

Demonstration of Switch Cases

public class Switch_Statement {


public static void main(String[] args) {
/* Java Program to check the size of a paragraph is it big ,
small or medium by looking at the number of words
using the switch...case statement*/
int number_of_words=21;
String size;
switch (number_of_words)
{case 80:
size="large";
System.out.println(size);
break;
case 78:
size="medium";
System.out.println(size);
break;
case 10:
size="small";
System.out.println(size);
break;
Note: The break statement is optional.
default:
 IfSystem.out.println("Entered Number
you omit the break, execution will continue into theis
nextnot
case. there in any of
the switch statements");
It is sometimes desirable to have multiple cases without break statements between
them. }}}

Iteration Statements: The while loop, do --- while loop


The while loop
 The while statement is a looping construct control statement that executes a block
of code while a condition is true.
 You can either have a single statement or a block of code within the while loop
 . The loop will never be executed if the testing expression evaluates to false.
 The loop condition must be a Boolean expression.
Syntax: while(condition)
{ // statements };

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

19
MODULE I

Demonstration of while

public static void main(String[] args) {

//Demonstration of While Loop TO print the multiplication


table of 5
int j=1;
int number = 5;
while(j<=10)
{System.out.println(j + "*" + number + "="+(j*number));
j++;
}

}
}

The do-while loop


 The do-while loop is similar to the while loop, except that the test is performed at the
end of the loop instead of at the beginning.
 This ensures that the loop will be executed at least once.
Syntax:
do
{
Body of the loop
}
while(condition);

Demonstration of do – while loop

public class Do_while {

public static void main(String[] args) {


int i=1;
do
{System.out.println(i);
i++;

}
while(i<=10);
Department of Artificial Intelligence & Data Science , DBIT Bangalore.
}
}

20
MODULE I

Difference between while and do – while


The main difference between a while loop and a do-while loop is that the code inside a
while loop may never be executed if the condition is initially false, whereas the code inside a
do-while loop is always executed at least once.
Parameter While Do – while
Definition The loop body is executed The loop body is executed,
after the given condition is and then the given condition
evaluated. is checked.
Variable Initialization Variables are initialized Variables may initialize
before the execution of the before or within the loop.
loop.
Loop type Entry Control Loop Exit Control Loop.
Semicolon Semicolon is not used as a Semicolon is used as a part
part of the syntax. of the syntax.
Syntax while(condition){ do{
//loop body // loop body
} } while (condition);
The for loop and for each loop
The for loop
 The for loop is a looping construct which can execute a set of instructions a
specified number of times. It’s a counter-controlled loop.
Syntax:
for(initialization; condition; iteration)
{
//body
}

Demonstration of for loop

//Demonstration Of for loop to add 1 to 10 numbers


public class for_loop {
public static void main(String[] args) {
int sum=0;
int i;
for(i=1; i<=10; i++)
{sum= sum+i;
}
}
}

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

21
MODULE I

The For-Each Version of the for Loop(Enhanced for loop)


 Beginning with JDK 5, a second form of for was defined that implements a “foreach”
style loop.
 The general form of the for-each version of the form is shown here
Syntax:

for(type itr-var: collection)

Statements;

package xxxx;
import java.util.ArrayList;
public class
Demonstration ForEachLoop
of for each loop {
public static void main(String[] args) {
ArrayList<String> list=new ArrayList<String>();
list.add("vimal");
list.add("sonoo");
list.add("ratan");
//traversing the list of elements using for-each loop
for(String s:list)
{System.out.println("First Element of Array is "+ s);
}
Difference between for loop and for each loop
The for loop is a control structure for The foreach loop is a control structure for
specifying iteration that allows code to be traversing items in an array or a collection.
repeatedly executed.
A for loop can be used to retrieve a The foreach loop cannot be used to retrieve
particular set of elements. a particular set of elements.
The for loop is harder to read and write than The for each loop is easier to read and write
the for-each loop. than the for loop.
The for loop is used as a general-purpose The foreach loop is used for arrays and
loop. collections.
Jump Statements – break ,continue and return
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program. The break statements

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

22
MODULE I

break
 The break statement transfers control out of the enclosing loop (for, while, do
or switch statement).
 You use a break statement when you want to jump immediately to the
statement following the enclosing control structure.
 You can also provide a loop with a label, and then use the label in your break
statement.
 The label name is optional, and is usually only used when you wish to
terminate the outermost loop in a series of nested loops.
Syntax:

break;

Demonstration of break
//Demonstrating break statement - while printing 1
to 10 break it when we reach the number 8.
public class Break_COntinue {
public static void main(String[] args) {
for (i=1; i<=10; i++){
if (i==8)
{
break;
}
System.out.println(i);
}
}}

Continue
A continue statement stops the iteration of a loop (while, do or for) and causes execution
to resume at the top of the nearest enclosing loop.
 You use a continue statement when you do not want to execute the remaining
statements in the loop, but you do not want to exit the loop itself.
 You can also provide a loop with a label and then use the label in your continue
statement.
 The label name is optional, and is usually only used when you wish to return to the
outermost loop in a series of nested loops.
Syntax:

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

23
MODULE I

continue;

Demonstration of continue

//Demonstrating continue statement. When i=8, the


number 8 will not be printed. only the numbers
1,2,3,4,5,6,7,9,10 will be printed
public class Continue {
public static void main(String[] args) {
int i;
for (i=1; i<=10; i++)
{if (i==8)
{continue;
}
System.out.println(i);
}
}
}

The return statement


The return statement exits from the current method, and control flow returns to where the method
was invoked.

Syntax:

The return statement has two forms: One that returns a value

return Val;

One that doesn't returns a value

return;

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

24
MODULE I

Difference between break and continue


Key Break continue

Functionality Break statements are mainly used to The continue statement mainly
terminate the enclosing loop such as skips the rest of the loop
while, do-while, for, or switch wherever the continue is
statements wherever a break is declared. declared and executes the next
iteration.
Executional The break statement resumes the control The continue statement resumes
flow of the program to the end of the loop and the control of the program to the
makes execution flow outside that loop. next iteration of that loop
enclosing 'continue' and made
execution flow inside the loop
again.
Usage As mentioned, break is used for the On the other hand, continue
termination of the enclosing loop. causes early execution of the
next iteration of the enclosing
loop.
Compatibility The break statement can be used and We can't use the continue
compatible with 'switch', and 'label'. statement with 'switch', and
'label' as it is not compatible
with them.

Department of Artificial Intelligence & Data Science , DBIT Bangalore.

25

You might also like