SlideShare a Scribd company logo
1 of 18
Download to read offline
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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

More Related Content

What's hot

Thirteen ways of looking at a turtle
Thirteen ways of looking at a turtleThirteen ways of looking at a turtle
Thirteen ways of looking at a turtleScott Wlaschin
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1Jomel Penalba
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming LanguageAhmad Idrees
 
Control structures i
Control structures i Control structures i
Control structures i Ahmad Idrees
 
Control structures functions and modules in python programming
Control structures functions and modules in python programmingControl structures functions and modules in python programming
Control structures functions and modules in python programmingSrinivas Narasegouda
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindPVS-Studio
 
DEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliksDEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliksFelipe Prado
 
Logical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by ProfessionalsLogical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by ProfessionalsPVS-Studio
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Courseparveen837153
 

What's hot (20)

Thirteen ways of looking at a turtle
Thirteen ways of looking at a turtleThirteen ways of looking at a turtle
Thirteen ways of looking at a turtle
 
Comp102 lec 5.1
Comp102   lec 5.1Comp102   lec 5.1
Comp102 lec 5.1
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
04 control structures 1
04 control structures 104 control structures 1
04 control structures 1
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
07 flow control
07   flow control07   flow control
07 flow control
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Control structures in C++ Programming Language
Control structures in C++ Programming LanguageControl structures in C++ Programming Language
Control structures in C++ Programming Language
 
Programming in Arduino (Part 1)
Programming in Arduino (Part 1)Programming in Arduino (Part 1)
Programming in Arduino (Part 1)
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Control structures i
Control structures i Control structures i
Control structures i
 
Exception handling
Exception handlingException handling
Exception handling
 
Java script session 4
Java script session 4Java script session 4
Java script session 4
 
Control structures functions and modules in python programming
Control structures functions and modules in python programmingControl structures functions and modules in python programming
Control structures functions and modules in python programming
 
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer HumankindAccord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
Accord.Net: Looking for a Bug that Could Help Machines Conquer Humankind
 
Control Structures: Part 1
Control Structures: Part 1Control Structures: Part 1
Control Structures: Part 1
 
DEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliksDEF CON 23 - Atlas - fun with symboliks
DEF CON 23 - Atlas - fun with symboliks
 
Logical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by ProfessionalsLogical Expressions in C/C++. Mistakes Made by Professionals
Logical Expressions in C/C++. Mistakes Made by Professionals
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 

Similar to Java Programming Operators and Control Statements Guide

The Awesome Python Class Part-3
The Awesome Python Class Part-3The Awesome Python Class Part-3
The Awesome Python Class Part-3Binay Kumar Ray
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++Praveen M Jigajinni
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and StringsIt Academy
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)jahanullah
 
Operators
OperatorsOperators
OperatorsKamran
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and StringsIt Academy
 
C operators
C operatorsC operators
C operatorsGPERI
 
4_A1208223655_21789_2_2018_04. Operators.ppt
4_A1208223655_21789_2_2018_04. Operators.ppt4_A1208223655_21789_2_2018_04. Operators.ppt
4_A1208223655_21789_2_2018_04. Operators.pptRithwikRanjan
 
C++ Expressions Notes
C++ Expressions NotesC++ Expressions Notes
C++ Expressions NotesProf Ansari
 

Similar to Java Programming Operators and Control Statements Guide (20)

Operators in java
Operators in javaOperators in java
Operators in java
 
05 operators
05   operators05   operators
05 operators
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
The Awesome Python Class Part-3
The Awesome Python Class Part-3The Awesome Python Class Part-3
The Awesome Python Class Part-3
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++
 
Chapter 3:Programming with Java Operators and Strings
Chapter 3:Programming with Java Operators and  StringsChapter 3:Programming with Java Operators and  Strings
Chapter 3:Programming with Java Operators and Strings
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
C Sharp Jn (2)
C Sharp Jn (2)C Sharp Jn (2)
C Sharp Jn (2)
 
Operators
OperatorsOperators
Operators
 
Py-Slides-2 (1).ppt
Py-Slides-2 (1).pptPy-Slides-2 (1).ppt
Py-Slides-2 (1).ppt
 
Py-Slides-2.ppt
Py-Slides-2.pptPy-Slides-2.ppt
Py-Slides-2.ppt
 
Py-Slides-2.ppt
Py-Slides-2.pptPy-Slides-2.ppt
Py-Slides-2.ppt
 
Chapter 3 : Programming with Java Operators and Strings
Chapter 3 : Programming with Java Operators and  StringsChapter 3 : Programming with Java Operators and  Strings
Chapter 3 : Programming with Java Operators and Strings
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
5_Operators.pdf
5_Operators.pdf5_Operators.pdf
5_Operators.pdf
 
C operators
C operatorsC operators
C operators
 
4_A1208223655_21789_2_2018_04. Operators.ppt
4_A1208223655_21789_2_2018_04. Operators.ppt4_A1208223655_21789_2_2018_04. Operators.ppt
4_A1208223655_21789_2_2018_04. Operators.ppt
 
Java - Operators
Java - OperatorsJava - Operators
Java - Operators
 
Java 2
Java 2Java 2
Java 2
 
C++ Expressions Notes
C++ Expressions NotesC++ Expressions Notes
C++ Expressions Notes
 

More from Shipra Swati

Operating System-Process Scheduling
Operating System-Process SchedulingOperating System-Process Scheduling
Operating System-Process SchedulingShipra Swati
 
Operating System-Concepts of Process
Operating System-Concepts of ProcessOperating System-Concepts of Process
Operating System-Concepts of ProcessShipra Swati
 
Operating System-Introduction
Operating System-IntroductionOperating System-Introduction
Operating System-IntroductionShipra Swati
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Shipra Swati
 
Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Shipra Swati
 
Fundamental of Information Technology
Fundamental of Information TechnologyFundamental of Information Technology
Fundamental of Information TechnologyShipra Swati
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process SynchronizationShipra Swati
 

More from Shipra Swati (20)

Operating System-Process Scheduling
Operating System-Process SchedulingOperating System-Process Scheduling
Operating System-Process Scheduling
 
Operating System-Concepts of Process
Operating System-Concepts of ProcessOperating System-Concepts of Process
Operating System-Concepts of Process
 
Operating System-Introduction
Operating System-IntroductionOperating System-Introduction
Operating System-Introduction
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Java unit 14
Java unit 14Java unit 14
Java unit 14
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Java unit 7
Java unit 7Java unit 7
Java unit 7
 
Java unit 2
Java unit 2Java unit 2
Java unit 2
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
OOPS_Unit_1
OOPS_Unit_1OOPS_Unit_1
OOPS_Unit_1
 
Ai lab manual
Ai lab manualAi lab manual
Ai lab manual
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7
 
Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6
 
Fundamental of Information Technology
Fundamental of Information TechnologyFundamental of Information Technology
Fundamental of Information Technology
 
Disk Management
Disk ManagementDisk Management
Disk Management
 
File Systems
File SystemsFile Systems
File Systems
 
Memory Management
Memory ManagementMemory Management
Memory Management
 
Deadlocks
DeadlocksDeadlocks
Deadlocks
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
 

Recently uploaded

OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacingjaychoudhary37
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 

Recently uploaded (20)

OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
microprocessor 8085 and its interfacing
microprocessor 8085  and its interfacingmicroprocessor 8085  and its interfacing
microprocessor 8085 and its interfacing
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
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