This document discusses operators in Java, including assignment, arithmetic, relational, and logical operators. It provides examples of using various operators and discusses some key points about operator precedence and equality testing. Specifically, it covers compound assignment operators, relational operators for comparison, and how equality is determined for primitives and object references. It also notes some topics about operators that are no longer covered on the Java certification exam.
Core Java introduction | Basics | free course Kernel Training
http://kerneltraining.com/core-java/
Learn the basics of Java and gain practical experience that is required to begin your career in java programming. Kernel Training has designed classroom and online course to upgrade your knowledge and skills in core Java.
Course Curriculum:
Introduction to Java
JDK and practical applications
Java Basic Data Types and Operators
Programming Constructs, Classes and Methods, constructor and Finalizer
Polymorphism
Inheritance
Method overriding and abstract classes
Packages and Interfaces
Strings and Arrays
Enums
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.
OCA Java SE 8 Exam Chapter 2 Operators & Statementsİbrahim Kürce
Operators in Java include unary, binary, and ternary operators that perform operations on operands. Binary operators like arithmetic, relational, and logical operators follow an order of precedence unless overridden by parentheses. Statements in Java include if-then, if-then-else, switch, while, do-while, for, and more to control program flow. The if-then statement and if-then-else statement evaluate conditions and execute code blocks conditionally. The switch statement compares a value to multiple case labels and executes the corresponding code block.
This document provides an introduction to the Java programming language. It discusses Java's evolution and history from 1991 to present. It also covers Java fundamentals including data types, operators, decision making and looping constructs, classes and objects, arrays and strings. The document is intended as an overview of the major topics and features in Java.
1. James Gosling and his team at Sun Microsystems started developing Java in 1990 as a simpler language than C++ for writing programs to control consumer electronics. They named the new language "Oak" in 1991, later changing it to "Java" in 1995.
2. The Java team realized Java would be well-suited for web programming as the internet was becoming more graphical. They developed the concept of web applets to embed small programs in web pages.
3. Key benefits of Java include being simple and object-oriented, platform independence allowing programs to run on any system with a Java Virtual Machine, and strong security features that help protect against viruses and hackers.
The document discusses various operators in Java including mathematical, assignment, increment/decrement, relational, logical, ternary, string and casting operators. It provides examples of using each operator and notes precedence rules and other behaviors like type promotion and truncation versus rounding during casting.
This document provides an introduction to programming in C, specifically covering operators and expressions, data input and output functions, and control statements. It discusses various operators in C like arithmetic, relational, logical, and assignment operators. It also describes common library functions for input like scanf and output like printf that allow entering and displaying data. Finally, it discusses control statements for branching and looping flow control.
The document provides information about Java programming concepts including:
- How to download, install Java, and write a simple "Hello World" program.
- Common operators in Java like arithmetic, assignment, logical, and comparison operators.
- How to compile and run a Java program from the command line.
- Core Java concepts like variables, data types, classes, and methods.
- The document is intended as an introduction to Java programming for beginners.
Variable is a name for a memory location that can store data of different types. There are three types of variables in Java: local variables which are declared within methods and can only be used locally, instance variables which are declared within a class but outside methods and can be accessed by any instance method, and static variables which have a single copy shared among all instances of a class.
This document provides an overview of object oriented programming topics including arrays and Java operators. It discusses single and multi-dimensional arrays, how to declare, create, initialize, and index arrays. It also covers the different types of Java operators such as assignment, arithmetic, relational, logical, and bitwise operators. Examples are provided to demonstrate how to use arrays and each type of operator in Java code.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
Operators in Java provide symbols that operate on arguments to produce results. The document discusses the different types of operators in Java including assignment, arithmetic, relational, logical, bitwise, and ternary operators. Examples are provided to demonstrate the usage of various operators like increment/decrement, arithmetic, relational, logical, bitwise, ternary, and instanceof operators in Java code.
Java defines several categories of operators: arithmetic, bitwise, relational, logical, and additional special operators. The increment and decrement operators ++ and -- increase or decrease a variable by 1. Relational operators determine the relationship between two operands and return a boolean. Control statements like if-else and switch allow a program to select or loop execution paths. Parentheses can be used to alter operator precedence or clarify complex expressions.
Core Java Programming | Data Type | operator | java Control Flow| Class 2Sagar Verma
This document provides an introduction to Java programming concepts including:
- Data types like primitives, classes, and objects
- Variables, identifiers, and naming conventions
- Control structures like if/else statements and loops
- Arrays and array initialization
- Methods and built-in classes
- Import statements and packages
- Output with System.out.println
It covers these concepts over multiple pages with examples and explanations of Java syntax and semantics.
This document provides solutions to exercises from Chapters 1 through 14 of a Java textbook. It presents solutions for 28 different exercises involving Java concepts like classes, objects, inheritance, polymorphism, and interfaces. Each solution is a code listing or brief explanation.
Operators and expressions are fundamental concepts in Python programming. The document discusses various types of operators used to manipulate operands, including arithmetic, comparison, assignment, logical, bitwise, and membership operators. It also covers expressions, which are combinations of operators and operands that evaluate to a value. Several types of expressions are described, such as constant, arithmetic, integral, floating, relational, logical, bitwise, and combinational expressions. Control flow statements like if, if-else, if-elif-else are also covered, along with looping using for and while loops and the break, continue, and pass statements.
The document discusses different ways to declare variables in JavaScript. There are three main keywords: var, let, and const. Var declares variables with function scope, let declares block-scoped variables, and const declares block-scoped variables that cannot be reassigned.
Here you can watch my ppt and learn the guide about java and its every part. Later on, I will make one more ppt on many programs and keywords and how to use them, I hope you like this presentation.
Thank you
This document discusses operators and expressions in C++. It begins by defining operators as symbols that represent operations and operands as the objects involved in those operations. It then covers various types of operators in C++ like arithmetic, relational, logical, and conditional operators. It provides examples of using each operator and notes order of precedence. The document also discusses expressions, noting they are combinations of operators, constants, and variables. It provides examples of integer, real, relational, and logical expressions. Finally, it discusses mathematical functions available in the C++ standard library header file math.h that can be used in arithmetic expressions.
The document summarizes the different types of operators in Java, including arithmetic, relational, conditional, and bitwise operators. It provides examples of each type of operator and how they are used in Java code. The main types of operators covered are assignment, arithmetic, unary, relational, conditional, type comparison, and bitwise/bit shift operators. Examples are given to demonstrate how each operator is used and the output it produces.
This document discusses control structures in Java including logical operators, truth tables, nested if/else statements, loops, and testing control structures. It defines logical operators like AND, OR, and NOT and how they are used to construct complex Boolean expressions. It also covers nested control structures, loop verification techniques like assertions, and best practices for testing loops and conditionals.
ELectronics Boards & Product Testing_Shiju.pdfShiju Jacob
This presentation provides a high level insight about DFT analysis and test coverage calculation, finalizing test strategy, and types of tests at different levels of the product.
This document provides an introduction to programming in C, specifically covering operators and expressions, data input and output functions, and control statements. It discusses various operators in C like arithmetic, relational, logical, and assignment operators. It also describes common library functions for input like scanf and output like printf that allow entering and displaying data. Finally, it discusses control statements for branching and looping flow control.
The document provides information about Java programming concepts including:
- How to download, install Java, and write a simple "Hello World" program.
- Common operators in Java like arithmetic, assignment, logical, and comparison operators.
- How to compile and run a Java program from the command line.
- Core Java concepts like variables, data types, classes, and methods.
- The document is intended as an introduction to Java programming for beginners.
Variable is a name for a memory location that can store data of different types. There are three types of variables in Java: local variables which are declared within methods and can only be used locally, instance variables which are declared within a class but outside methods and can be accessed by any instance method, and static variables which have a single copy shared among all instances of a class.
This document provides an overview of object oriented programming topics including arrays and Java operators. It discusses single and multi-dimensional arrays, how to declare, create, initialize, and index arrays. It also covers the different types of Java operators such as assignment, arithmetic, relational, logical, and bitwise operators. Examples are provided to demonstrate how to use arrays and each type of operator in Java code.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
The document discusses Java architecture and fundamentals. It can be summarized as:
1. Java's architecture consists of four main components: the Java programming language, Java class files, the Java API, and the Java Virtual Machine (JVM).
2. When a Java program is written and run, it uses these four technologies. The program is written in Java source code and compiled to class files, which are then run on the JVM along with the Java API library.
3. The JVM handles execution by using areas like the method area for bytecode storage, the Java stack for method calls and parameters, and the heap for object instantiation and garbage collection.
Operators in Java provide symbols that operate on arguments to produce results. The document discusses the different types of operators in Java including assignment, arithmetic, relational, logical, bitwise, and ternary operators. Examples are provided to demonstrate the usage of various operators like increment/decrement, arithmetic, relational, logical, bitwise, ternary, and instanceof operators in Java code.
Java defines several categories of operators: arithmetic, bitwise, relational, logical, and additional special operators. The increment and decrement operators ++ and -- increase or decrease a variable by 1. Relational operators determine the relationship between two operands and return a boolean. Control statements like if-else and switch allow a program to select or loop execution paths. Parentheses can be used to alter operator precedence or clarify complex expressions.
Core Java Programming | Data Type | operator | java Control Flow| Class 2Sagar Verma
This document provides an introduction to Java programming concepts including:
- Data types like primitives, classes, and objects
- Variables, identifiers, and naming conventions
- Control structures like if/else statements and loops
- Arrays and array initialization
- Methods and built-in classes
- Import statements and packages
- Output with System.out.println
It covers these concepts over multiple pages with examples and explanations of Java syntax and semantics.
This document provides solutions to exercises from Chapters 1 through 14 of a Java textbook. It presents solutions for 28 different exercises involving Java concepts like classes, objects, inheritance, polymorphism, and interfaces. Each solution is a code listing or brief explanation.
Operators and expressions are fundamental concepts in Python programming. The document discusses various types of operators used to manipulate operands, including arithmetic, comparison, assignment, logical, bitwise, and membership operators. It also covers expressions, which are combinations of operators and operands that evaluate to a value. Several types of expressions are described, such as constant, arithmetic, integral, floating, relational, logical, bitwise, and combinational expressions. Control flow statements like if, if-else, if-elif-else are also covered, along with looping using for and while loops and the break, continue, and pass statements.
The document discusses different ways to declare variables in JavaScript. There are three main keywords: var, let, and const. Var declares variables with function scope, let declares block-scoped variables, and const declares block-scoped variables that cannot be reassigned.
Here you can watch my ppt and learn the guide about java and its every part. Later on, I will make one more ppt on many programs and keywords and how to use them, I hope you like this presentation.
Thank you
This document discusses operators and expressions in C++. It begins by defining operators as symbols that represent operations and operands as the objects involved in those operations. It then covers various types of operators in C++ like arithmetic, relational, logical, and conditional operators. It provides examples of using each operator and notes order of precedence. The document also discusses expressions, noting they are combinations of operators, constants, and variables. It provides examples of integer, real, relational, and logical expressions. Finally, it discusses mathematical functions available in the C++ standard library header file math.h that can be used in arithmetic expressions.
The document summarizes the different types of operators in Java, including arithmetic, relational, conditional, and bitwise operators. It provides examples of each type of operator and how they are used in Java code. The main types of operators covered are assignment, arithmetic, unary, relational, conditional, type comparison, and bitwise/bit shift operators. Examples are given to demonstrate how each operator is used and the output it produces.
This document discusses control structures in Java including logical operators, truth tables, nested if/else statements, loops, and testing control structures. It defines logical operators like AND, OR, and NOT and how they are used to construct complex Boolean expressions. It also covers nested control structures, loop verification techniques like assertions, and best practices for testing loops and conditionals.
ELectronics Boards & Product Testing_Shiju.pdfShiju Jacob
This presentation provides a high level insight about DFT analysis and test coverage calculation, finalizing test strategy, and types of tests at different levels of the product.
Raish Khanji GTU 8th sem Internship Report.pdfRaishKhanji
This report details the practical experiences gained during an internship at Indo German Tool
Room, Ahmedabad. The internship provided hands-on training in various manufacturing technologies, encompassing both conventional and advanced techniques. Significant emphasis was placed on machining processes, including operation and fundamental
understanding of lathe and milling machines. Furthermore, the internship incorporated
modern welding technology, notably through the application of an Augmented Reality (AR)
simulator, offering a safe and effective environment for skill development. Exposure to
industrial automation was achieved through practical exercises in Programmable Logic Controllers (PLCs) using Siemens TIA software and direct operation of industrial robots
utilizing teach pendants. The principles and practical aspects of Computer Numerical Control
(CNC) technology were also explored. Complementing these manufacturing processes, the
internship included extensive application of SolidWorks software for design and modeling tasks. This comprehensive practical training has provided a foundational understanding of
key aspects of modern manufacturing and design, enhancing the technical proficiency and readiness for future engineering endeavors.
Passenger car unit (PCU) of a vehicle type depends on vehicular characteristics, stream characteristics, roadway characteristics, environmental factors, climate conditions and control conditions. Keeping in view various factors affecting PCU, a model was developed taking a volume to capacity ratio and percentage share of particular vehicle type as independent parameters. A microscopic traffic simulation model VISSIM has been used in present study for generating traffic flow data which some time very difficult to obtain from field survey. A comparison study was carried out with the purpose of verifying when the adaptive neuro-fuzzy inference system (ANFIS), artificial neural network (ANN) and multiple linear regression (MLR) models are appropriate for prediction of PCUs of different vehicle types. From the results observed that ANFIS model estimates were closer to the corresponding simulated PCU values compared to MLR and ANN models. It is concluded that the ANFIS model showed greater potential in predicting PCUs from v/c ratio and proportional share for all type of vehicles whereas MLR and ANN models did not perform well.
The Fluke 925 is a vane anemometer, a handheld device designed to measure wind speed, air flow (volume), and temperature. It features a separate sensor and display unit, allowing greater flexibility and ease of use in tight or hard-to-reach spaces. The Fluke 925 is particularly suitable for HVAC (heating, ventilation, and air conditioning) maintenance in both residential and commercial buildings, offering a durable and cost-effective solution for routine airflow diagnostics.
We introduce the Gaussian process (GP) modeling module developed within the UQLab software framework. The novel design of the GP-module aims at providing seamless integration of GP modeling into any uncertainty quantification workflow, as well as a standalone surrogate modeling tool. We first briefly present the key mathematical tools on the basis of GP modeling (a.k.a. Kriging), as well as the associated theoretical and computational framework. We then provide an extensive overview of the available features of the software and demonstrate its flexibility and user-friendliness. Finally, we showcase the usage and the performance of the software on several applications borrowed from different fields of engineering. These include a basic surrogate of a well-known analytical benchmark function; a hierarchical Kriging example applied to wind turbine aero-servo-elastic simulations and a more complex geotechnical example that requires a non-stationary, user-defined correlation function. The GP-module, like the rest of the scientific code that is shipped with UQLab, is open source (BSD license).
Concept of Problem Solving, Introduction to Algorithms, Characteristics of Algorithms, Introduction to Data Structure, Data Structure Classification (Linear and Non-linear, Static and Dynamic, Persistent and Ephemeral data structures), Time complexity and Space complexity, Asymptotic Notation - The Big-O, Omega and Theta notation, Algorithmic upper bounds, lower bounds, Best, Worst and Average case analysis of an Algorithm, Abstract Data Types (ADT)
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