UNIT 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 99

Basic Syntactical

Constructs in Java

Mr. S. P. Kholambe
Paradigms of programming Language
B Language

COBOL

Pascal

C
Compiler Based
Procedure Oriented
C++
Compiler Based
Object Oriented
Java (Oak) Compiler & Interpreter Based
Basics

 A Compiler is a computer program that transforms source code written in


a programming language (the source language) into another computer
language. (A binary form known as object code).
 An Interpreter is a computer program that directly executes, i.e. performs,
instructions written in a programming, without previously compiling them
into a machine language program.
 Procedure Oriented: It is a flow of function which will execute one
function after another.
 Object Oriented : It work by using object. Object may call any function or
method of a program.
What is Java?
 Java is a programming language and a platform.
 Platform : Any hardware or software environment in which a program runs, known as a
platform. Since Java has its own Runtime Environment (JRE) and API, it is called platform.
Where it is used?
 Desktop Applications such as acrobat reader, media player, antivirus etc.
 Web Applications such as irctc.co.in, javatpoint.com etc.
 Enterprise Applications such as banking applications.
 Mobile
 Embedded System
 Smart Card
 Robotics
 Games etc.
Difference Between C & JAVA
Difference Between JAVA & C++
Java Features
 Simple:
 Syntax is based on C++ (so easier for programmers to learn it after C++).

 Removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
 No need to remove unreferenced objects because there is Automatic Garbage Collection in java.

 Object-oriented:
 Object-oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior.
 Object-oriented programming(OOPs) is a methodology that simplify software development and
maintenance by providing some rules.
 Basic concepts of OOPs are:

 Object, Class, Inheritance, Polymorphism, Abstraction, Encapsulation etc.


Java Features
 Platform Independent:
 Java provides software-based platform. The Java platform differs from most other
platforms in the sense that it's a software-based platform that runs on top of other
hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
 Java code can be run on multiple platforms.
 e.g. Windows, Linux, Sun Solaris, Mac/OS etc.
 Java code is compiled by the compiler and converted into byte code. This byte code is a
platform independent code because it can be run on multiple platforms i.e. Write Once
and Run Anywhere(WORA).
Java Features
 Secured:
 Java is secured because: No explicit pointer, Programs run inside virtual machine
sandbox.
 Classloader- adds security by separating the package for the classes of the local file system from
those that are imported from network sources.
 Bytecode Verifier- checks the code fragments for illegal code that can violate access right to objects.
 Security Manager-
determines what resources
a class can access such as
reading and writing to the
local disk.
Java Features

 Robust:
 Robust simply means strong. Java uses strong memory management. There are
lack of pointers that avoids security problem. There is automatic garbage
collection in java. There is exception handling and type checking mechanism in
java. All these points makes java robust.
 Architecture-neutral:
 There is no implementation dependent features e.g. size of primitive types is
set.
 Portable:
 We may carry the java byte code to any platform.
Java Features
 High-performance:
 Java is faster than traditional interpretation since byte code is "close" to native
code still somewhat slower than a compiled language (e.g., C++)
 Distributed:
 We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any
machine on the internet.
 Multi-threaded:
 A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The
main advantage of multi-threading is that it shares the same memory. Threads are
important for multi-media, Web applications etc.
Java Features
 Dynamic:
 Java was designed to adapt to an evolving environment:

 Even after binaries have been released, they can adapt to a changing environment
Java loads in classes as they are needed, even from across the network It defers
many decisions to runtime, which solves many of the version problems that C++
has Dynamic linking .
 Interpreted:
 The Java compiler generates byte-codes, rather than native machine code. To
actually run a Java program, you use the Java interpreter to execute the compiled
byte-codes. Java byte-codes provide an architecture-neutral object file format. The
code is designed to transport programs efficiently to multiple platforms.
 Software author is protected, since binary byte streams are downloaded and not
the source code
Java Support System

 Internet Connection: It transfer request and response to java


application.
 Web Browser : It is used to access www and run java applet.
 HTML: applet tag-placing java applet in html
 Byte code: It is highly optimize instruction set.
 Mail Server: It exchange mail across the networks.
Java Programming Environment
 Java environment includes number of development tools that contains various type
of classes & methods.
 The development codes are the part of system is known as Java Development Kit
(JDK) and classes or methods are the part of Java Standard Library(JSL) and
Application Program Interface (API).
 JDK contents:
 appletviewer – this tool can be used to run and debug Java applets without a web browser.
 java – the loader for Java applications(interpreter)
 javac – the Java compiler, which converts source code into Java bytecode
 javadoc – the documentation generator, which automatically generates documentation from source
code comments
 jar – the archiver, which packages related class libraries into a single JAR file.
 javah – the C header and stub generator, used to write native methods
 javap – the class file disassemble.
 javaws – the Java Web Start launcher for JNLP applications
How to Create & Execute Java Program
1. Create the hello java program:
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
2. Save this file as Simple.java
3. To compile: javac Simple.java
4. To execute: java Simple
5. Output: Hello Java
Understanding first java program
 Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
 class keyword is used to declare a class in java.
 public keyword is an access modifier which represents visibility, it means it is
visible to all.
 static is a keyword, if we declare any method as static, it is known as static method.
The core advantage of static method is that there is no need to create object to
invoke the static method. The main method is executed by the JVM, so it doesn't
require to create object to invoke the main method. So it saves memory.
 void is the return type of the method, it means it doesn't return any value.
 main represents startup of the program.
 String[] args is used for command line argument. We will learn it later.
 System.out.println() is used print statement. We will learn about the internal
working of System.out.println statement later.
Java Virtual Machine(JVM)
 JVM is an abstract machine. It is a specification that provides runtime
environment in which java byte code can be executed.
 JVMs are available for many hardware and software platforms.

What is JVM?
 A specification where working of Java Virtual Machine is specified. But
implementation provider is independent to choose the algorithm. Its
implementation has been provided by Sun and other companies.
 An implementation Its implementation is known as JRE.
 Runtime Instance Whenever you write java command on the command
prompt to run the java class, and instance of JVM is created.
Java Virtual Machine(JVM)
 The JVM performs following operation:
 Loads code ,Verifies code, Executes code, Provides runtime environment
 Process of Compilation:

 Process of Interpretation:
Classes

 A class is a collection of fields (data) and methods (procedure or


function) that operate on that data.

Name of class

Variable Declaration

Methods Declaration

22
Defining a class

 The basic syntax for a class definition


class ClassName [extends Super ClassName]
{
[fields declaration]
[methods declaration]
}
 Object is default superclass of every java program.
Field Declaration

 Data is encapsulated in a class by placing data fields inside the body of


class declaration.
 The fields (data) are also called the instance variables.

class Circle
{
public double x, y; // centre coordinate
public double r; // radius of the circle
}
Method Declaration

 Methods are declared inside the body of the class but immediately after
the declaration of data fields.
 The general form of a method declaration is:

Access Modifier Return_type MethodName (parameter-list)


{
Method-body;
}
Method Declaration
 A method definition consists of a method header and a method body. Here are all the parts of
a method:
 Modifiers: The modifier, which is optional, tells the compiler how to call the method. This
defines the access type of the method.
 Return Type: A method may return a value. The return ValueType is the data type of the
value the method returns. Some methods perform the desired operations without returning
a value. In this case, the returnValueType is the keyword void.
 Method Name: This is the actual name of the method. The method name and the parameter
list together constitute the method signature.
 Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value
to the parameter. This value is referred to as actual parameter or argument.
 Method Body: The method body contains a collection of statements that define what the
method does.
Creating Object

 In java block of memory that contains space to store the instance variable.
 Objects are created dynamically using the new keyword.
 There are three steps when creating an object from a class −
 Declaration − A variable declaration with a variable name with an object type.
 Instantiation − The 'new' keyword is used to create the object.

 Initialization − The 'new' keyword is followed by a call to a constructor. This call


initializes the new object.

 Syntax: ClassName objectReference = new ClassName();


 Example: Circle c = new Circle();
Accessing Class Member

 Object is used to communicate variable & methods that are declare in


class.
 Syntax:

ObjectName.VariableName=Value
ObjectName.MethodName(Parameter_List)

 Example:

c.x=10;
c.area(int radius)
Java Tokens
 Token -Smallest individual units in a program is known as Token.
1. Identifiers :
 The first category of token is an Identifier.
 Identifiers are used by programmers to name things in Java: things such as
variables, methods, fields, classes, interfaces, exceptions, packages, etc.
 The rules for identifiers define:
1. Identifier have alphabets, digits, and underscore etc.
2. Identifier not begins with digit.
3. Upper and Lower case are distinct.
4. No limitation of length.
 For Example:
 area, TOTAL, F_MAX, sum
Java Tokens
2. Keywords :
 The second category of token is a Keyword, sometimes called a reserved word.
Keywords are identifiers that Java reserves for its own use.
 We can also not attempt to use Boolean value true and false or null in program.
Java Tokens

3. Separators:
 The third category of token is a Separator (also known as a punctuator).
There are exactly nine, single character separators in Java.
 Seperator are symbols used to indicate where groups of code is divided
and arranged.
 separator :- <= ; | , | . | ( | ) | { | } | [ | ]
Java Tokens
4. Operators:
 The fourth category of token is an Operator. Java includes 37 operators
that are listed in the table below; each of these operators consist of 1, 2,
or at most 3 special characters.
 The keywords instanceof and new are also considered operators in
Java.
Java Tokens

5. Literals :
 All values that we write in a program are literals: each belongs to one of
Java's four primitive types (int, double, boolean, char) or belongs to the
special reference type String.
 A value written in a Java
program is called a literal;
and, each written literal
belongs in exactly one type.
Java Tokens
6. Comments :
 Comments allow us to place any
form of documentation inside our
Java code.
 They can contain anything that we
can type on the keyboard: English,
mathematics, even low-
resolution pictures.
 Line-Oriented:
 begins with // and continues until
the end of the line.
 Block-Oriented:
 begins with /* and continues
(possibly over many lines) until */ is
reached.
Java Tokens

 The Java Character Set:


 The full Java character set includes all the Unicode characters; there are
216 = 65,536 unicode characters.
 The subset of unicode that includes all the ASCII (pronounced "Ask E")
characters; there are 28 = 256 ASCII characters, of which we will still
use a small subset containing alphabetic, numeric, and some special
characters.
Data Types
Primitive Data Types

 Java support 8 primitive data types:

1. byte:
 Byte is a 8 bit data type
 It's range is -128 to 127.
 It's default value is zero.
 It is the smallest java integer type. Byte is four times smaller
than an int.
 Example :
 byte x = 90,
 byte y =- 60.
Primitive Data Types

2. short:
 Short is 16 bit signed type.
 It's range is 32,768 to 32,767.
 Default value is 0.
 Short is 2 times smaller than an int.
 Example :
 short s= 20000 ,
 short r = -30000
Primitive Data Types

3. int :
 Int is a 32-bit data type.
 It's range is from 2,147,483,648 to 2,147,483,647.
 For integral value int is generally used.
 Default value is 0.
 Example :
 int a = 200000,
 int b = -300000.
Primitive Data Types
4. long:
 Long is 64 bit data type.
 It's range is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
 Long is used where we need to store a wider range data than int.
 It's default value is 0L.
 Example :
 int a = 100000L,

 int b = -200000L.
Primitive Data Types

5. double:
 Double is used ,when fractional precision calculation is
required.
 It is 64 bit double precision data type.
 It's default value is Default value is 0.0d.
 Example :
 double d = 123.4.
Primitive Data Types

6. float :
 float is 32 bit single precision type.
 It is used when fractional precision calculation is required.
 Default value is 0.0f.
 Example :
 float f1 = 234.5f.
Primitive Data Types

7. Boolean:
 When we need to represent one bit of information, we use Boolean
data type.
 It takes two values true and false.
 It is generally used where we need to track true or false conditions.
 Default value is false.
 Example :
 Boolean one = true.
Primitive Data Types

8. char:
 char is 16 bit type and used to represent Unicode characters.
 Range of char is 0 to 65,536.
 Example:
 char letter ='A' .
What is a Constant?

 To fixed value that do not change during execution.


 Numeric constants:
 Integer Constant:- Sequence of digits.

Decimal- Digit between 0 to 9. e.g. 456,254.


Octal- Combination of digit 0 t0 9 with leading 0.
e.g. 056,023
Hexadecimal- Digits preceded by ox to 0X. E.g. 0X5,0X9a
 Real Constant: Numbers containing fractional part.

 Fixed point notation e.g. 145.56


 Floating point notation e.g. 145e2, 1.6e+7
Constants

 Character Constants:
 Character Constant: A single character constant contain a single character
enclosed with single quotes.
e.g. ‘5’, ‘A’.
 String Constants: A sequence of character enclosed with double quotes.

e.g. “Java”, “156”, ”ad*cd+d”.


 Backslash Character Constants:

\n new line, \b backspace, \f form feed,


\r Ca rring return, \t horizontal tab, \’ Single quotes,
\ “ Double quotes, \\ backslash.
What is a variable?
 It is a named computer location in memory that holds values that
might vary.
 Variable is a name of memory location.
 Must that location have an address?
 YES
 What has addresses? Bits, bytes, words, what?
 Bytes

 Can a variable be more than one byte long?


 YES
Variable
 Variable is name of reserved area allocated in memory.
 Syntax:
 Data type name of variable = value;
 int i = 10;
Types Of Variable

 There are three types of variables in java


 local variable
 Instance variable
 Class variable
1. Local Variable
 A variable that is declared inside the method is called local variable.
2. Instance Variable
 A variable that is declared inside the class but outside the method is called
instance variable . It is not declared as static.
3. Class variable
 Class variables are variables declared within a class, outside any method,
with the static keyword.
public class MainClass {
public static void main(String[] args) {
int outer = 1;
{
int inner = 2;
System.out.println("inner = " + inner);
System.out.println("outer = " + outer);
}
int inner = 3;
System.out.println("inner = " + inner);
System.out.println("outer = " + outer);
}
}
OUTPUT: inner = 2
outer = 1
inner = 3
outer = 1
Type Casting

 Assigning a value of one to a variable of another type is known as


Type Casting.
 Reference type casting is nothing but assigning one Java object to
another object.
 It comes with very strict rules and is explained clearly in Object
Casting.
 Example:
 int x = 10;

 byte y = ( byte ) x;
Implicit Casting (Widening Conversion)
 A data type of lower size (occupying less memory) is assigned to a data type of
higher size. This is done implicitly by the JVM.
 The lower size is widened to higher size. This is also named as automatic type
conversion.
 int x = 10; // occupies 4 bytes

 double y = x; // occupies 8 bytes

 In the above code 4 bytes integer value is assigned to 8 bytes double value.
public class Implicitdemo {

public static void main(String[] args) {


int i = 100;
long l =i;
float f = l;

System.out.println("Int Value : " +i);


System.out.println("Long Value : " +l);
System.out.println("Float Value : " +f);
}
}

********************** OUTPUT *********************


Int Value : 100
Long Value : 100
Float Value : 100.0
Explicit Casting (Narrowing Conversion)

 A data type of higher size (occupying more memory) cannot be


assigned to a data type of lower size.
 This is not done implicitly by the JVM and requires explicit casting; a
casting operation to be performed by the programmer.
 The higher size is narrowed to lower size.
public class Test
{
public static void main(String[] args)
{
double d = 100.10;
long l =(long)d;
int i= (int)l;

System.out.println("Double Value : " +d);


System.out.println("Long Value : " +l);
System.out.println("Int Value : " +i);
}
}
********************** OUTPUT *********************
Double Value : 100.1
Long Value : 100
Int Value : 100
Standard Default Value

 Java Provide default value to the variable for initialize them. The
standard value of different variable listed below:
Operator & Expression

 Expressions are segments of code that perform computations and


return values. They are combinations of literals, variables, constants,
and operators.
 An operator performs an action on variables, constants, and literals.
Types Of Operator

1. Arithmetic
2. Relational
3. Logical
4. Assignment
5. Increment & decrement
6. Conditional
7. Bitwise
8. Special
Arithmetic Operator
 Basic arithmetic operators
class ArithmeticOperatorDemo
are: +, -, *, /, %. {
 + is for addition. public static void main(String args[ ])
{
 – is for subtraction. int n1 = 100;
 * is for multiplication. int n2 = 20;

 / is for division. System.out.println(“Addition is: " + (n1 + n2) );


 % is for modulo. System.out.println("Subtraction: " + (n1 - n2) );
System.out.println("Multiplication : " + (n1 * n2) );
System.out.println(" Division : " + (n1 / n2) );
System.out.println(" Modulo : " + (n1 % n2) );
}
}
Relational (Comparison) Operator

 The equality and relational operators determine if one operand is


greater than, less than, equal to, or not equal to another
operand.
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
Logical Operator

 An expression that content two or more relational expression is called


as Logical operator.
&& Conditional-AND
|| Conditional-OR
! NOT
 Eg. (a>b) && (d<e)
(a>b) || (c>d)
Assignment Operator

 Assignments operators in java are: =, +=, -=, *=, /=, %=

 num2 = num1 would assign value of variable num1 to the variable.


 num2+=num1 is equal to num2 = num2+num1
 num2-=num1 is equal to num2 = num2-num1
 num2*=num1 is equal to num2 = num2*num1
 num2/=num1 is equal to num2 = num2/num1
 num2%=num1 is equal to num2 = num2%num1
class AssignmentOperatorDemo {
public static void main(String args[ ]) {
int num1 = 10;
int num2 = 20;

num2 = num1;
System.out.println("= Output: "+num2);
num2 += num1;
System.out.println("+= Output: "+num2);
num2 -= num1;
System.out.println("-= Output: "+num2);
num2 *= num1;
System.out.println("*= Output: "+num2);
num2 /= num1;
System.out.println("/= Output: "+num2);
num2 %= num1;
System.out.println("%= Output: "+num2);
}
}
Increment & Decrement
 Increment and Decrement Operators are Unary Operators.
 Operates on One Operand.
 Increment Operator is Used to Increment Value Stored inside Variable on which
it is operating.
 Decrement Operator is used to decrement value of Variable by 1 (default).
 Types:
 Pre Increment / Pre Decrement Operator
 Post Increment / Post Decrement Operator
class OperatorDemo {
public static void main(String args[])
{
int x=10;
System.out.println(x++); //10 (11)
System.out.println(++x); //12
System.out.println(x--); //12 (11)
System.out.println(--x); //10
}
}
Output:
10
12
12
10
Ternary (Conditional) Operator

 This operator evaluates a


class OperatorExample{
Boolean expression and assign
public static void main(String args[]){
the value based on the result.
int a=2;
 Syntax:
int b=5;
 variable num1 = (expression) ?
value if true : value if false int min=(a<b)?a:b;
 E.g. a=10, b=15 System.out.println(min);
}
x=(b>a)?a : b;
}
Output: 2
Bitwise Operator

 Bitwise Operators in java : &, |, ^, ~, <<, >>


public class BitwiseOperatorDemo {
public static void main(String args[]) {

int num1 = 11; /* 11 = 00001011 */


int num2 = 22; /* 22 = 00010110 */
int result = 0;
result = num1 & num2;
System.out.println("num1 & num2: "+result);
result = num1 | num2;
System.out.println("num1 | num2: "+result);
result = num1 ^ num2;
System.out.println("num1 ^ num2: "+result);
result = ~num1;
System.out.println("~num1: "+result);
result = num1 << 2;
System.out.println("num1 << 2: "+result);
result = num1 >> 2;
System.out.println("num1 >> 2: "+result);
}}
Special Operator

 Java provides two special operators as given below.


1. instanceof Operator :
 This operator is used to know if an object is an instance of a
particular class or not.
 This operator returns “true” if an object given at the left hand side
is an instance of the class given at right hand side. Otherwise, it
returns “false”.
 Example: circle instanceof Shape
 The above statement checks if the object “circle” is an instance of
the class “Shape”. If yes, it returns “true”, else returns “false”
Special Operator

2. Dot operator(.) :
 This operator is used to access the variables and methods of a class.
 Example: student.mark
 Here we are accessing the variable “mark” of the “student” object
Arithmetic Expression

 It is combination of variables, constants, an operator arrange as per


the syntax of language.

Algebraic Exp. Java Exp


ab- c a*b-c
(m+n)(x+y) (m+n)*(x+y)
ab/c a*b/c
3x2+2x+1 3x*x+2*x+1
Mathematical Functions

 The java.lang.Math class contains methods for performing basic numeric


operations such as the elementary exponential, logarithm, square root, and
trigonometric functions.
Decision Making & Branching

 Decision making: This statement solve one operation & it produce


one output , it may be true /false. Depend on that operation is
known as Decision Making statement.
 Branching or Jumping: When a program breaks the sequential
flow& jump to another part of program is known as Branching or
Jumping.
Decision Making & Branching

 Decision-making statements:
1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement
Decision making if statement

 The if statement is a powerful decision making statement and is used


to control the flow of execution of statements.
 It is basically a two-way decision statement and is used in conjunction
with an expression. It takes the following form:
 Syntax: if (test expression)
 The if statement may be implemented in different forms depending on the
complexity of the conditions to be tested.
 Simple if statement
 if...else statement
 Nested if...else statement
 else if ladder.
Simple if statement

 The Java if statement tests the public class IfExample {


condition. It executes the if block public static void main(String[] args)
if condition is true. {
int age=20;
 Syntax:
if(age>18)
{
if(condition) System.out.print("Age is greater than
18");
{
}
//code to be executed }
} }
Output: Age is greater than 18
The if…else statement

 The Java if-else statement also tests the public class IfElseExample {
condition. It executes the if block if public static void main(String[] args) {
condition is true otherwise else int number=13;
block is executed.
if(number%2==0){
 Syntax:
System.out.println(“Even number");
if(condition){
}else{
//code if condition is true
System.out.println(“Odd number");
}
}
else{
}
//code if condition is false
}
}
Output: Odd number
The Nested if statement
 The nested if statement represents the public class JavaNestedIfExample {
if block within another if block. public static void main(String[] args)
Here, the inner if block condition {
executes only when outer if block
int age=20, weight=80;
condition is true.
if(age>=18){
if(condition)
if(weight>50){
{
System.out.println("You are
//code to be executed eligible to donate blood");
if(condition){ }
//code to be executed }
} }}
} Output: You are eligible to donate blood
The if-else-if ladder statement

 The if-else-if ladder statement if(condition1){


executes one condition from //execute if condition1 is true
multiple statements. }else if(condition2){
//execute if condition2 is true
}
else if(condition3){
// execute if condition3 is true
}
...
else{
//execute if all the conditions are false
}
public class IfElseIfExample else if(marks>=70 && marks<80){
{ System.out.println("B grade");
public static void main(String[] args) }
{ else if(marks>=80 && marks<90){
int marks=65; System.out.println("A grade");
}
if(marks<50){ else if(marks>=90 && marks<100){
System.out.println("fail"); System.out.println("A+ grade");
} }
else if(marks>=50 && marks<60){ else{
System.out.println("D grade"); System.out.println("Invalid!");
} }
else if(marks>=60 && marks<70){ }
System.out.println("C grade"); }
}
Output: C grade
The switch Statement
 A switch statement allows a switch(expression){
variable to be tested for equality case value1:
against a list of values. Each value //code to be executed;
is called a case, and the variable break; //optional
being switched on is checked for case value2:
each case.
......
default:
code to be executed if all cases are not
matched;
}
public class SwitchExample {
public static void main(String[] args) {

int number=20;

switch(number){

case 10: System.out.println("10");


break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
default: System.out.println("Not in 10, 20 or 30");
}
}
}
Decision Making & Looping

 The process of repeat executing block of code is called looping.


 Control Statement: It test certain condition then direct repeated
execution of statement content of body loop.
 Classify into two type:
1. Entry Controlled Loop
2. Exit Controlled Loop
Control Statement
Types of Looping Statement

 Java provide following three looping mechanisms. You can use one of the
following three loops:
1. for Loop
2. while Loop
3. do...while Loop
The for Statement
 A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:
1. Initialization: It is the initial condition which is executed once when the loop starts.
2. Condition: It is the second condition which is executed each time to test the condition of
the loop. It continues execution until the condition is false.
3. Statement: The statement of the loop is executed each time until the second condition is
false.
4. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
Syntax: for (initialization; termination; increment)
{
statement(s);
}
public class ForExample {
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
}
}

*For loop is an entry controlled loop statement.


While statement
 The Java while loop is used to iterate
a part of the program several public class WhileExample
times. If the number of iteration is {
not fixed, it is recommended to use public static void main(String[]
while loop. args)
 Syntax:
{
int i=1;
while(test condition)
while(i<=10){
{
System.out.println(i);
Body of the loop; i++;
} }
 While is an entry controlled loop }
statement. }
Do-while statement
 The Java do-while loop is used to iterate a public class DoWhileExample {
part of the program several times. If the
public static void main(String[] args)
number of iteration is not fixed and you
must have to execute the loop at least {
once, it is recommended to use do-while int i=1;
loop.
do{
 The Java do-while loop is executed at least
once because condition is checked after System.out.println(i);
loop body. (Exit Controlled Loop) i++;
do }while(i<=10);
{
}
body of the loop;
}
}
while(test condition);
Break Statement
 When a break statement is encountered public class BreakExample {
inside a loop, the loop is immediately public static void main(String[] args) {
terminated and the program control
resumes at the next statement for(int i=1;i<=10;i++){
following the loop.
if(i==5){
 The Java break is used to break loop
or switch statement. It breaks the
current flow of the program at specified break; //breaking the loop
condition. }
 We can use Java break statement in all System.out.println(i);
types of loops such as for loop, while }
loop and do-while loop. }
}
Continue Statement
 The continue statement is used in loop public class ContinueExample {
control structure when you need to public static void main(String[] args) {
jump to the next iteration of the loop
immediately. for(int i=1;i<=10;i++){
 The Java continue statement is used to if(i==5){
continue the loop. It continues the
continue;//it will skip the
current flow of the program and rest statement
skips the remaining code at the
}
specified condition.
System.out.println(i);
 We can use Java continue statement in
all types of loops such as for loop, }
while loop and do-while loop. }
}
Return Statement
 At any time in a method the return class Return
statement can be used to cause {
execution to branch back to the public static void main(String args[ ])
caller of the method. {
 Thus, the return statement boolean t = true;
immediately terminates the System.out.println("Before the return.");
method in which it is executed. if(t)
 Here, return causes execution to return; // return to caller
return to the Java run-time system, System.out.println("This won't execute.");
since it is the run-time system that }
calls main( ). }
Nested Loops

 Java allows loops to be nested class Pattern {


public static void main(String[] args) {
(i.e., loops within loops) like all
the other programming languages int rows = 5;
allows.
for(int i = 1; i <= rows; ++i)
 Nested loops means, loop inside {
loop inside loop and so on. for(int j = 1; j <= i; ++j)
{
System.out.print(j + " ");
}
System.out.println("");
}
}
}
Labeled Loops

 According to nested loop, if


we put break statement in
inner loop, compiler will jump
out from inner loop and
continue the outer loop again.
What if we need to jump out
from the outer loop using
break statement given inside
inner loop? The answer is, we
should define lable along
with colon(:) sign before loop.
class WithLabelledLoop class LabeledContinue {
{ public static void main(String[] args) {
public static void main(String args[])
{ label:
int i,j; for (int i = 1; i < 6; ++i)
{
loop1: for(i=1;i<=10;i++)
{
for (int j = 1; j < 5; ++j)
System.out.println(); {
if (i == 3 || j == 2)
loop2: for(j=1;j<=10;j++) continue label;
{ System.out.println("i = " + i + "; j = " + j);
System.out.print(j + " "); }
}
if(j==5) }
break loop1; //Statement 1 }
}
} }}
OUTPUT: 1 2 3 4 5
For each version of the for loop

 The for-each loop is used to public class ForEachExample {


traverse array or collection in public static void main(String[] args)
java. It is easier to use than simple {
for loop because we don't need int arr[]={12,23,44,56,78};
to increment value and use for(int i:arr)
subscript notation.
{
 It works on elements basis not
System.out.println("The Array is: "+i);
index. It returns element one by
}
one in the defined variable.
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy