0% found this document useful (0 votes)
64 views58 pages

Chapter 1 Basic Syntactical Constructs

Uploaded by

Harish Khojare
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)
64 views58 pages

Chapter 1 Basic Syntactical Constructs

Uploaded by

Harish Khojare
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/ 58

JAVA PROGRAMMING ( 22412)

Unit 1
Basic Syntactical Constructs In Java
What is Java
1.Java is a programming language and a platform.
2.Java is a high level, robust, object-oriented and secure programming language.
3.Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995.
4.James Gosling is known as the father of Java.
5.Before Java, its name was Oak.
6.Since Oak was already a registered company, so James Gosling and his team changed the Oak
name to Java.

Platform: Any hardware or software environment in which a program runs, is known as a


platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

Prepared By Roshani K.Dharme Head Computer


1
Engg.Department
JAVA Features

A list of most important features of Java language is given below.

1.Compiled and Interpreted:


2.Platform Independent
3.Portable
4.Robust and Secure
5.Dynamic
6.Object Oriented
7.Distributed
8.Multithreaded and Interactive
9.High Performance

Prepared By Roshani K.Dharme Head Computer


2
Engg.Department
JAVA Features

1. Compiled and Interpreted:


Java is first machine independent programming language; it uses both compiler and interpreter.
Java compilers are designed in such a way that converts source code into platform independent form
i.e byte codes. These byte codes are then converted to machine code by interpreter.

2.Platform Independent
Java compiler produces a unique type of code called byte code unlike c compiler where compiler
produces only natively executable code for a particular machine.
When the Java program runs in a particular machine it is sent to java compiler, which converts this
code into intermediate code called byte code. This byte code is sent to Java virtual machine (JVM)
which resides in the RAM of any operating system. JVM recognizes the platform it is on and converts
the byte codes into native machine code. Hence java is called platform independent language.

Prepared By Roshani K.Dharme Head Computer


3
Engg.Department
JAVA Features

Prepared By Roshani K.Dharme Head Computer


4
Engg.Department
JAVA Features
3. Portable
Java is portable because it facilitates you to carry the Java byte code to any platform. It doesn't require
any implementation.

4.Robust and Secure


Robust: Java is Robust because it is highly supported language. It is portable across many operating
systems. Due to this feature it is also known as “ Platform Independent” or “Write Once Run
Anywhere” language.
This makes Java a platform independent language, one of the major reason to prefer java over other
languages like C and C++ for developing apps and other software's.

Secure: Unlike C, there are no pointers in Java. The basic use of Pointers is to refer to the actual
memory location where the value is stored, and hence enabling the programmer to further modify the
actual value.
As java does not consist of pointers, there is no way one can refer to the actual value, and hence the
value remains protected or unaltered.
Due to these reasons, Java is known as a Secure language.
Prepared By Roshani K.Dharme Head Computer
5
Engg.Department
JAVA Features

5. Dynamic
Java is dynamic language
It is capable of dynamically linking in new class libraries ,methods and objects.
It can also determine the type of class through a query, making it possible to either dynamically link or
abort the program depending on the response.

6.Object Oriented
A fully object-oriented language needs to have all the 4 oops concepts i.e Abstraction, Polymorphism,
Encapsulation, Inheritance.
In addition to that, all predefined and, user-defined types must be objects and, all the operations should
be performed only by calling the methods of a class.
Though java follows all the four object-oriented concepts,
Java has predefined primitive data types (which are not objects).
You can access the members of a static class without creating an object of it.
Therefore, Java is not considered as fully object-oriented Technology.

Prepared By Roshani K.Dharme Head Computer


6
Engg.Department
JAVA Features

7. Distributed
Java is a distributed language as it can be used to create applications to communicate over the
network as it supports TCP/IP, network communication protocol.

8. Multithreaded and Interactive


The process of executing multiple threads simultaneously (concurrently) is called multithreading in
Java.
When a program contains more than one thread, the CPU can switch between two threads to execute
them at the same time.

9.High Performance
Java has high performance than C and C++.
In real life applications ,most of the time java is prefer than C/C++.

Prepared By Roshani K.Dharme Head Computer


7
Engg.Department
JAVA Programming Environment

The Java Programming environment consists of —


Java Language — used by programmers to write the application
The Java Virtual Machine (JVM) — used to execute the application
The Java Ecosystem — provides additional value to the developers using the programming language

What is the Java Language?


It is a human-readable language which is generally considered easy to read and write (albeit a bit
verbose at times).
It is class-based and object-oriented in nature.
Java is intended to be easy to learn and to teach.

Prepared By Roshani K.Dharme Head Computer


8
Engg.Department
JAVA Programming Environment

What is the JVM?


❑ The Java Virtual Machine is a program which provides the runtime environment to execute Java
programs.
❑ Java programs cannot run if a supporting JVM is not available.
❑ JVM does not take Java source files as input.
❑ The java source code is first converted to bytecode by javac program.
❑ Javac takes in source files as input and outputs bytecode in the form of class files with .class
extension.
These class files are then interpreted (stepped through one at a time) by the JVM interpreter and the
program is executed. JVM makes the programmer’s life easier by- providing a container for the Java
program to run in creating a secure execution environment as compared to C/C++ taking memory
management out of the hands of the developer allowing class files from one platform to run on a
different environment without any modification or recompilation
This property is known as “write once, run anywhere” (WORA) and thus make Java an easily
portable language.

Prepared By Roshani K.Dharme Head Computer


9
Engg.Department
JAVA Programming Environment

Prepared By Roshani K.Dharme Head Computer


10
Engg.Department
JAVA Programming Environment

Java Ecosystem
Java has emerged to be a robust, portable and high performing language and has been widely
adopted globally. One of the major reasons for the success of Java is the immense number of
third party libraries and components written in Java. Today it is rare to a find a component
which does not have a supporting Java connector. From traditional MySQL to NoSQL,
monitoring frameworks, network components all have a Java connector readily available.

Prepared By Roshani K.Dharme Head Computer


11
Engg.Department
Defining Class In Java
A class is a user-defined data type with the template that serves to define its properties.
Most important thing here is to understand is that a class defines new data type. Once defined, this
new data type can be used to create objects of that type.
A class is declared by the keyword class.
class class-name
{
data-type instance-variable1;
data-type instance-variable2; Class Members
- - - - -;
data-type instance-variableN;

data-type method-name1(parameter-list)
{
//body of the method1
} Member Methods

data-type method-nameN(parameter-list)
{
//body of the methodN
}
} Prepared By Roshani K.Dharme Head Computer
Engg.Department
12
Creating an Object

Creating the objects of the class is also called as instantiating an object.


As stated earlier, a class creates new data type.
Objects are created using the ‘new’ operator. This ‘new’ operator creates an object of the specified
class and returns the reference of that object.
Example :
Country India; // declaration
India = new Country(); // instantiation

Prepared By Roshani K.Dharme Head Computer


13
Engg.Department
Accessing the member variables

• The dot operator or member selection operator is used to


access the instance variables of the class.
• We can not access the instance variables outside of the class
without referring to the object.
• syntax:

objectname. variablename

Prepared By Roshani K.Dharme Head Computer


14
Engg.Department
Java Tokens

Constants:
A constant is fixed value that does not change during the execution of the program.
Java support following types of constants:-

Constants

Numeric Character

Integer Real character String

Prepared By Roshani K.Dharme Head Computer


15
Engg.Department
Java Variables
❑ A variable is a container which holds the value while the Java program is executed.
❑ A variable is assigned with a data type.
❑ Variable is a name of memory location.
❑ There are three types of variables in java: local, instance and static.

Variable
Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It
is a combination of "vary + able" that means its value can be changed.
int data=50;//Here data is variable

Reserved Area

10

RAM
Prepared By Roshani K.Dharme Head Computer
16
Engg.Department
Java Variables

There are three types of variables in Java:


1. local variable
2. instance variable
3. static variable
Types of
Variable

Local Instance Static

Prepared By Roshani K.Dharme Head Computer


17
Engg.Department
Java Variables
1) Local Variable
A variable declared inside the body of the method is called local variable.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable. It
is not declared as static.
It is called instance variable because its value is instance specific and is not shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can create a
single copy of static variable and share among all the instances of the class. Memory allocation for
static variable happens only once when the class is loaded in the memory.
Example to understand the types of variables in java
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
} }//end of class
Prepared By Roshani K.Dharme Head Computer
18
Engg.Department
Java Data Types
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
There are 8 types of primitive data types:
1. boolean data type
2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type

Prepared By Roshani K.Dharme Head Computer


19
Engg.Department
Java Data Types

Prepared By Roshani K.Dharme Head Computer


20
Engg.Department
Java Data Types

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is used
for simple flags that track true/false conditions.
Example: Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It is an 8-bit signed two's complement integer.
Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is
127. Its default value is 0. It saves space because a byte is 4 times smaller than an integer. It can also be
used in place of "int" data type.
Example: byte a = 10, byte b = -20

Prepared By Roshani K.Dharme Head Computer


21
Engg.Department
Java Data Types

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to
32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2
times smaller than an integer.
Example: short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and
maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example: int a = 100000, int b = -200000

Prepared By Roshani K.Dharme Head Computer


22
Engg.Department
Java Data Types
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value
is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0.
The long data type is used when you need a range of values more than those provided by int.
Example: long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It
is recommended to use a float (instead of double) if you need to save memory in large arrays of
floating point numbers. The float data type should never be used for precise values, such as
currency. Its default value is 0.0F.
Example: float f1 = 234.5f

Prepared By Roshani K.Dharme Head Computer


23
Engg.Department
Java Data Types

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double data
type also should never be used for precise values, such as currency. Its default value is 0.0d.
Example: double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0)
to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example: char letterA = 'A'

Prepared By Roshani K.Dharme Head Computer


24
Engg.Department
Java Data Types
Strings
The String data type is used to store a sequence of characters (text). String values must be surrounded
by double quotes:
Example
String greeting = "Hello World";
System.out.println(greeting);
A String in Java is actually a non-primitive data type, because it refers to an object. The String object
has methods that are used to perform certain operations on strings.

Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.
To declare an array, define the variable type with square brackets:
String[] cars;
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};
Prepared By Roshani K.Dharme Head Computer
25
Engg.Department
Java Data Types
This statement accesses the value of the first element in cars:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
// Outputs Volvo

Non-Primitive Data Types


Non-primitive data types are called reference types because they refer to objects.

The main difference between primitive and non-primitive data types are:
❑ Primitive types are predefined (already defined) in Java. Non-primitive types are created by the
programmer and is not defined by Java (except for String).
❑ Non-primitive types can be used to call methods to perform certain operations, while primitive
types cannot.
❑ A primitive type has always a value, while non-primitive types can be null.
❑ A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase
letter.
Prepared By Roshani K.Dharme Head Computer
26
Engg.Department
Dynamic Initialization of Variable
The process of initializing variable at the time of its declaration at run time is known as dynamic
initialization of variable.
Thus in dynamic initialization of variable a variable is assigned value at run time at the time of its
declaration.

int main()
{
int a;
printf(“Enter Value of a”);
scanf(“%d”,&a);
int cube = a * a * a;
printf(“Cube is=%d\n”,cube);
return 0;
}
In above example variable cube is initialized at run time using expression a * a * a at the time of its
declaration.

Prepared By Roshani K.Dharme Head Computer


27
Engg.Department
Scope Of Variable
In Java, variables are only accessible inside the region they are created. This is called scope.

Method Scope
Variables declared directly inside a method are available anywhere in the method following the
line of code in which they were declared:
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
int x = 100;
// Code here can use x
System.out.println(x);
}
}
Block Scope
A block of code refers to all of the code between curly braces {}. Variables declared inside blocks of
code are only accessible by the code between the curly braces, which follows the line in which the
variable was declared:

Prepared By Roshani K.Dharme Head Computer


28
Engg.Department
Scope Of Variable
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
{ // This is a block
// Code here CANNOT use x
int x = 100;
// Code here CAN use x
System.out.println(x);
} // The block ends here
// Code here CANNOT use x
}
}

A block of code may exist on its own or it can belong to an if, while or for statement. In the case of
for statements, variables declared in the statement itself are also available inside the block's scope.

Prepared By Roshani K.Dharme Head Computer


29
Engg.Department
Java Type 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:

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


byte -> short -> char -> int -> long -> float -> double
2. Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte

Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
Example
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
} Prepared By Roshani K.Dharme Head Computer
30
} Engg.Department
Java Type Casting

Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:

Example
public class Main {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}

Prepared By Roshani K.Dharme Head Computer


31
Engg.Department
Standard Default Values

Prepared By Roshani K.Dharme Head Computer


32
Engg.Department
Operator & Expressions
Operators in Java can be classified into 5 types:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Unary Operators
6. Bitwise Operators

1. Java Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on variables and data. For example,
a + b;
Here, the + operator is used to add two variables a and b. Similarly, there are various other arithmetic
operators in Java.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after
Prepared By Roshani division)
K.Dharme Head Computer
33
Engg.Department
Operator & Expressions
2. Java Assignment Operators
Assignment operators are used in Java to assign values to variables.
For example,
int age;
age = 5;
Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5
is assigned to the variable age.
Operator Example Equivalent to
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
3. Java Relational Operators
Relational operators are used to check the relationship between two operands. For example,
a < b;
Here, > operator is the relational operator. It checks if a is less than b or not.It returns either true or
false. Prepared By Roshani K.Dharme Head Computer
34
Engg.Department
Operator & Expressions
Operator Description Example
== Is Equal To 3 == 5 returns false
!= Not Equal To 3 != 5 returns true
> Greater Than 3 > 5 returns false
< Less Than 3 < 5 returns true
>= Greater Than or Equal To 3 >= 5 returns false
<= Less Than or Equal To 3 <= 5 returns false

4. Java Logical Operators


Logical operators are used to check whether an expression is true or false. They are used in decision
making.
Operator Example Meaning
&& (Logical AND) expression1 && expression2 true only if both expression1 and expression2
are true
|| (Logical OR) expression1 || expression2 true if either expression1 or expression2 is
true
! (Logical NOT) !expression true if expression is false and vice
versa Prepared By Roshani K.Dharme Head Computer
35
Engg.Department
Operator & Expressions

5. Java Unary Operators

Unary operators are used with only one operand. For example, ++ is a unary operator that increases
the value of a variable by 1. That is, ++5 will return 6.

Different types of unary operators are:


Operator Meaning
+ Unary plus: not necessary to use since numbers are positive without using it
- Unary minus: inverts the sign of an expression
++ Increment operator: increments value by 1
-- Decrement operator: decrements value by 1
! Logical complement operator: inverts the value of a boolean

Prepared By Roshani K.Dharme Head Computer


36
Engg.Department
Operator & Expressions
6. Java Bitwise Operators
Bitwise operators in Java are used to perform operations on individual bits. For example,
Bitwise complement Operation of 35

35 = 00100011 (In Binary)


~ 00100011
________
11011100 = 220 (In decimal)
Here, ~ is a bitwise operator. It inverts the value of each bit (0 to 1 and 1 to 0).

The various bitwise operators present in Java are:

Operator Description
~ Bitwise Complement
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
& Bitwise AND
Prepared By Roshani K.Dharme Head Computer
^ Bitwise exclusive OR Engg.Department
37
Operator & Expressions
Other operators
Besides these operators, there are other additional operators in Java.
Java instanceof Operator
The instance of operator checks whether an object is an instance of a particular class. For example,

class Main {
public static void main(String[] args) {
String str = "Programiz";
boolean result;
// checks if str is an instance of
// the String class
result = str instanceof String;
System.out.println("Is str an object of String? " + result);
}
}
Output

Is str an object of String? true Prepared By Roshani K.Dharme Head Computer


38
Engg.Department
Operator & Expressions
Java Ternary Operator
The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example,
variable = Expression ? expression1 : expression2
Here's how it works.
If the Expression is true, expression1 is assigned to the variable.
If the Expression is false, expression2 is assigned to the variable.
Let's see an example of a ternary operator.
class Java {
public static void main(String[] args) {
int februaryDays = 29;
String result;
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Output
Leap year
Prepared By Roshani K.Dharme Head Computer
39
Engg.Department
Operator & Expressions
Object member access (.)
An object is a collection of data and methods that operate on that data; the data fields and methods of
an object are called its members. The dot (.) operator accesses these members.

Precedence Of an Operator
Precedence specifies the order in which operations are performed. Consider this expression:

a+b*c
The multiplication operator has higher precedence than the addition operator, so a is added to the
product of b and c. Operator precedence can be thought of as a measure of how tightly operators bind
to their operands. The higher the number, the more tightly they bind.

Default operator precedence can be overridden through the use of parentheses, to explicitly specify
the order of operations. The previous expression can be rewritten as follows to specify that the
addition should be performed before the multiplication:

(a + b) * c
Prepared By Roshani K.Dharme Head Computer
40
Engg.Department
Math Functions
The Java Math class has many methods that allows you to perform mathematical tasks on numbers.

Math.max(x,y)
The Math.max(x,y) method can be used to find the highest value of x and y:

Example
Math.max(5, 10);

Math.min(x,y)
The Math.min(x,y) method can be used to find the lowest value of x and y:

Example
Math.min(5, 10);

Math.sqrt(x)
The Math.sqrt(x) method returns the square root of x:

Example
Math.sqrt(64); Prepared By Roshani K.Dharme Head Computer
41
Engg.Department
Math Functions
Math.abs(x)
The Math.abs(x) method returns the absolute (positive) value of x:

Example
Math.abs(-4.7);

Random Numbers
Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):

Example
Math.random();

To get more control over the random number, e.g. you only want a random number between 0 and 100, you can
use the following formula:

Example
int randomNum = (int)(Math.random() * 101); // 0 to 100
Prepared By Roshani K.Dharme Head Computer
42
Engg.Department
Decision Making and Looping
Java If-else Statement
The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in Java.
1. if statement
2. if-else statement
3. if-else-if ladder
4. nested if statement
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
if(condition){
//code to be executed
}
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true Prepared By Roshani K.Dharme Head Computer
43
}else{ //code if condition is false } Engg.Department
Decision Making and Looping
Using Ternary Operator

We can also use ternary operator (? :) to perform the task of if...else statement. It is a shorthand
way to check the condition. If the condition is true, the result of ? is returned. But, if the condition
is false, the result of : is returned.

Example:

public class IfElseTernaryExample {


public static void main(String[] args) {
int number=13;
//Using ternary operator
String output=(number%2==0)?"even number":"odd number";
System.out.println(output);
}
}

Prepared By Roshani K.Dharme Head Computer


44
Engg.Department
Decision Making and Looping
Java if-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.

Syntax:

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Prepared By Roshani K.Dharme Head Computer
45
Engg.Department
Decision Making and Looping
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail"); }
else if(marks>=50 && marks<60){
System.out.println("D grade"); }
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade"); }
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade"); }else{
System.out.println("Invalid!");
} } } Prepared By Roshani K.Dharme Head Computer
Engg.Department
46
Decision Making and Looping
Java Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed } }
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
} } }} Prepared By Roshani K.Dharme Head Computer
47
Engg.Department
Decision Making and Looping
Java Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long, enum types, String and some
wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.

In other words, the switch statement tests the equality of a variable against multiple values.

Points to Remember
1. There can be one or N number of case values for a switch expression.
2. The case value must be of switch expression type only. The case value must be literal or constant.
It doesn't allow variables.
3. The case values must be unique. In case of duplicate value, it renders compile-time error.
4. The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and
string.
5. Each case statement can have a break statement which is optional. When control reaches to the
break statement, it jumps the control after the switch expression. If a break statement is not found,
it executes the next case.
6. The case value can have a default label which is optional.
Prepared By Roshani K.Dharme Head Computer
48
Engg.Department
Decision Making and Looping

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

Prepared By Roshani K.Dharme Head Computer


49
Engg.Department
Decision Making and Looping
Program to check Vowel or Consonant: case 'A':
public class SwitchVowelExample { System.out.println("Vowel");
public static void main(String[] args) { break;
char ch='O'; case 'E':
switch(ch) System.out.println("Vowel");
{ case 'a': break;
System.out.println("Vowel"); case 'I':
break; System.out.println("Vowel");
case 'e': break;
System.out.println("Vowel"); case 'O':
break; System.out.println("Vowel");
case 'i': break;
System.out.println("Vowel"); case 'U':
break; System.out.println("Vowel");
case 'o': break;
System.out.println("Vowel"); default:
break; System.out.println("Consonant");
case 'u': } } }
System.out.println("Vowel"); Prepared By Roshani K.Dharme Head Computer
50
break; Engg.Department
Decision Making and Looping
Loops in Java
In programming languages, loops are used to execute a set of instructions/functions repeatedly when
some conditions become true. There are three types of loops in Java.
1. for loop
2. while loop
3. do-while loop
Java For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop
instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}

The example below will print the numbers 0 to 4:


Example
for (int i = 0; i < 5; i++) {
System.out.println(i);}
Prepared By Roshani K.Dharme Head Computer
51
Engg.Department
Decision Making and Looping
Java While Loop
Loops can execute a block of code as long as a specified condition is reached.

Java While Loop


The while loop loops through a block of code as long as a specified condition is true:

Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

Example
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end!
Prepared By Roshani K.Dharme Head Computer
52
Engg.Department
Decision Making and Looping
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the
condition is true, then it will repeat the loop as long as the condition is true.

Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is
false, because the code block is executed before the condition is tested:

Example
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
Prepared By Roshani K.Dharme Head Computer
53
Engg.Department
Decision Making and Looping
Java Break and Continue

Java Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
}
Prepared By Roshani K.Dharme Head Computer
54
Engg.Department
Decision Making and Looping
Java Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

This example skips the value of 4:

Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}

Prepared By Roshani K.Dharme Head Computer


55
Engg.Department
Decision Making and Looping
Java Labeled For Loop aa:
We can have a name of each Java for loop. To do for(int i=1;i<=3;i++){
so, we use label before the for loop. It is useful if bb:
we have nested for loop so that we can for(int j=1;j<=3;j++){
break/continue specific for loop. if(i==2&&j==2){
Usually, break and continue keywords break aa;
breaks/continues the innermost for loop only. }
Syntax: System.out.println(i+" "+j);
labelname: }
for(initialization;condition;incr/decr){ } } }
//code to be executed
}
Example:
//A Java program to demonstrate the use of label
ed for loop
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
Prepared By Roshani K.Dharme Head Computer
56
Engg.Department
Decision Making and Looping
Java for-each Loop
The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop
because we don't need to increment value and use subscript notation.
It works on elements basis not index. It returns element one by one in the defined variable.
Syntax:
for(Type var:array){
//code to be executed
}
Example:
//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
} } } Prepared By Roshani K.Dharme Head Computer
57
Engg.Department
Prepared By Roshani K.Dharme Head Computer
58
Engg.Department

You might also like