Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
UNIT II: Constants, Variables and Data Types
2.1 Constants, Symbolic Constants.
2.2 Variables, Declaration of Variables, Giving values to Variables.
2.3 Data Types.
2.4 Typecasting.
2.5 Arithmetic operators, Relational operators.
2.6 Logical operators, Assignment operators.
2.7 Increment & Decrement operators, conditional operators.
2.8 Bitwise operators.
2.9 Arithmetic Expressions, Evaluation of Expressions.
2.10 Type Conversions in Expressions.
2.11 Operator Precedence & Associativity.
2.12 Decision Making with Control Statements,
2.13 Looping Statements, Jump in loops, Labelled loops.
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 1
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
2.1 Constants, Symbolic Constants
A constant is a variable whose value cannot change once it has been assigned.
Java doesn't have built-in support for constants.
a constant is cached by the JVM as well as our application, so using a constant
can improve performance.
To define a variable as a constant, we just need to add the keyword "final" in
front of the variable declaration.
Syntax
final float pi = 3.14f;
Types of Constants
1. Numeric Constants
Numeric constants are the constants that contains numerals. It may also have a
leading sign and decimal point.
a. Integer Constants
A constant that contains digits (0-9) and does not have decimal point is called
integer constants. By default, it is type of int.
b. Real Constants
Numeric constants that have a decimal point are called real or floating-point
constants.
By default, the real constants are of double type. We can explicitly mention the
type of a floating-point constant as a float by appending the letter f or F at the
end of the constant.
2. Non-numeric Constants
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 2
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
A constant that does not contain digits is called non-numeric constants. There
are the following two types of non-numeric constants:
a. Character Constants
A Character constant is a single alphabet, digit or any special symbol enclosed
using single quotes. For example, 'Y',’d’, '6', '#', '&'.
b. String Constants
String constants consist of zero or more characters enclosed in double quotes
(""). At the end of the string, the null character i.e '\0' is automatically placed by
the compiler
Symbolic constants
a symbolic constant is a named constant value defined once and used
throughout a program. Symbolic constants are declared using the final keyword.
Which indicates that the value cannot be changed once it is initialized.
The naming convention for symbolic constants is to use all capital letters with
underscores separating words.
Syntax:
final data_type CONSTANT_NAME = value;
final: The final keyword indicates that the value of the constant cannot be
changed once it is initialized.
data_type: The data type of the constant such as int, double, boolean, or String.
CONSTANT_NAME: The name of the constant which should be written in all
capital letters with underscores separating words.
value: The initial value of the constant must be of the same data type as the
constant.
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 3
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
2.2 Variables, Declaration of Variables, Giving values to Variables
Variables are the containers for storing the data values or you can also call it a
memory location name for the data. Every variable has a:
Data Type – The kind of data that it can hold. For example, int, string, float,
char, etc.
Variable Name – To identify the variable uniquely within the scope.
Value – The data assigned to the variable.
Declaration of Variables
datatype: In Java, a data type define the type of data that a variable can hold.
data_name: Name was given to the variable.
Ex int a;
Giving values to Variables
Use an assignment operator(=) to assign or give value to variable
Ex. a=10;
There are three types of variables in Java
Local Variables
A variable defined within a block or method
The Local variable is created at the time of declaration and destroyed after
exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variables
are declared, i.e., we can access these variables only within that block.
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 4
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
Initialization of the local variable is mandatory before using it in the defined
scope.
Instance Variables
Instance variables are non-static variables and are declared in a class and
outside of any method or block.
Initialization of an instance variable is not mandatory. Its default value is
dependent on the data type of variable. For String it is null, for float it is 0.0f, for
int it is 0, for Wrapper classes like Integer it is null, etc.
Instance variables can be accessed only by creating objects.
Static Variables
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method
Static variables are created when the program starts and destroyed when the
program stops.
Static variables can be accessed by calling with the class name
ClassName.VariableName.
Ex. private static double salary;
public static final String DEPARTMENT = "Development ";
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 5
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
2.3 Data Types
Java data types define the type and value range of the data for the different
types of variables, constants, method parameters, return types, etc.
The data type tells the compiler about the type of data to be stored and the
required memory.
The Java data types are categorized into two main categories
Primitive Data Types
Primitive data types are predefined by the language and named by a keyword.
There are eight primitive data types supported by Java.
byte Data Type
The byte data type is an 8-bit signed two's complement integer with a minimum
value of -128 to 127.
The default value of a byte variable is 0, which is used to save space in large
arrays
Ex byte a = 100; byte b = -50;
Reference/Object Data Types
short Data Type
The short data type is a 16-bit signed two's complement integer, which provides
a range of values from -32,768 to 32,767.
The default value for a short variable is 0.
Ex short s = 10000; short r = -20000;
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 6
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
int Data Type
The int data type is a 32-bit signed two's complement integer, allowing for a
wide range of values from -2,147,483,648 to 2,147,483,647.
The default value for an int variable is 0.
Ex int a = 100000; int b = -200000;
long Data Type
The long data type is a 64-bit signed two's complement integer, capable of
representing a vast range of values from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
The default value is 0L.
Ex. long a = 100000L; long b = -200000L;
float Data Type
It is particularly useful for saving memory in large arrays of floating-point
numbers. Its default value is 0.0f.
Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
Ex float f1 = 234.5f;
double Data Type
The double data type in Java is a primitive data type that represents double-
precision 64-bit IEEE 754 floating-point numbers.
Its default value is 0.0d.
Stores fractional numbers. Sufficient for storing 15 to 16 decimal digits
Ex double d1 = 123.4;
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 7
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
boolean Data Type
the boolean data type represents a single bit of information with two possible
states: true or false. It is used to store the result of logical expressions or
conditions
Ex boolean a=false;
char Data Type
The char data type in Java is a primitive data type that represents a single 16-bit
Unicode character.
Ex char c = 'A';
The char data type is commonly used to represent characters, such as letters,
digits, and symbols, in Java programs.
Non-Primitive Data Types
The non-primitive data types are not predefined.
The reference data types are created using defined constructors of the classes.
They are used to access objects.
The following are the non-primitive (reference/object) data types
String: The string is a class in Java, and it represents the sequences of
characters.
Arrays: Arrays are created with the help of primitive data types and store
multiple values of the same type.
Classes: The classes are the user-defined data types and consist of variables
and methods.
Interfaces: The interfaces are abstract types that are used to specify a set of
methods.
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 8
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
2.4 Typecasting.
Typecasting in Java is the process of converting one data type to another data
type using the casting operator.
When you assign a value from one primitive data type to another type, this is
known as type casting.
To enable the use of a variable in a specific manner, this method requires
explicitly instructing the Java compiler to treat a variable of one data type as a
variable of another data type.
Syntax:
<datatype> variableName = (<datatype>) value;
Types of Type Casting
There are two types of Type Casting in java:
Widening Type Casting
A lower data type is transformed into a higher one by a process known as
widening type casting. Implicit type casting and casting down are some names
for it. It occurs naturally. Since there is no chance of data loss, it is secure.
Widening Type casting occurs when:
The target type must be larger than the source type.
Both data types must be compatible with each other.
Syntax: larger_data_type variable_name = smaller_data_type_variable;
Narrow Type Casting
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 9
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
The process of downsizing a bigger data type into a smaller one is known as
narrowing type casting.
Narrowing type casting is unsafe because data loss might happen due to the
lower data type’s smaller range of permitted values.
Syntax:
smaller_data_type variable_name = (smaller_data_type)
larger_data_type_variable;
Ex double i = 100.245; int k = (int)i;
2.5 Arithmetic operators, Relational operators
Arithmetic operators
These operators involve the mathematical operators that can be used to
perform various simple or advanced arithmetic operations on the primitive data
types referred to as the operands.
These operators consist of various unary and binary operators that can be
applied on a single or two operands.
1. Addition(+): This operator is a binary operator and is used to add two
operands.
2. Subtraction(-): This operator is a binary operator and is used to subtract
two operands.
3. Multiplication(*): This operator is a binary operator and is used to multiply
two operands.
4. Division(/): This is a binary operator that is used to divide the first
operand(dividend) by the second operand(divisor) and give the quotient as a
result.
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 10
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
5. Modulus(%): This is a binary operator that is used to return the remainder
when the first operand(dividend) is divided by the second operand(divisor).
Relational operators
Relational Operators are a bunch of binary operators used to check for relations
between two operands, including equality, greater than, less than, etc.
They return a boolean result after the comparison and are extensively used in
looping statements as well as conditional if-else statements and so on.
‘Equal to’ operator (==)
This operator is used to check whether the two given operands are equal or not
‘Not equal to’ Operator (!=)
It returns true if the operand at the left-hand side is not equal to the right-hand
side, else false.
Greater than’ operator (>)
This checks whether the first operand is greater than the second operand or
not.
‘Less than’ Operator (<)
This checks whether the first operand is less than the second operand or not.
Greater than or equal to (>=)
This checks whether the first operand is greater than or equal to the second
operand or not.
Less than or equal to (<=)
This checks whether the first operand is less than or equal to the second
operand or not.
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 11
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
2.6 Logical operators, Assignment operators
Logical operators
Logical operators are used to manipulate boolean values. There are three types
of logical operators in Java:
AND (&&): The AND operator returns true if both the operands are true,
otherwise it returns false.
Ex. int x = 5, y = 7;
if (x > 3 && y < 10) {
System.out.println("Both conditions are true");
OR (||): The OR operator returns true if at least one of the operands is true,
otherwise it returns false.
Ex. int x = 5, y = 7;
if (x > 10 || y < 10) {
System.out.println("At least one condition is true");
NOT (!): The NOT operator is used to reverse the value of a boolean expression.
If the expression is true, the NOT operator returns false, and if the expression is
false, the NOT operator returns true.
Ex. boolean x = true;
if (!x) { System.out.println("The value of x is false"); } else {
System.out.println("The value of x is true"); }
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 12
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
Assignment operators
These operators are used to assign values to a variable. The left side operand of
the assignment operator is a variable, and the right side operand of the
assignment operator is a value.
Types of Assignment Operators
1. Simple Assignment Operator: The Simple Assignment Operator is used
with the “=” sign where the left side consists of the operand and the right side
consists of a value.
Ex int a=10;
2. Compound Assignment Operator: The Compound Operator is used where
+,-,*, and / is used along with the = operator.
+= operator:
This operator is a compound of ‘+’ and ‘=’ operators. It operates by adding the
current value of the variable on the left to the value on the right and then
assigning the result to the operand on the left.
Ex. num1 += num2;
-= operator:
This operator is a compound of ‘-‘ and ‘=’ operators. It operates by subtracting
the variable’s value on the right from the current value of the variable on the
left and then assigning the result to the operand on the left.
Ex. num1 -= num2;
*= operator:
This operator is a compound of ‘*’ and ‘=’ operators. It operates by multiplying
the current value of the variable on the left to the value on the right and then
assigning the result to the operand on the left.
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 13
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
Ex. num1 *= num2;
/= operator:
This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the
current value of the variable on the left by the value on the right and then
assigning the quotient to the operand on the left.
Ex. num1 /= num2;
%= operator:
This operator is a compound of ‘%’ and ‘=’ operators. It operates by dividing the
current value of the variable on the left by the value on the right and then
assigning the remainder to the operand on the left.
Ex.
num1 %= num2;
int a = 10;
int b = 20;
System.out.println("a+b= " + (a += b) );
System.out.println("a-b = " + (a += b) );
System.out.println("a*b= " + (a *= b) );
System.out.println("a/b = " + (a /= b) );
System.out.println("a%b = " + (a %= b) );
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 14
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
2.7 Increment & Decrement operators, conditional operators
Increment & Decrement operators
The increment (++) and decrement (–) operators are unary operators in Java,
which means they operate on a single operand.
They are used to increase or decrease the value of an integer, floating-point, or
character variable by 1.
These operators can be applied in two ways
Prefix Increment and Decrement Operators
In the prefix form, the operator is placed before the operand. The value of the
operand is incremented or decremented first, and then the result is used in the
expression.
Ex. ++variable; --variable;
Postfix Increment and Decrement Operators
n the postfix form, the operator is placed after the operand. The value of the
operand is used in the expression first, and then it is incremented or
decremented.
Ex. variable++; variable--;
public static void main(String []args){
int a = 5,b=5;
b += ++a;
System.out.println("a: " + a + ", b: " + b);
b -= a++;
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 15
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
System.out.println("a: " + a + ", b: " + b);
b *= --a;
System.out.println("a: " + a + ", b: " + b);
b /= a--;
System.out.println("a: " + a + ", b: " + b);
conditional operators
conditional operators check the condition and decides the desired result on the
basis of both conditions.
Types of Conditional Operator
Conditional AND
The operator is applied between two Boolean expressions. It is denoted by the
two AND operators (&&). It returns true if and only if both expressions are true,
else returns false.
Conditional OR
The operator is applied between two Boolean expressions. It is denoted by the
two OR operator (||). It returns true if any of the expression is true, else returns
false.
public static void main(String args[])
int x=5, y=4, z=7;
System.out.println(x>y && x>z || y<z);
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 16
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
System.out.println((x<z || y>z) && x<y);
Ternary Operator
The meaning of ternary is composed of three parts. T
The ternary operator (? :) consists of three operands.
It is used to evaluate Boolean expressions.
The operator decides which value will be assigned to the variable.
It can be used instead of the if-else statement. It makes the code much more
easy, readable, and shorter.
Syntax: variable = (condition)? expression1: expression2
public static void main(String args[])
int x=69;
int y=89;
int z=79;
int largestNumber= (x > y) ? (x > z ? x : z) : (y > z ? y : z);
System.out.println("The largest numbers is: "+largestNumber);
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 17
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
2.8 Bitwise operators
Bitwise operator works on bits and performs bit-by-bit operation.
Ex a=60 128 64 32 16 8 4 2 1
In binary 0 0 1 1 1 1 0 0
There are six types of the bitwise operator
Bitwise AND (&)
It is a binary operator denoted by the symbol &. It returns 1 if and only if both
bits are 1, else returns 0.
Bitwise exclusive OR (^)
It is a binary operator denoted by the symbol ^ (pronounced as caret). It
returns 0 if both bits are the same, else returns 1.
Bitwise inclusive OR (|)
It is a binary operator denoted by the symbol | (pronounced as a pipe). It
returns 1 if either of the bit is 1, else returns 0.
Bitwise Complement (~)
It is a unary operator denoted by the symbol ~ (pronounced as the tilde). It
returns the inverse or complement of the bit. It makes every 0 a 1 and every 1 a
0.
Bit Shift Operators
Shift operator is used in shifting the bits either right or left. We can use shift
operators if we divide or multiply any number by 2.
Java provides the following types of shift operators:
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 18
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
Signed Right Shift Operator (>>)
The signed right shift operator shifts a bit pattern of a number towards the right
with a specified number of positions and fills 0.
The operator is denoted by the symbol >>.
It also preserves the leftmost bit (sign bit).
If 0 is presented at the leftmost bit, it means the number is positive.
If 1 is presented at the leftmost bit, it means the number is negative.
public static void main(String []args){
int b= 256 >> 3;
=256/ (2*2*2) =256/8= 32
System.out.println("b: " + b);
Output 32
Signed Left Shift Operator (<<)
The signed left shift operator (<<) shifts a bit pattern to the left. It is
represented by the symbol <<. It also preserves the leftmost bit (sign bit). It
does not preserve the sign bit.
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 19
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
if we write a<<n, it means to shift the bits of a number toward the left with
specified position (n).
Ex. 20 << 3
20*(2*2*2) = 20*8 = 160
Unsigned Right Shift Operator (>>>)
It shifts a zero at the leftmost position and fills 0. It is denoted by the symbol
>>>
int x = 20;
System.out.println("x>>>2 = " + (x >>>2));
Output: 5
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 20
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
2.9 Arithmetic Expressions, Evaluation of Expressions
Arithmetic Expressions
An assignment statement or expression changes the value that is held in a
variable.
Java Arithmetic expressions use arithmetic operators such as +, -, /, *, and %.
The % operator is the remainder or modulo operator.
Arithmetic expressions are used to assign arithmetic values to variables.
An expression is a combination of literals, operators, variables, and parentheses
used to calculate a value.
int x, y, z; // Three integer variables declared at the same time.
x = 10;
y = 12;
z = y / x; // z is assigned the value of x+y expression
Evaluation of Expressions
Evaluation of expressions refers to the process by which the Java Virtual
Machine (JVM) computes the result of an expression following Java's rules of
operator precedence, associativity, and type promotion.
Evaluate an expression represented by a String. The expression can contain
parentheses, you can assume parentheses are well-matched.
Java evaluates expressions according to operator precedence (which operator
comes first) and associativity (left to right or right to left evaluation). type
promotion Converts smaller data types to larger ones during evaluation
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 21
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
public static void main(String[] args) {
int a = 5, b = 3, c = 2;
boolean result = (a * b > 10) && (b + c < 10);
System.out.println(result);
2.10 Type Conversions in Expressions
Type Promotion in Expressions
While evaluating expressions, the intermediate value may exceed the range of
operands and hence the expression value will be promoted. Some conditions for
type promotion are:
Java automatically promotes each byte, short, or char operand to int when
evaluating an expression.
If one operand is long, float or double the whole expression is promoted to long,
float, or double respectively.
public static void main(String []args){
// Declaring and initializing primitive types
int i = 50;
float f = 5.67f;
// The Expression
double result = (f * i) + (i / f) - (i * f);
System.out.printf("%,.2f ", result);
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 22
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
Explicit Type Casting in Expressions
While evaluating expressions, the result is automatically updated to a larger
data type of the operand. But if we store that result in any smaller data type it
generates a compile-time error, due to which we need to typecast the result.
public static void main(String []args){
int a=40;
byte b=7;
// Type casting int to byte
b = (byte)((a*2)+(a+b));
// Display value in byte
System.out.println(b);
2.11 Operator Precedence & Associativity.
When various operators are used within the same statement a problem arises
which is which operation should be performed first.
Operator Precedence is a set of rules that defines the priority for all the
operators present in a programming language.
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 23
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
The operation which has an operator with the highest priority will be executed
first.
Ex. a= 4+5/10;
if we solve the addition first then the answer will be 9/10=0.9
if we solve the division first then the answer will be 4 + 0.5 = 4.5
Out of this the second answer is a valid answer because the precedence of
division is more than addition.
Operators Associativity
() [] . Left to Right
! ~ ++ -- + - Right to Left
*/% Left to Right
+- Left to Right
< > <= >= Left to Right
== != Left to Right
&& Left to Right
= += -= *= /= %= Right to Left
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 24
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
2.12 Decision Making with Control Statements,
Decision-making statements in Java execute a block of code based on a
condition.
A programming language uses control statements to control the flow of
execution of a program based on certain conditions.
if Statement
The if statement is the most simple decision-making statement.
If a certain condition is true then a block of statements is executed otherwise
not.
Syntax
if(condition) {
statement 1; //executes when condition is true
If-else statement
The if-else statement is an extension to the if-statement, which uses another
block of code, i.e., else block.
The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 25
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
else{
statement 2; //executes when condition is false
If-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if
statements.
We can also define an else statement at the end of the chain.
Syntax
if(condition 1) {
statement 1; //executes when condition 1 is true
else if(condition 2) {
statement 2; //executes when condition 2 is true
else {
statement 2; //executes when all the conditions are false
Nested if-statement
nested if-statements, the if statement can contain a if or if-else statement inside
another if or else-if statement.
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 26
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
Syntax
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
else{
statement 2; //executes when condition 2 is false
Switch Statement:
Switch statements are similar to if-else-if statements.
The switch statement contains multiple blocks of code called cases and a single
case is executed based on the variable which is being switched.
Cases cannot be duplicate
Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
Break statement terminates the switch block when the condition is satisfied.
Ex. int num = 2;
switch (num){
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 27
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
Output: 2
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 28
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
2.13 Looping Statements, Jump in loops, Labelled loops.
Loop statements are used to execute the set of instructions in a repeated order.
The execution of the set of instructions depends upon a particular condition.
There are three types of loops
for loop
It enables us to initialize the loop variable, check the condition, and
increment/decrement in a single line of code.
We use the for loop only when we exactly know the number of times, we want
to execute the block of code.
Syntax:
for(initialization, condition, increment/decrement) {
while loop
if we don't know the number of iterations in advance, it is recommended to use
a while loop.
It is also known as the entry-controlled loop since the condition is checked at
the start of the loop. If the condition is true, then the loop body will be executed.
Syntax
while(condition){
do-while loop
The do-while loop checks the condition at the end of the loop after executing the
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 29
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
loop statements.
When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in
first time.
Syntax:
do
} while (condition);
Ex.
int i = 10;
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 30
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
Jump in loops
Jump statements are used to transfer the control of the program to the specific
statements.
There are two types of jump statements in Java
break statement
The break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement.
The break statement cannot be used independently in the Java program, i.e., it
can only be written inside the loop or switch statement.
Ex. public static void main(String[] args) {
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
continue statement
The continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.
Ex. public static void main(String[] args) {
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 31
Notes: Object Oriented Programming using Java (SBCAST1151), Class: BCA FY,
Unit II: Constants, Variables and Data Types
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue; }
System.out.println(j); } } }
Labelled loops
A label is a valid variable name that denotes the name of the loop to where the
control of execution should jump.
To label a loop, place the label before the loop with a colon at the end.
a loop with the label is called a labeled loop.
int i, j;
inner:for(j=1;j<=10;j++)
{ System.out.print(j);
if(j==5)
break inner;
Thank You!
Prepared by: Mr. G.P.Shinde , COCSIT Latur Page 32