Operators and Control Statements in Java : Arithmetic Operators, Unary Operators, Relational
Operators, Logical Operators, Boolean Operators, Bitwise Operators, Ternary Operators, New
Operator, Cast Operator, If .... else statement, Switch statement, Break statement, Continue
statement, Return statement, do ... while loop, while loop, for loop.
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
Java Programming Operators and Control Statements Guide
1. Introduction to Java Programming Language
UNIT-III
[Operators and Control Statements in Java : Arithmetic Operators, Unary Operators, Relational Operators,
Logical Operators, Boolean Operators, Bitwise Operators, Ternary Operators, New Operator, Cast Operator,
If .... else statement, Switch statement, Break statement, Continue statement, Return statement, do ... while
loop, while loop, for loop.]
Arithmetic Operator
The Java programming language provides operators that perform addition, subtraction,
multiplication, and division. One operator is modulus or ramainder operator "%", which divides one
operand by another and returns the remainder as its result.
Example
class ArithmeticDemo {
public static void main (String[] args) {
int result = 1 + 2;
// result is now 3
System.out.println("1 + 2 = " + result);
int original_result = result;
result = result 1;
// result is now 2
System.out.println(original_result + " 1 = " + result);
original_result = result;
result = result * 2;
// result is now 4
System.out.println(original_result + " * 2 = " + result);
original_result = result;
result = result / 2;
// result is now 2
System.out.println(original_result + " / 2 = " + result);
original_result = result;
Provided By Shipra Swati, PSCET
2. Introduction to Java Programming Language
result = result + 8;
// result is now 10
System.out.println(original_result + " + 8 = " + result);
original_result = result;
result = result % 7;
// result is now 3
System.out.println(original_result + " % 7 = " + result);
}
}
OUTPUT
1 + 2 = 3
3 - 1 = 2
2 * 2 = 4
4 / 2 = 2
2 + 8 = 10
10 % 7 = 3
Unary Operators
The unary operators require only one operand; they perform various operations such as
incrementing/decrementing a value by one, negating an expression, or inverting the value of a
boolean.
Example
class UnaryDemo {
public static void main(String[] args) {
int result = +1;
Provided By Shipra Swati, PSCET
3. Introduction to Java Programming Language
// result is now 1
System.out.println(result);
result;
// result is now 0
System.out.println(result);
result++;
// result is now 1
System.out.println(result);
result = result;
// result is now 1
System.out.println(result);
boolean success = false;
// false
System.out.println(success);
// true
System.out.println(!success);
}
}
OUTPUT
1
0
1
-1
false
true
Relational Operators
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
Provided By Shipra Swati, PSCET
4. Introduction to Java Programming Language
Example
class ComparisonDemo {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if(value1 == value2)
System.out.println("value1 == value2");
if(value1 != value2)
System.out.println("value1 != value2");
if(value1 > value2)
System.out.println("value1 > value2");
if(value1 < value2)
System.out.println("value1 < value2");
if(value1 <= value2)
System.out.println("value1 <= value2");
}
}
Output
value1 != value2
value1 < value2
value1 <= value2
Logical Operators
Logical operators are used when we want to check multiple conditions together. Lets assume
operand1 and operand2 be relational expressions or boolean types. The logical operators and
principals of their operations are given below:
Operator Meaning Operation
&&
Logical
AND
Result of “operand1 && operand2” will be
1. “true” only if both operand1 and operand2 are “true”
2. “false” if any of the operands (operand1 or operand2) is “false” or
both the operands (operand1 or operand2) are “false”.
||
Logical
OR
Result of the operation “operand1 || operand2” will be
1. “true” if any of the operands (operand1 or operand2) is “true” or
both the operands (operand1 or operand2) are “true”.
2. “false” only if both operand1 and operand2 are “false”
!
Logical
Not
1. Assume the original value is “true”. If we use this operator, the
value will be changed to “false”.
2. Assume the original value is “false”. If we use this operator, the
value will be changed to “true”.
Provided By Shipra Swati, PSCET
5. Introduction to Java Programming Language
Example
public class LogicalDemo {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
Output
a && b = false
a || b = true
!(a && b) = true
Boolean Operators
These operators are also called Boolean Logical Operators. The Boolean logical operators are : |, &,
^, !. These operators act on Boolean operands according to this table
A B A|B A&B A^B !A
false false false false false true
true false true false true false
false true true false true true
true true true true false false
| the OR operator
& the AND operator
^ the XOR operator
! the NOT operator
Example:
class BoolDemo{
public static void main(String args[]){
// these are boolean variables
boolean A = true;
boolean B = false;
//these are int variables
int c = 6;
Provided By Shipra Swati, PSCET
6. Introduction to Java Programming Language
int d = 4;
System.out.println("A|B = "+(A|B));
System.out.println("A||B = "+(A|B));
System.out.println("c|d = "+(c|d));
System.out.println("A&B = "+(A&B));
System.out.println("A&&B = "+(A&B));
System.out.println("c&d = "+(c&d));
System.out.println("!A = "+(!A));
System.out.println("A^B = "+(A^B));
System.out.println("c^d = "+(c^d));
}
}
Output
A|B = true
A||B = true
c|d = 6
A&B = false
A&&B = false
c&d = 4
!A = false
A^B = true
c^d = 2
Boolean AND (&) or Boolean OR (|) can work with integers but Logical AND (&&) or Logical OR
(||) can not.
& and | provide the same outcome as the && and || operators in case of boolean operands. The
difference is that they (& and |) always evaluate both sides of the expression where as && and ||
stop evaluating if the first condition is enough to determine the outcome. So, logical operators are
also called short-circuiting. Following code blocks explains the idea of short-circuit:
int x = 0;
if (false && (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); // "0"
In the value printed to the console of x will be 0, because the first operand in the if statement is
false, hence java has no need to compute (1 == ++x) therefore x will not be computed.
Provided By Shipra Swati, PSCET
7. Introduction to Java Programming Language
int x = 0;
if (false & (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); //"1"
Now, the expression (1 == ++x) will be executed, even though the left operand is false. Hence the
value printed out for x will be 1 because it got incremented.
Bitwise Operators
These operators perform bitwise and bit shift operations on integral types. The operators discussed
in this section are less commonly used.
The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of
the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains
8 bits; applying this operator to a value whose bit pattern is "00000000" would change its
pattern to "11111111".
The signed left shift operator "<<" shifts a bit pattern to the left,
The signed right shift operator ">>" shifts a bit pattern to the right.
The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-
hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while
the leftmost position after ">>"depends on sign extension.
The bitwise & operator performs a bitwise AND operation.
The bitwise ^ operator performs a bitwise exclusive OR operation.
The bitwise | operator performs a bitwise inclusive OR operation.
Example
class BitwiseDemo {
public static void main(String args[]) {
int a = 10; /* 10 = 0000 1010 */
int b = 4; /* 04 = 0000 0100 */
int c = 0;
c = a & b; /* 0 = 0000 0000 */
System.out.println("a & b = " + c );
c = a | b; /* 14 = 0000 1110 */
System.out.println("a | b = " + c );
Provided By Shipra Swati, PSCET
8. Introduction to Java Programming Language
c = a ^ b; /* = 0000 0000 */
System.out.println("a ^ b = " + c );
c = ~a; /*11 = 1111 0101 */
System.out.println("~a = " + c );
c = a << 2; /* 40 = 0010 1000 */
System.out.println("a << 2 = " + c );
c = a >> 2; /* 2 = 0000 0010 */
System.out.println("a >> 2 = " + c );
c = a >>> 2; /* 2 = 0000 0010 */
System.out.println("a >>> 2 = " + c );
}
}
Output
a & b = 0
a | b = 14
a ^ b = 14
~a = -11
a << 2 = 40
a >> 2 = 2
a >>> 2 = 2
Ternary Operators
Ternay operator, also known as the conditional operator, uses two symblos ? And : and uses three
operands. This operator can be thought of shorthand for an if-then-else statement. Below is the
basic syntax of ternary operator in java:
condition ? trueStatement : falseStatement
Condition : First part is the condition section.
TrueStatement : Second is the code block which executes in case of first part condition
goes true.
FalseStatement : The Third part code block executes if condition results as false.
Examples
public class TernaryDemo {
public static void main(String[] args) {
int a = 10;
int b = 20;
String result = a > b ? "a is greater" : "b is greater";
Provided By Shipra Swati, PSCET
9. Introduction to Java Programming Language
System.out.println(result);
}
}
Output
b is greater
Ternary operator can be nested also.
New Operator
Creating object in java is a two step process:
1. Declaring a variable of user defined class
class_name var_name;
2. Instantiation and Initialization
The new operator instantiates a class by dynamically allocating (i.e, allocation at run time) memory
for a new object and returning a reference to that memory. This reference is then stored in the
variable var_name. The new operator is also followed by a call to a class constructor, which
initializes the new object.
Example: Consider a class definition given below:
class Box{
double width;
double height;
double depth;
}
Box mybox; // This declaration will create a reference in memoery which currently points to nothing.
mybox = new Box; // the variable name, mybox, contains a reference pointing to Box object)
Provided By Shipra Swati, PSCET
10. Introduction to Java Programming Language
Hence declaration of a class variable, instantiation of a class and initialization of an object of class
can be together illustrated as follows :
Assigning Reference to another object:
Provided By Shipra Swati, PSCET
11. Introduction to Java Programming Language
Since arrays are object in java, hence while instantiating arrays, we use new operator. For
example:
int arr[] = new int[5];
Java’s primitive types (int, float etc) are not implemented as objects. Rather, they are
implemented as “normal” variables. So, they do not need to use new operator for
instantiation.
Cast Operator
Assigning a value of one type to a variable of another type is known as Type Casting.
Example :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,
Widening Casting(Implicit)
Narrowing Casting(Explicitly done)
Widening or Automatic type converion: Automatic Type casting take place when,
the two types are compatible
the target type is larger than the source type
Provided By Shipra Swati, PSCET
12. Introduction to Java Programming Language
Example :
public class Test {
public static void main(String[] args) {
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
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
Narrowing or Explicit type conversion: When you are assigning a larger type value to a variable
of smaller type, then you need to perform explicit type casting.
Example :
public class Test {
public static void main(String[] args) {
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
Output :
Double value 100.04
Long value 100
Int value 100
Provided By Shipra Swati, PSCET
13. Introduction to Java Programming Language
If .... else statement
It is one of the control flow statements, which help to execute a certain section of code only if a
particular test evaluates to true.
Example:
The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a
score of 90% or above, a B for a score of 80% or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
Output
Grade = C
*** Notes: The opening and closing braces are optional, provided that the block contains only one
statement.
Switch statement
Unlike if-else statements, the switch statement can have a number of possible execution paths,
which will be executed when corresponding condition is true.
Example:
The following code example, SwitchDemo, declares an int named month whose value represents a
month. The code displays the name of the month, based on the value of month, using the switch
statement.
Provided By Shipra Swati, PSCET
14. Introduction to Java Programming Language
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
Output
August
The body of a switch statement is known as a switch block. A statement in the switch block can be
labeled with one or more case or default labels. The switch statement evaluates its expression, then
executes all statements that follow the matching case label. Each break statement terminates the
enclosing switch statement. Control flow continues with the first statement following the switch
block.
Provided By Shipra Swati, PSCET
15. Introduction to Java Programming Language
do ... while loop
do-while statement can be expressed as follows:
do {
statement(s)
} while (expression);
The while statement evaluates expression, which must return a boolean value. If the expression
evaluates to true, the do-while block is executed again. The while statement continues testing the
expression and executing its block until the expression evaluates to false.
Example
Using do-while loop to print the values from 1 through 10.
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
Output
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
while loop
The while statement continually executes a block of statements while a particular condition is true.
Its syntax can be expressed as:
while (expression) {
statement(s)
}
Provided By Shipra Swati, PSCET
16. Introduction to Java Programming Language
Example:
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11) {
System.out.println("Count is: " + count);
count++;
}
}
}
Output
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
for loop
The for statement provides a compact way to iterate over a range of values. Programmers often
refer to it as the "for loop" because of the way in which it repeatedly loops until a particular
condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
statement(s)
}
The initialization expression initializes the loop; it's executed once, as the loop begins.
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly
acceptable for this expression to increment or decrement a value.
Example:
The following program, ForDemo, uses the general form of the for statement to print the numbers 1
through 10 to standard output:
Provided By Shipra Swati, PSCET
17. Introduction to Java Programming Language
class ForDemo {
public static void main(String[] args){
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
Output
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Break statement
The Java break is used to break loop or switch statement. It breaks the current flow of the program
at specified condition. In case of inner loop, it breaks only inner loop.
Example
public class BreakDemo {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
}
}
Output
1
2
3
4
Provided By Shipra Swati, PSCET
18. Introduction to Java Programming Language
Continue statement
The Java continue statement is used to continue loop. It continues the current flow of the program
and skips the remaining code at specified condition. In case of inner loop, it continues only inner
loop.
Example
public class ContinueDemo {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
System.out.println(i);
}
}
}
Output
1
2
3
4
6
7
8
9
10
Return statement
The return statement immediately terminates the method in which it is executed. This topic will be
covered, when function in java will be discussed in Unit-8.
Provided By Shipra Swati, PSCET