SlideShare a Scribd company logo
Lesson:
Java Operators
Cracking the Coding Interview in JAVA - Foundation
Pre-Requisites:
List of Concepts Involved:
Topic 1: Java Operators
1.Java Arithmetic operators:
Java Basic syntax for input and output
Data types
Variables
Identifiers
Keywords
Operators
Operators precedence and associativity.
Operators are the symbols that are used to perform pre-defined operations on variables and values
(commonly referred to as operands). As soon as the compiler encounters an operator, it performs the specific
mathematical or logical operation and returns the result.



Let us learn and understand about the relevant operators in detail.



Operators in Java can be classified into 6 types:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Unary Operators
Bitwise Operators
Arithmetic operators are used in mathematical expressions in a program. They function in the same way as
they do in algebra. 

The following table lists the arithmetic operators: 

Assume integer variable num1 holds a value of 20, variable num2 holds a value of 30 and num3 holds a value
of 30, then:
Cracking the Coding Interview in JAVA - Foundation
Let us now write a simple program to implement all the operators.You may try it yourself too !



Example:

class Main {

public static void main(String[] args) {





int p = 20, q = 10;

int result;





result=p+q;

System.out.println(result);





System.out.println(p - q); 



System.out.println(p * q);



System.out.println(p / q);





System.out.println(p % q);

}

}
// declare variables p and q
// addition operator
// subtraction operator
// we can directly perform subtraction in print statement,no need 

// to use result variable here 

// multiplication operator
// division operator

// modulo operator
Cracking the Coding Interview in JAVA - Foundation
2.Java Relational Operators:
Output

30

10

200

2

0
Relational operators compare numeric, character string, or logical data. The result of the comparison, either
true ( 1 ) or false ( 0 ), can be used to make a decision regarding program flow. The table below enlists
relational operators used in Java.
Let us write a program to implement all of these.


class Main {



public static void main(String[] args) {

int p = 10, q = 15;

System.out.println(p == q); // false

System.out.println(p != q); // true

System.out.println(p > q); // false

System.out.println(p < q); // true

System.out.println(p >= q); // false

System.out.println(p <= q); // true

}

}
// create variables

// == operator

// != operator

// > operator

// < operator

// >= operator

// <= operator
Cracking the Coding Interview in JAVA - Foundation
3.Java Logical Operators
Output

false

true

false

true

false

true
Logical operators are used for decision making. This class of operators is used to check whether an expression
is true or false. Some of the commonly used logical operators are mentioned in the table below.
Let us look at the following program to understand it better.


Example code:

class Main {

public static void main(String[] args) {





int p=15,q=10,r=5;

System.out.println((p > q) && (p > r)); // true

System.out.println((p > q) && (p < r)); // false





System.out.println((r < q) || (p < q)); // true

System.out.println((p > q) || (q > r)); // true

System.out.println((p < q) || (p < r)); // false





System.out.println(!(p == q)); // true

System.out.println(!(p > q)); // false

}

}


Output:

true

false

true

true

false

true

false
// && operator
// || operator
// ! operator
Cracking the Coding Interview in JAVA - Foundation
4.Java assignment operators:
The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer
element given by its left-hand operand. Confused? Don’t worry, we have you covered here.

Let's have a look at some of the commonly used assignment operators available in Java with examples.
Try out the following example for better understanding.


Example code:

class Main {

public static void main(String[] args) {



int p = 10;

int q;



q = p;

System.out.println(q); // value of q is 10



q += p;

System.out.println(q); // value of q is 20





q *= p;

System.out.println(q); // value of q is 200

}

}


Output:

10

20

200
// assign value using =

// assign value using =+

// assign value using =*
Cracking the Coding Interview in JAVA - Foundation
5.Java Unary Operators:
Question: Is there any performance difference between x+=y and x=x+y?

Solution: Yes, x+=y performs better than x=x+y.

Eg. x += 10 means
Find the place identified by x
Add 10 to it

And x = x + 10 means
Evaluate x+10
Find the place(memory) identified by the variable x
Copy x into an accumulator (accumulator is a part of CPU for temporary storage)
Add 10 to the accumulator
Store the result in variable x
Find the place (memory) identified by x
Copy the accumulator(result) to it


Hence, clearly x=+10 is better than x=x+10 since evaluation is direct with no intermediate steps for CPU to
perform.



Let us look at the next class of operators.
Interestingly, unlike the normal operators seen so far, java unary operators need only one operand to perform
operations like increment, decrement, negation, etc.

The table below will help you understand it in a better way.
For example:

class Main {

public static void main(String[] args) {





int p = 5;

System.out.println("Post-Increment Operator");

System.out.println(p++); // 5

// initialize p
// / p's value is incremented to 6 after returning current value i.e; 5
Cracking the Coding Interview in JAVA - Foundation
6.Java Bitwise operators:
int q = 5;

System.out.println("Pre-Increment Operator");

System.out.println(++q); //6



}

}


Output:

Post-Increment Operator

5

Pre-Increment Operator

6
// initialized to 5

// q is incremented to 6 and then it's value is returned
Interestingly, unlike the normal operators seen so far, java unary operators need only one operand to perform
operations like increment, decrement, negation, etc.

The table below will help you understand it in a better way.
Let's look at a simple code to understand the working of these operators.



Example code:


class Main {

public static void main(String[] args) {



int p = 5;

System.out.println(p<<2); 

}

}
// initialize p

// Shifting the value of p towards the left two positions
Cracking the Coding Interview in JAVA - Foundation
Output 20

Explanation:

Shifting the value of p towards the left (two positions) will make the leftmost 2 bits to be lost. The value of p is 5.
The binary representation of 5 is 00000101(we will learn about this conversion in the forthcoming lecture).

After 2 left shifts, binary representation of p will be 00010100 which is equivalent to 20.



Now that we have learnt about all types of operators, its a good time to explore the precedence/priority of each
of these wrt each other in different scenarios.
Topic : Java Operator Precedence and Associativity
Operator precedence determines the order/sequence of evaluation of operators in an expression (analogous
to BODMAS concept in maths). 


Take a look at the statement below:

int ans = 10 - 4 * 2;


What will be the value of variable ans? Will it be (10 - 4)*2, that is, 12? Or it will be 10 - (4 * 2), that is, 2?


When two operators share a common operand (4 in this case), the operator with the highest precedence is
operated upon first. In java, the precedence of * is higher than that of -. Hence, multiplication is performed
before subtraction, and hence the final value of the variable ans will be 2.


Associativity of Operators in Java

A question arises here, what if the precedence of all operators in an expression is same? In that case, the
concept of associativity comes into picture.


Associativity specifies the order in which operators are evaluated by the compiler, which can be left to right or
right to left. For example, in the phrase p = q = r = 10, the assignment operator is used from right to left. It means
that the value 10 is assigned to r, then r is assigned to q, and at last, q is assigned to p. This phrase can be
parenthesized as (p = (q = (r = 10))).
Cracking the Coding Interview in JAVA - Foundation
Operator Precedence in Java (Highest to Lowest)
Let us try a few questions on precedence and associativity to clear the air of confusion.



Example 1.

Let say we have 4 variables of type int ; p,q,r,s



s = p-++r-++q;

is equivalent to


Answer: s = p-(++r)-(++q);


Explanation: The operator precedence of prefix ++ is higher than that of - subtraction operator.


Example 2. What does the following code fragment print?


System.out.println(4 + 2 + "pqr");

System.out.println("pqr" + 4 + 2);



Answer: 6pqr and pqr42, respectively. 


Explanation: The + operator is left-to-right associative, whether it is string concatenation or simple number
addition.
Cracking the Coding Interview in JAVA - Foundation
Example 3: What is the result of the following code fragment? Explain.


boolean p = false;

boolean q = false;

boolean r = true;

System.out.println(p == q == r);



Answer: It prints true. 


Explanation: The equality operator is left-to-right associative, so p == q evaluates to true and this result is
compared to r, which yields true.



This brings us to the end of the lecture !

Keep Learning ! Keep Exploring !!
Upcoming Class Teaser
Java conditionals
if/else
switch
Ad

More Related Content

Similar to 4.Lesson Plan - Java Operators.pdf...pdf (20)

C operators
C operatorsC operators
C operators
GPERI
 
INTRODUCTION TO C PROGRAMMING - PART 2
INTRODUCTION TO C PROGRAMMING - PART 2INTRODUCTION TO C PROGRAMMING - PART 2
INTRODUCTION TO C PROGRAMMING - PART 2
JEENA SARA VIJU
 
Operators in java
Operators in javaOperators in java
Operators in java
Madishetty Prathibha
 
Basic_Java_02.pptx
Basic_Java_02.pptxBasic_Java_02.pptx
Basic_Java_02.pptx
Kajal Kashyap
 
object oriented programming java lectures
object oriented programming java lecturesobject oriented programming java lectures
object oriented programming java lectures
MSohaib24
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Operators in java
Operators in javaOperators in java
Operators in java
Then Murugeshwari
 
UNIT 2 programming in java_operators.pptx
UNIT 2 programming in java_operators.pptxUNIT 2 programming in java_operators.pptx
UNIT 2 programming in java_operators.pptx
jijinamt
 
MODULE_2_Operators.pptx
MODULE_2_Operators.pptxMODULE_2_Operators.pptx
MODULE_2_Operators.pptx
VeerannaKotagi1
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
2013 bookmatter learn_javaforandroiddevelopment
2013 bookmatter learn_javaforandroiddevelopment2013 bookmatter learn_javaforandroiddevelopment
2013 bookmatter learn_javaforandroiddevelopment
CarlosPineda729332
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
malekaanjum1
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
venud11
 
UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
Guide to Java.pptx
Guide to Java.pptxGuide to Java.pptx
Guide to Java.pptx
PrathamVaishnav1
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++
Praveen M Jigajinni
 
Operators
OperatorsOperators
Operators
loidasacueza
 
Ppt chapter06
Ppt chapter06Ppt chapter06
Ppt chapter06
Richard Styner
 
C operators
C operatorsC operators
C operators
GPERI
 
INTRODUCTION TO C PROGRAMMING - PART 2
INTRODUCTION TO C PROGRAMMING - PART 2INTRODUCTION TO C PROGRAMMING - PART 2
INTRODUCTION TO C PROGRAMMING - PART 2
JEENA SARA VIJU
 
object oriented programming java lectures
object oriented programming java lecturesobject oriented programming java lectures
object oriented programming java lectures
MSohaib24
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
UNIT 2 programming in java_operators.pptx
UNIT 2 programming in java_operators.pptxUNIT 2 programming in java_operators.pptx
UNIT 2 programming in java_operators.pptx
jijinamt
 
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2Core Java Programming | Data Type | operator | java Control Flow| Class 2
Core Java Programming | Data Type | operator | java Control Flow| Class 2
Sagar Verma
 
2013 bookmatter learn_javaforandroiddevelopment
2013 bookmatter learn_javaforandroiddevelopment2013 bookmatter learn_javaforandroiddevelopment
2013 bookmatter learn_javaforandroiddevelopment
CarlosPineda729332
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
venud11
 
UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
Operators and Expressions in C++
Operators and Expressions in C++Operators and Expressions in C++
Operators and Expressions in C++
Praveen M Jigajinni
 

Recently uploaded (20)

ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Raish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdfRaish Khanji GTU 8th sem Internship Report.pdf
Raish Khanji GTU 8th sem Internship Report.pdf
RaishKhanji
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
fluke dealers in bangalore..............
fluke dealers in bangalore..............fluke dealers in bangalore..............
fluke dealers in bangalore..............
Haresh Vaswani
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)AI-assisted Software Testing (3-hours tutorial)
AI-assisted Software Testing (3-hours tutorial)
Vəhid Gəruslu
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Ad

4.Lesson Plan - Java Operators.pdf...pdf

  • 2. Cracking the Coding Interview in JAVA - Foundation Pre-Requisites: List of Concepts Involved: Topic 1: Java Operators 1.Java Arithmetic operators: Java Basic syntax for input and output Data types Variables Identifiers Keywords Operators Operators precedence and associativity. Operators are the symbols that are used to perform pre-defined operations on variables and values (commonly referred to as operands). As soon as the compiler encounters an operator, it performs the specific mathematical or logical operation and returns the result. Let us learn and understand about the relevant operators in detail. Operators in Java can be classified into 6 types: Arithmetic Operators Relational Operators Logical Operators Assignment Operators Unary Operators Bitwise Operators Arithmetic operators are used in mathematical expressions in a program. They function in the same way as they do in algebra. The following table lists the arithmetic operators: Assume integer variable num1 holds a value of 20, variable num2 holds a value of 30 and num3 holds a value of 30, then:
  • 3. Cracking the Coding Interview in JAVA - Foundation Let us now write a simple program to implement all the operators.You may try it yourself too ! Example: class Main { public static void main(String[] args) { int p = 20, q = 10; int result; result=p+q; System.out.println(result); System.out.println(p - q); System.out.println(p * q); System.out.println(p / q); System.out.println(p % q); } } // declare variables p and q // addition operator // subtraction operator // we can directly perform subtraction in print statement,no need // to use result variable here // multiplication operator // division operator // modulo operator
  • 4. Cracking the Coding Interview in JAVA - Foundation 2.Java Relational Operators: Output 30 10 200 2 0 Relational operators compare numeric, character string, or logical data. The result of the comparison, either true ( 1 ) or false ( 0 ), can be used to make a decision regarding program flow. The table below enlists relational operators used in Java. Let us write a program to implement all of these. class Main { public static void main(String[] args) { int p = 10, q = 15; System.out.println(p == q); // false System.out.println(p != q); // true System.out.println(p > q); // false System.out.println(p < q); // true System.out.println(p >= q); // false System.out.println(p <= q); // true } } // create variables // == operator // != operator // > operator // < operator // >= operator // <= operator
  • 5. Cracking the Coding Interview in JAVA - Foundation 3.Java Logical Operators Output false true false true false true Logical operators are used for decision making. This class of operators is used to check whether an expression is true or false. Some of the commonly used logical operators are mentioned in the table below. Let us look at the following program to understand it better. Example code: class Main { public static void main(String[] args) { int p=15,q=10,r=5; System.out.println((p > q) && (p > r)); // true System.out.println((p > q) && (p < r)); // false System.out.println((r < q) || (p < q)); // true System.out.println((p > q) || (q > r)); // true System.out.println((p < q) || (p < r)); // false System.out.println(!(p == q)); // true System.out.println(!(p > q)); // false } } Output: true false true true false true false // && operator // || operator // ! operator
  • 6. Cracking the Coding Interview in JAVA - Foundation 4.Java assignment operators: The assignment operator = assigns the value of its right-hand operand to a variable, a property, or an indexer element given by its left-hand operand. Confused? Don’t worry, we have you covered here. Let's have a look at some of the commonly used assignment operators available in Java with examples. Try out the following example for better understanding. Example code: class Main { public static void main(String[] args) { int p = 10; int q; q = p; System.out.println(q); // value of q is 10 q += p; System.out.println(q); // value of q is 20 q *= p; System.out.println(q); // value of q is 200 } } Output: 10 20 200 // assign value using = // assign value using =+ // assign value using =*
  • 7. Cracking the Coding Interview in JAVA - Foundation 5.Java Unary Operators: Question: Is there any performance difference between x+=y and x=x+y? Solution: Yes, x+=y performs better than x=x+y. Eg. x += 10 means Find the place identified by x Add 10 to it And x = x + 10 means Evaluate x+10 Find the place(memory) identified by the variable x Copy x into an accumulator (accumulator is a part of CPU for temporary storage) Add 10 to the accumulator Store the result in variable x Find the place (memory) identified by x Copy the accumulator(result) to it Hence, clearly x=+10 is better than x=x+10 since evaluation is direct with no intermediate steps for CPU to perform. Let us look at the next class of operators. Interestingly, unlike the normal operators seen so far, java unary operators need only one operand to perform operations like increment, decrement, negation, etc. The table below will help you understand it in a better way. For example: class Main { public static void main(String[] args) { int p = 5; System.out.println("Post-Increment Operator"); System.out.println(p++); // 5 // initialize p // / p's value is incremented to 6 after returning current value i.e; 5
  • 8. Cracking the Coding Interview in JAVA - Foundation 6.Java Bitwise operators: int q = 5; System.out.println("Pre-Increment Operator"); System.out.println(++q); //6 } } Output: Post-Increment Operator 5 Pre-Increment Operator 6 // initialized to 5 // q is incremented to 6 and then it's value is returned Interestingly, unlike the normal operators seen so far, java unary operators need only one operand to perform operations like increment, decrement, negation, etc. The table below will help you understand it in a better way. Let's look at a simple code to understand the working of these operators. Example code: class Main { public static void main(String[] args) { int p = 5; System.out.println(p<<2); } } // initialize p // Shifting the value of p towards the left two positions
  • 9. Cracking the Coding Interview in JAVA - Foundation Output 20 Explanation: Shifting the value of p towards the left (two positions) will make the leftmost 2 bits to be lost. The value of p is 5. The binary representation of 5 is 00000101(we will learn about this conversion in the forthcoming lecture). After 2 left shifts, binary representation of p will be 00010100 which is equivalent to 20. Now that we have learnt about all types of operators, its a good time to explore the precedence/priority of each of these wrt each other in different scenarios. Topic : Java Operator Precedence and Associativity Operator precedence determines the order/sequence of evaluation of operators in an expression (analogous to BODMAS concept in maths). Take a look at the statement below: int ans = 10 - 4 * 2; What will be the value of variable ans? Will it be (10 - 4)*2, that is, 12? Or it will be 10 - (4 * 2), that is, 2? When two operators share a common operand (4 in this case), the operator with the highest precedence is operated upon first. In java, the precedence of * is higher than that of -. Hence, multiplication is performed before subtraction, and hence the final value of the variable ans will be 2. Associativity of Operators in Java A question arises here, what if the precedence of all operators in an expression is same? In that case, the concept of associativity comes into picture. Associativity specifies the order in which operators are evaluated by the compiler, which can be left to right or right to left. For example, in the phrase p = q = r = 10, the assignment operator is used from right to left. It means that the value 10 is assigned to r, then r is assigned to q, and at last, q is assigned to p. This phrase can be parenthesized as (p = (q = (r = 10))).
  • 10. Cracking the Coding Interview in JAVA - Foundation Operator Precedence in Java (Highest to Lowest) Let us try a few questions on precedence and associativity to clear the air of confusion. Example 1. Let say we have 4 variables of type int ; p,q,r,s s = p-++r-++q; is equivalent to Answer: s = p-(++r)-(++q); Explanation: The operator precedence of prefix ++ is higher than that of - subtraction operator. Example 2. What does the following code fragment print? System.out.println(4 + 2 + "pqr"); System.out.println("pqr" + 4 + 2); Answer: 6pqr and pqr42, respectively. Explanation: The + operator is left-to-right associative, whether it is string concatenation or simple number addition.
  • 11. Cracking the Coding Interview in JAVA - Foundation Example 3: What is the result of the following code fragment? Explain. boolean p = false; boolean q = false; boolean r = true; System.out.println(p == q == r); Answer: It prints true. Explanation: The equality operator is left-to-right associative, so p == q evaluates to true and this result is compared to r, which yields true. This brings us to the end of the lecture ! Keep Learning ! Keep Exploring !! Upcoming Class Teaser Java conditionals if/else switch