The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Now that you've learned how to declare and initialize variables, you probably want to know how to do something with them. Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands , and then return a result.

As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

Operators Precedence
postfix ++ --
unary -- + - ~ !
multiplicative
additive
shift
relational
equality
bitwise AND
bitwise exclusive OR
bitwise inclusive OR
logical AND
logical OR
ternary
assignment

In general-purpose programming, certain operators tend to appear more frequently than others; for example, the assignment operator " = " is far more common than the unsigned right shift operator " >>> ". With that in mind, the following discussion focuses first on the operators that you're most likely to use on a regular basis, and ends focusing on those that are less common. Each discussion is accompanied by sample code that you can compile and run. Studying its output will help reinforce what you've just learned.

About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights

Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.

  • Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Java Tutorial

Overview of Java

  • Introduction to Java
  • The Complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works - JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?

Basics of Java

  • Java Basic Syntax
  • Java Hello World Program
  • Java Data Types
  • Primitive data type vs. Object data type in Java with Examples
  • Java Identifiers

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

  • How to Take Input From User in Java?
  • Scanner Class in Java
  • Java.io.BufferedReader Class in Java
  • Difference Between Scanner and BufferedReader Class in Java
  • Ways to read input from console in Java
  • System.out.println in Java
  • Difference between print() and println() in Java
  • Formatted Output in Java using printf()
  • Fast I/O in Java in Competitive Programming

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples

Java Assignment Operators with Examples

  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods

Access Modifiers in Java

  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java

Inheritance in Java

Abstraction in java, encapsulation in java, polymorphism in java, interfaces in java.

  • 'this' reference in Java
  • Inheritance and Constructors in Java
  • Java and Multiple Inheritance
  • Interfaces and Inheritance in Java
  • Association, Composition and Aggregation in Java
  • Comparison of Inheritance in C++ and Java
  • abstract keyword in java
  • Abstract Class in Java
  • Difference between Abstract Class and Interface in Java
  • Control Abstraction in Java with Examples
  • Difference Between Data Hiding and Abstraction in Java
  • Difference between Abstraction and Encapsulation in Java with Examples
  • Difference between Inheritance and Polymorphism
  • Dynamic Method Dispatch or Runtime Polymorphism in Java
  • Difference between Compile-time and Run-time Polymorphism in Java

Constructors in Java

  • Copy Constructor in Java
  • Constructor Overloading in Java
  • Constructor Chaining In Java with Examples
  • Private Constructors and Singleton Classes in Java

Methods in Java

  • Static methods vs Instance methods in Java
  • Abstract Method in Java with Examples
  • Overriding in Java
  • Method Overloading in Java
  • Difference Between Method Overloading and Method Overriding in Java
  • Differences between Interface and Class in Java
  • Functional Interfaces in Java
  • Nested Interface in Java
  • Marker interface in Java
  • Comparator Interface in Java with Examples
  • Need of Wrapper Classes in Java
  • Different Ways to Create the Instances of Wrapper Classes in Java
  • Character Class in Java
  • Java.Lang.Byte class in Java
  • Java.Lang.Short class in Java
  • Java.lang.Integer class in Java
  • Java.Lang.Long class in Java
  • Java.Lang.Float class in Java
  • Java.Lang.Double Class in Java
  • Java.lang.Boolean Class in Java
  • Autoboxing and Unboxing in Java
  • Type conversion in Java with Examples

Keywords in Java

  • Java Keywords
  • Important Keywords in Java
  • Super Keyword in Java
  • final Keyword in Java
  • static Keyword in Java
  • enum in Java
  • transient keyword in Java
  • volatile Keyword in Java
  • final, finally and finalize in Java
  • Public vs Protected vs Package vs Private Access Modifier in Java
  • Access and Non Access Modifiers in Java

Memory Allocation in Java

  • Java Memory Management
  • How are Java objects stored in memory?
  • Stack vs Heap Memory Allocation
  • How many types of memory areas are allocated by JVM?
  • Garbage Collection in Java
  • Types of JVM Garbage Collectors in Java with implementation details
  • Memory leaks in Java
  • Java Virtual Machine (JVM) Stack Area

Classes of Java

  • Understanding Classes and Objects in Java
  • Singleton Method Design Pattern in Java
  • Object Class in Java
  • Inner Class in Java
  • Throwable Class in Java with Examples

Packages in Java

  • Packages In Java
  • How to Create a Package in Java?
  • Java.util Package in Java
  • Java.lang package in Java
  • Java.io Package in Java
  • Java Collection Tutorial

Exception Handling in Java

  • Exceptions in Java
  • Types of Exception in Java with Examples
  • Checked vs Unchecked Exceptions in Java
  • Java Try Catch Block
  • Flow control in try catch finally in Java
  • throw and throws in Java
  • User-defined Custom Exception in Java
  • Chained Exceptions in Java
  • Null Pointer Exception In Java
  • Exception Handling with Method Overriding in Java
  • Multithreading in Java
  • Lifecycle and States of a Thread in Java
  • Java Thread Priority in Multithreading
  • Main thread in Java
  • Java.lang.Thread Class in Java
  • Runnable interface in Java
  • Naming a thread and fetching name of current thread in Java
  • What does start() function do in multithreading in Java?
  • Difference between Thread.start() and Thread.run() in Java
  • Thread.sleep() Method in Java With Examples
  • Synchronization in Java
  • Importance of Thread Synchronization in Java
  • Method and Block Synchronization in Java
  • Lock framework vs Thread synchronization in Java
  • Difference Between Atomic, Volatile and Synchronized in Java
  • Deadlock in Java Multithreading
  • Deadlock Prevention And Avoidance
  • Difference Between Lock and Monitor in Java Concurrency
  • Reentrant Lock in Java

File Handling in Java

  • Java.io.File Class in Java
  • Java Program to Create a New File
  • Different ways of Reading a text file in Java
  • Java Program to Write into a File
  • Delete a File Using Java
  • File Permissions in Java
  • FileWriter Class in Java
  • Java.io.FileDescriptor in Java
  • Java.io.RandomAccessFile Class Method | Set 1
  • Regular Expressions in Java
  • Regex Tutorial - How to write Regular Expressions?
  • Matcher pattern() method in Java with Examples
  • Pattern pattern() method in Java with Examples
  • Quantifiers in Java
  • java.lang.Character class methods | Set 1
  • Java IO : Input-output in Java with Examples
  • Java.io.Reader class in Java
  • Java.io.Writer Class in Java
  • Java.io.FileInputStream Class in Java
  • FileOutputStream in Java
  • Java.io.BufferedOutputStream class in Java
  • Java Networking
  • TCP/IP Model
  • User Datagram Protocol (UDP)
  • Differences between IPv4 and IPv6
  • Difference between Connection-oriented and Connection-less Services
  • Socket Programming in Java
  • java.net.ServerSocket Class in Java
  • URL Class in Java with Examples

JDBC - Java Database Connectivity

  • Introduction to JDBC (Java Database Connectivity)
  • JDBC Drivers
  • Establishing JDBC Connection in Java
  • Types of Statements in JDBC
  • JDBC Tutorial
  • Java 8 Features - Complete Tutorial

Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide.

Types of Operators: 

  • Arithmetic Operators
  • Unary Operators
  • Assignment Operator
  • Relational Operators
  • Logical Operators
  • Ternary Operator
  • Bitwise Operators
  • Shift Operators

This article explains all that one needs to know regarding Assignment Operators. 

Assignment Operators

These operators are used to assign values to a variable. The left side operand of the assignment operator is a variable, and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. This means that the assignment operators have right to left associativity, i.e., the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side value must be declared before using it or should be a constant. The general format of the assignment operator is, 

Types of Assignment Operators in Java

The Assignment Operator is generally of two types. They are:

1. Simple Assignment Operator: The Simple Assignment Operator is used with the “=” sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

2. Compound Assignment Operator: The Compound Operator is used where +,-,*, and / is used along with the = operator.

Let’s look at each of the assignment operators and how they operate: 

1. (=) operator: 

This is the most straightforward assignment operator, which is used to assign the value on the right to the variable on the left. This is the basic definition of an assignment operator and how it functions. 

Syntax:  

Example:  

2. (+=) operator: 

This operator is a compound of ‘+’ and ‘=’ operators. It operates by adding the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

Note: The compound assignment operator in Java performs implicit type casting. Let’s consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5 Method 2: x += 4.5 As per the previous example, you might think both of them are equal. But in reality, Method 1 will throw a runtime error stating the “i ncompatible types: possible lossy conversion from double to int “, Method 2 will run without any error and prints 9 as output.

Reason for the Above Calculation

Method 1 will result in a runtime error stating “incompatible types: possible lossy conversion from double to int.” The reason is that the addition of an int and a double results in a double value. Assigning this double value back to the int variable x requires an explicit type casting because it may result in a loss of precision. Without the explicit cast, the compiler throws an error. Method 2 will run without any error and print the value 9 as output. The compound assignment operator += performs an implicit type conversion, also known as an automatic narrowing primitive conversion from double to int . It is equivalent to x = (int) (x + 4.5) , where the result of the addition is explicitly cast to an int . The fractional part of the double value is truncated, and the resulting int value is assigned back to x . It is advisable to use Method 2 ( x += 4.5 ) to avoid runtime errors and to obtain the desired output.

Same automatic narrowing primitive conversion is applicable for other compound assignment operators as well, including -= , *= , /= , and %= .

3. (-=) operator: 

This operator is a compound of ‘-‘ and ‘=’ operators. It operates by subtracting the variable’s value on the right from the current value of the variable on the left and then assigning the result to the operand on the left. 

4. (*=) operator:

 This operator is a compound of ‘*’ and ‘=’ operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

5. (/=) operator: 

This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the quotient to the operand on the left. 

6. (%=) operator: 

This operator is a compound of ‘%’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the remainder to the operand on the left. 

Please Login to comment...

Similar reads.

  • Java-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Boolean Logic

noahpgordon's avatar

One of the primitive data types in Java is the boolean . A boolean object takes a value of true or false .

Boolean logic describes how boolean values can be combined and manipulated. Java implements boolean logic through a set of operators and methods .

Boolean Logical Operators

The boolean logical operators available in Java are described in the following table:

Operator Symbol Syntax Behavior Equivalent Logical Concept
Returns if both arguments equal ; otherwise returns AND / Conjunction
Returns if at least one argument equals ; otherwise returns OR / Inclusive disjunction
Returns if the argument equals ; otherwise returns NOT / Negation
Returns if exactly one argument equals ; otherwise returns XOR / Exclusive disjunction

Boolean Logical Methods

The boolean logical methods available in Java are described in the following table:

Method Syntax Behavior Equivalent Logical Concept
Returns the result of AND / Conjunction
Returns the result of OR / Inclusive disjunction
Returns the result of XOR / Exclusive disjunction

Use in Conditionals

Boolean logic is commonly used within conditionals to control the flow of a program.

The following example illustrates the use of boolean logical operators within conditionals.

The above example gives following output:

All contributors

THE-Spellchecker's avatar

  • noahpgordon
  • THE-Spellchecker

Looking to contribute?

  • Learn more about how to get involved.
  • Edit this page on GitHub to fix an error or make an improvement.
  • Submit feedback to let us know how we can improve Docs.

Learn Java on Codecademy

Build basic android apps with java.

Java Booleans Explained [Easy Examples]

September 1, 2021

Introduction to Java booleans

Java Boolean is an inbuilt class that wraps are used for wrapping the value of primitive data type, i.e. boolean in an object. The boolean class contains two values, i.e. true or false . Java provides a wrapper class Boolean in java.lang package. The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field, whose type is boolean. In this tutorial, we will learn about java booleans in detail. We will see how we can use booleans in conditions, loops, and functions. Moreover, we will also cover some of the java operators that return a boolean value, along with examples. All in all, this will be one of the detailed tutorials about java booleans.

Getting started with Java booleans

The Boolean class is simply a wrapper class for the primitive type boolean. It wraps the boolean primitive value to an object. An object of type Boolean contains a single field whose type is boolean. The simple syntax of creating a boolean object from  a boolean class looks like this;

Now let us create a boolean object and then use it in our java code. See the example below:

Notice that we get true for the first three cases which means that the java boolean class is not case sensitive. It will return true does not matter which alphabetic case we use.  And it will return false if we provide an argument other than true , that is why for the last case we get false .

Logical operators and Java booleans

We know that the logical operators in Java return booleans value. You can learn more about logical operators . There are three logical operators in Java which are as follow:

  • &&  ; Return true if both the conditions are true.
  • || ; Return true if any of the conditions are true.
  • ! ; Return true if the condition is not true

Now, in this section, we will take examples of each of these operators and get a boolean value.

Example-1 AND operator and Java booleans

AND operator returns boolean value true if both the conditions are satisfied, otherwise, it will return the boolean value false . See the example below which uses the logical AND operator.

Notice that the logical AND operator only returns true if both the conditions are true , else it returns false .

Example-2 OR operator and Java booleans

Java logical OR operator returns true if any of the conditions are true and only returns false if all the conditions are false . See the example below:

Notice that we only get false when both of the conditions were False .

Example-3 NOT operator and Java booleans

NOT operator simply reverses the condition, which means if the condition is true , it will return false and if the condition is false it will return true . See the example below:

Notice that we get true for the False condition and vice versa.

Rational operators and Java booleans

Relational operator refers to the relationships that values or operands can have with one another. Java provides 6 relational operators for comparing numbers and characters. They are mostly used for comparison purposes. After the comparison, they return the result in boolean datatype. The rational operators in Java are listed below:

  • == : Return true if both the operands are equal.
  • !=  ; Return true if both the operands are not equal.
  • <  ; Return true if left-hand side operand is less than right side one.
  • >  ; Return true if right-hand side operand is less than left side one.
  • <= ; Return true if left side operand is less than or equal to right side one.
  • >=  ; Return true if right side operand is less than or equal to left side one.

In this section, we will take these rational operations and see how and when they return java booleans.

Example-1 Equal and not equal assignment operators and Java booleans

Equal to the operator ( == ) return true if both the operands are equal. It can be used to compare lists, int, float dict, strings, and other data types. While not equal to ( != ) operator returns true if both of the operands are not equal. It can also be used to compare various data types.

Now let us take an example and see how they are used to compare data types. See the example below:

Example-2 Greater than or less than operators and Java booleans

Greater than ( > ) operator returns true if the left side is greater than the right side one else, it returns false . Similarly, the less than ( < ) operator returns true if the left side is smaller than the right side one, else it will also return false .

See the example below which uses these operators.

Notice that we get the result accordingly.

Java booleans in conditional statements

One of the important uses of java booleans is in conditional statements. If the condition is true , the java statements inside the condition will be executed and if the condition is false then none of the statements inside the condition will be executed. So the java booleans are important parts of if-else statements. In this section, we will be discussing how the java booleans control the if-else statements in the java programming language.

Example-1 Direct use of java booleans

First, let us directly use the java booleans in our conditional statements so it will give us a depth understanding of how it works in if-else statements. See the example below:

Notice that the first condition was true so it was executed. Now if we make the first condition false , then the else statement will be executed. See the example below:

Example-2 Using conditions that return Java booleans

We already had discussed some of the java operators that return booleans in a couple of sections above. Now, let us see how we can use those operators in java conditions and executed the required statements only. See the example below:

Notice that the operators in the if and else if statements, return false because the conditions were false and it only executes the last statement.

Java booleans in while loop

Java while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. ... If the condition evaluates to true then we will execute the body of the loop and go to update expression inside the loop. In this section let us use java while loop with java booleans.

Example-1 Direct use of java booleans in while loop

If we use direct true in the while loop without any break statement or condition, it will be an infinity loop and if we use direct false in our while loop, then the loop will never be executed. See the example below which uses direct true boolean in while loop:

This is an infinity loop because the condition is never going to be false and we don't have any break statements as well. This kind of loop is prohibited in any programming language because it returns unexpected values. It is always recommended to use either break or conditional statements inside loops.

Now let us see what will happens if we use direct false booleans value while loop. See the example below:

This time we will get an error because we had used a direct the false boolean value and java will through an error saying that the code inside the loop is not reachable. See the error below:

Java Booleans Explained [Easy Examples]

Example-2 using condition in while loop

Now let us use a condition that returns true if it is true and returns false if it becomes false . See the example below:

Notice that as the condition was true , the loop was executing and as soon as the condition becomes false , the loop stops executing.

In Java, the boolean keyword is a primitive data type. It is used to store only two possible values, either true or false . It specifies 1-bit of information and its "size" can't be defined precisely. The boolean keyword is used with variables and methods. Its default value is false . It is generally associated with conditional statements. In this tutorial, we learned about java booleans in detail.

We learned how we can create a java boolean object from the boolean class in java by taking examples. Moreover, we also learned about the java operators that return boolean values depending on the condition and we also discussed how booleans play important role in java while loop. All in all, this tutorial, contains all the information that you need to start working with java booleans.

Further Reading

Java booleans Java booleans documentation Java operators

Bashir Alam

Bashir Alam

He is a Computer Science graduate from the University of Central Asia, currently employed as a full-time Machine Learning Engineer at uExel. His expertise lies in Python, Java, Machine Learning, OCR, text extraction, data preprocessing, and predictive models. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to [email protected]

Thank You for your support!!

Leave a Comment Cancel reply

Save my name and email in this browser for the next time I comment.

Notify me via e-mail if anyone answers my comment.

java boolean assignment

We try to offer easy-to-follow guides and tips on various topics such as Linux, Cloud Computing, Programming Languages, Ethical Hacking and much more.

Recent Comments

Popular posts, 7 tools to detect memory leaks with examples, 100+ linux commands cheat sheet & examples, tutorial: beginners guide on linux memory management, top 15 tools to monitor disk io performance with examples, overview on different disk types and disk interface types, 6 ssh authentication methods to secure connection (sshd_config), how to check security updates list & perform linux patch management rhel 6/7/8, 8 ways to prevent brute force ssh attacks in linux (centos/rhel 7).

Privacy Policy

HTML Sitemap

Java Tutorial

Java methods, java classes, java file handling, java how to's, java reference, java examples, java operators.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Try it Yourself »

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

Java divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example Try it
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

Advertisement

Java Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Java Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either true or false . These values are known as Boolean values , and you will learn more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator ( > ) to find out if 5 is greater than 3:

Operator Name Example Try it
== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

Java Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example Try it
&&  Logical and Returns true if both statements are true x < 5 &&  x < 10
||  Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Java Bitwise Operators

Bitwise operators are used to perform binary logic with the bits of an integer or long integer.

Operator Description Example Same as Result Decimal
& AND - Sets each bit to 1 if both bits are 1 5 & 1 0101 & 0001 0001  1
| OR - Sets each bit to 1 if any of the two bits is 1 5 | 1 0101 | 0001 0101  5
~ NOT - Inverts all the bits ~ 5  ~0101 1010  10
^ XOR - Sets each bit to 1 if only one of the two bits is 1 5 ^ 1 0101 ^ 0001 0100  4
<< Zero-fill left shift - Shift left by pushing zeroes in from the right and letting the leftmost bits fall off 9 << 1 1001 << 1 0010 2
>> Signed right shift - Shift right by pushing copies of the leftmost bit in from the left and letting the rightmost bits fall off 9 >> 1 1001 >> 1 1100 12
>>> Zero-fill right shift - Shift right by pushing zeroes in from the left and letting the rightmost bits fall off 9 >>> 1 1001 >>> 1 0100 4

Note: The Bitwise examples above use 4-bit unsigned examples, but Java uses 32-bit signed integers and 64-bit signed long integers. Because of this, in Java, ~5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010

In Java, 9 >> 1 will not return 12. It will return 4. 00000000000000000000000000001001 >> 1 will return 00000000000000000000000000000100

Test Yourself With Exercises

Multiply 10 with 5 , and print the result.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

T HIS SECTION TAKES A CLOSER LOOK at expressions. Recall that an expression is a piece of program code that represents or computes a value. An expression can be a literal, a variable, a function call, or several of these things combined with operators such as + and > . The value of an expression can be assigned to a variable, used as the output value in an output routine, or combined with other values into a more complicated expression. (The value can even, in some cases, be ignored, if that's what you want to do; this is more common than you might think.) Expressions are an essential part of programming. So far, these notes have dealt only informally with expressions. This section tells you the more-or-less complete story.

The basic building blocks of expressions are literals (such as 674 , 3.14 , true , and 'X' ), variables, and function calls. Recall that a function is a subroutine that returns a value. You've already seen some examples of functions: the input routines from the TextIO class and the mathematical functions from the Math class.

Literals, variables, and function calls are simple expressions. More complex expressions can be built up by using operators to combine simpler expressions. Operators include + for adding two numbers, > for comparing two values, and so on. When several operators appear in an expression, there is a question of precedence , which determines how the operators are grouped for evaluation. For example, in the expression " A + B * C ", B*C is computed first and then the result is added to A . We say that multiplication ( * ) has higher precedence than addition ( + ). If the default precedence is not what you want, you can use parentheses to explicitly specify the grouping you want. For example, you could use " (A + B) * C " if you want to add A to B first and then multiply the result by C .

The rest of this section gives details of operators in Java. The number of operators in Java is quite large, and I will not cover them all here. Most of the important ones are here; a few will be covered in later chapters as they become relevant.

Arithmetic operators include addition, subtraction, multiplication, and division. They are indicated by + , - , * , and / . These operations can be used on values of any numeric type: byte , short , int , long , float , or double . When the computer actually calculates one of these operations, the two values that it combines must be of the same type. If your program tells the computer to combine two values of different types, the computer will convert one of the values from one type to another. For example, to compute 37.4 + 10, the computer will convert the integer 10 to a real number 10.0 and will then compute 37.4 + 10.0. (The computer's internal representations for 10 and 10.0 are very different, even though people think of them as representing the same number.) Ordinarily, you don't have to worry about type conversion, because the computer does it automatically.

When two numerical values are combined (after doing type conversion on one of them, if necessary), the answer will be of the same type. If you multiply two ints , you get an int ; if you multiply two double s, you get a double . This is what you would expect, but you have to be very careful when you use the division operator / . When you divide two integers, the answer will always be an integer; if the quotient has a fractional part, it is discarded. For example, the value of 7/2 is 3 , not 3.5 . If N is an integer variable, then N/100 is an integer, and 1/N is equal to zero for any N greater than one! This fact is a common source of programming errors. You can force the computer to compute a real number as the answer by making one of the operands real: For example, when the computer evaluates 1.0/N , it first converts N to a real number in order to match the type of 1.0 , so you get a real number as the answer.

Java also has an operator for computing the remainder when one integer is divided by another. This operator is indicated by % . If A and B are integers, then A % B represents the remainder when A is divided by B . For example, 7 % 2 is 1 , while 34577 % 100 is 77 , and 50 % 8 is 2 . A common use of % is to test whether a given integer is even or odd. N is even if N % 2 is zero, and it is odd if N % 2 is 1 . More generally, you can check whether an integer N is evenly divisible by an integer M by checking whether N % M is zero.

Finally, you might need the unary minus operator, which takes the negative of a number. For example, -X has the same value as (-1)*X . For completeness, Java also has a unary plus operator, as in +X , even though it doesn't really do anything.

You'll find that adding 1 to a variable is an extremely common operation in programming. Subtracting 1 from a variable is also pretty common. You might perform the operation of adding 1 to a variable with assignment statements such as:

The effect of the assignment statement x = x + 1 is to take the old value of the variable x , compute the result of adding 1 to that value, and store the answer as the new value of x . The same operation can be accomplished by writing x++ (or, if you prefer, ++x ). This actually changes the value of x , so that it has the same effect as writing " x = x + 1 ". The two statements above could be written

Similarly, you could write x-- (or --x ) to subtract 1 from x . That is, x-- performs the same computation as x = x - 1 . Adding 1 to a variable is called incrementing that variable, and subtracting 1 is called decrementing . The operators ++ and -- are called the increment operator and the decrement operator, respectively. These operators can be used on variables belonging to any of the numerical types and also on variables of type char .

Usually, the operators ++ or -- , are used in statements like " x++ ;" or " x-- ;". These statements are commands to change the value of x . However, it is also legal to use x++ , ++x , x-- , or --x as expressions, or as parts of larger expressions. That is, you can write things like:

The statement " y = x++ ;" has the effects of adding 1 to the value of x and, in addition, assigning some value to y . The value assigned to y is the value of the expression x++ , which is defined to be the old value of x , before the 1 is added. Thus, if the value of x is 6 , the statement " y = x++ ;" will change the value of x to 7 and will change the value of y to 6 . On the other hand, the value of ++x is defined to be the new value of x , after the 1 is added. So if x is 6 , then the statement " y = ++x ;" changes the values of both x and y to 7 . The decrement operator, -- , works in a similar way.

This can be confusing. My advice is: Don't be confused. Use ++ and -- only in stand-alone statements, not in expressions. I will follow this advice in all the examples in these notes.

Java has boolean variables and boolean-valued expressions that can be used to express conditions that can be either true or false . One way to form a boolean-valued expression is to compare two values using a relational operator . Relational operators are used to test whether two values are equal, whether one value is greater than another, and so forth. The relation operators in Java are: == , != , < , > , <= , and >= . The meanings of these operators are:

These operators can be used to compare values of any of the numeric types. They can also be used to compare values of type char . For characters, < and > are defined according the numeric Unicode values of the characters. (This might not always be what you want. It is not the same as alphabetical order because all the upper case letters come before all the lower case letters.)

When using boolean expressions, you should remember that as far as the computer is concerned, there is nothing special about boolean values. In the next chapter, you will see how to use them in loop and branch statements. But you can also assign boolean-valued expressions to boolean variables, just as you can assign numeric values to numeric variables.

By the way, the operators == and != can be used to compare boolean values. This is occasionally useful. For example, can you figure out what this does:

One thing that you cannot do with the relational operators < , > , <= , and <= is to use them to compare values of type String . You can legally use == and != to compare Strings , but because of peculiarities in the way objects behave, they might not give the results you want. (The == operator checks whether two objects are stored in the same memory location, rather than whether they contain the same value. Occasionally, for some objects, you do want to make such a check -- but rarely for strings. I'll get back to this in a later chapter.) Instead, you should use the subroutines equals() , equalsIgnoreCase() , and compareTo() , which were described in Section 3 , to compare two Strings .

In English, complicated conditions can be formed using the words "and", "or", and "not." For example, "If there is a test and you did not study for it...". "And", "or", and "not" are boolean operators, and they exist in Java as well as in English.

In Java, the boolean operator "and" is represented by && . The && operator is used to combine two boolean values. The result is also a boolean value. The result is true if both of the combined values are true , and the result is false if either of the combined values is false . For example, " (x == 0) && (y == 0) " is true if and only if both x is equal to 0 and y is equal to 0.

The boolean operator "or" is represented by || . (That's supposed to be two of the vertical line characters, | .) " A || B " is true if either A is true or B is true , or if both are true. " A || B " is false only if both A and B are false.

The operators && and || are said to be short-circuited versions of the boolean operators. This means that the second operand of && or || is not necessarily evaluated. Consider the test

(x != 0) && (y/x > 1)

Suppose that the value of x is in fact zero. In that case, the division x/y is illegal, since division by zero is not allowed. However, the computer will never perform the division, since when the computer evaluates (x != 0) , it finds that the result is false , and so it knows that ( (x != 0) && anything ) has to be false. Therefore, it doesn't bother to evaluate the second operand, (x/y > 1) . The evaluation has been short-circuited and the division by zero is avoided. Without the short-circuiting, there would have been a division-by-zero error. (This may seem like a technicality, and it is. But at times, it will make your programming life a little easier. To be even more technical: There are actually non-short-circuited versions of && and || , which are written as & and | . Don't use them unless you have a particular reason to do so.)

The boolean operator "not" is a unary operator. In Java, it is indicated by ! and is written in front of its single operand. For example, if test is a boolean variable, then

test = ! test;

will reverse the value of test, changing it from true to false , or from false to true .

Any good programming language has some nifty little features that aren't really necessary but that let you feel cool when you use them. Java has the conditional operator. It's a ternary operator -- that is, it has three operands -- and it comes in two pieces, ? and :, that have to be used together. It takes the form

boolean-expression ? expression-1 : expression-2

The computer tests the value of boolean-expression . If the value is true , it evaluates expression-1 ; otherwise, it evaluates expression-2 . For example:

next = (N % 2 == 0) ? (N/2) : (3*N+1);

will assign the value N/2 to next if N is even (that is, if N % 2 == 0 is true ), and it will assign the value (3*N+1) to next if N is odd.

You are already familiar with the assignment statement, which uses the symbol "=" to assign the value of an expression to a variable. In fact, = is really an operator in the sense that an assignment can itself be used as an expression or as part of a more complex expression. The value of an assignment such as A=B is the same as the value that is assigned to A . So, if you want to assign the value of B to A and test at the same time whether that value is zero, you could say:

if ( (A=B) == 0 )

Usually, I would say, don't do things like that !

In general, the type of the expression on the right-hand side of an assignment statement must be the same as the type of the variable on the left-hand side. However, in some cases, the computer will automatically convert the value computed by the expression to match the type of the variable. Consider the list of numeric types: byte , short , int , long , float , double . A value of a type that occurs earlier in this list can be converted automatically to a value that occurs later. For example:

The idea is that conversion should only be done automatically when it can be done without changing the semantics of the value. Any int can be converted to a double with the same numeric value. However, there are int values that lie outside the legal range of short s. There is simply no way to represent the int 100000 as a short , for example, since the largest value of type short is 32767.

In some cases, you might want to force a conversion that wouldn't be done automatically. For this, you could use what is called a type cast . A type cast is indicated by putting a type name, in parentheses, in front of the value you want to convert. For example,

As another example of type casts, consider the problem of getting a random integer between 1 and 6. The function Math.random() gives a real number between 0.0 and 0.9999..., and so 6*Math.random() is between 0.0 and 5.999.... The type-cast operator, (int) , can be used to convert this to an integer: (int)(6*Math.random()) . A real number is cast to an integer by discarding the fractional part. Thus, (int)(6*Math.random()) is one of the integers 0, 1, 2, 3, 4, and 5. To get a number between 1 and 6, we can add 1: " (int)(6*Math.random()) + 1 ".

You can also type-cast between the type char and the numeric types. The numeric value of a char is its Unicode code number. For example, (char)97 is 'a' , and (int)'+' is 43 .

Java has several variations on the assignment operator, which exist to save typing. For example, " A += B " is defined to be the same as " A = A + B ". Every operator in Java that applies to two operands gives rise to a similar assignment operator. For example:

The combined assignment operator += even works with strings. You will recall from Section 3 that when the + operator is used with a string as the first operand, it represents concatenation. Since str += x is equivalent to str = str + x , when += is used with a string on the left-hand side, it appends the value on the right-hand side onto the string. For example, if str has the value "tire", then the statement str += 'd'; changes the value of str to "tired".

If you use several operators in one expression, and if you don't use parentheses to explicitly indicate the order of evaluation, then you have to worry about the precedence rules that determine the order of evaluation. (Advice: don't confuse yourself or the reader of your program; use parentheses liberally.)

Here is a listing of the operators discussed in this section, listed in order from highest precedence (evaluated first) to lowest precedence (evaluated last):

Operators on the same line have the same precedence. When they occur together, unary operators and assignment operators are evaluated right-to-left, and the remaining operators are evaluated left-to-right. For example, A*B/C means (A*B)/C , while A=B=C means A=(B=C) . (Can you see how the expression A=B=C might be useful, given that the value of B=C as an expression is the same as the value that is assigned to B ?)

[ Next Chapter | Previous Section | Chapter Index | Main Index ]

Java Compound Operators

Last updated: March 17, 2024

java boolean assignment

  • Java Operators

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Now that the new version of REST With Spring - “REST With Spring Boot” is finally out, the current price will be available until the 22nd of June , after which it will permanently increase by 50$

>> GET ACCESS NOW

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

The Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

And, you can participate in a very quick (1 minute) paid user research from the Java on Azure product team.

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

A quick guide to materially improve your tests with Junit 5:

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Building a REST API with Spring?

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll have a look at Java compound operators, their types and how Java evaluates them.

We’ll also explain how implicit casting works.

2. Compound Assignment Operators

An assignment operator is a binary operator that assigns the result of the right-hand side to the variable on the left-hand side. The simplest is the “=” assignment operator:

This statement declares a new variable x , assigns x the value of 5 and returns 5 .

Compound Assignment Operators are a shorter way to apply an arithmetic or bitwise operation and to assign the value of the operation to the variable on the left-hand side.

For example, the following two multiplication statements are equivalent, meaning  a and b will have the same value:

It’s important to note that the variable on the left-hand of a compound assignment operator must be already declared. In other words,  compound operators can’t be used to declare a new variable.

Like the “=” assignment operator, compound operators return the assigned result of the expression:

Both x and y will hold the value 3 .

The assignment (x+=2) does two things: first, it adds 2 to the value of the variable x , which becomes  3;  second, it returns the value of the assignment, which is also 3 .

3. Types of Compound Assignment Operators

Java supports 11 compound assignment operators. We can group these into arithmetic and bitwise operators.

Let’s go through the arithmetic operators and the operations they perform:

  • Incrementation: +=
  • Decrementation: -=
  • Multiplication: *=
  • Division: /=
  • Modulus: %=

Then, we also have the bitwise operators:

  • AND, binary: &=
  • Exclusive OR, binary: ^=
  • Inclusive OR, binary: |=
  • Left Shift, binary: <<=
  • Right Shift, binary: >>=
  • Shift right zero fill: >>>=

Let’s have a look at a few examples of these operations:

As we can see here, the syntax to use these operators is consistent.

4. Evaluation of Compound Assignment Operations

There are two ways Java evaluates the compound operations.

First, when the left-hand operand is not an array, then Java will, in order:

  • Verify the operand is a declared variable
  • Save the value of the left-hand operand
  • Evaluate the right-hand operand
  • Perform the binary operation as indicated by the compound operator
  • Convert the result of the binary operation to the type of the left-hand variable (implicit casting)
  • Assign the converted result to the left-hand variable

Next, when the left-hand operand is an array, the steps to follow are a bit different:

  • Verify the array expression on the left-hand side and throw a NullPointerException  or  ArrayIndexOutOfBoundsException if it’s incorrect
  • Save the array element in the index
  • Check if the array component selected is a primitive type or reference type and then continue with the same steps as the first list, as if the left-hand operand is a variable.

If any step of the evaluation fails, Java doesn’t continue to perform the following steps.

Let’s give some examples related to the evaluation of these operations to an array element:

As we’d expect, this will throw a  NullPointerException .

However, if we assign an initial value to the array:

We would get rid of the NullPointerException, but we’d still get an  ArrayIndexOutOfBoundsException , as the index used is not correct.

If we fix that, the operation will be completed successfully:

Finally, the x variable will be 6 at the end of the assignment.

5. Implicit Casting

One of the reasons compound operators are useful is that not only they provide a shorter way for operations, but also implicitly cast variables.

Formally, a compound assignment expression of the form:

is equivalent to:

E1 – (T)(E1 op E2)

where T is the type of E1 .

Let’s consider the following example:

Let’s review why the last line won’t compile.

Java automatically promotes smaller data types to larger data ones, when they are together in an operation, but will throw an error when trying to convert from larger to smaller types .

So, first,  i will be promoted to long and then the multiplication will give the result 10L. The long result would be assigned to i , which is an int , and this will throw an error.

This could be fixed with an explicit cast:

Java compound assignment operators are perfect in this case because they do an implicit casting:

This statement works just fine, casting the multiplication result to int and assigning the value to the left-hand side variable, i .

6. Conclusion

In this article, we looked at compound operators in Java, giving some examples and different types of them. We explained how Java evaluates these operations.

Finally, we also reviewed implicit casting, one of the reasons these shorthand operators are useful.

As always, all of the code snippets mentioned in this article can be found in our GitHub repository .

Creating PDFs is actually surprisingly hard. When we first tried, none of the existing PDF libraries met our needs. So we made DocRaptor for ourselves and later launched it as one of the first HTML-to-PDF APIs.

We think DocRaptor is the fastest and most scalable way to make PDFs , especially high-quality or complex PDFs. And as developers ourselves, we love good documentation, no-account trial keys, and an easy setup process.

>> Try DocRaptor's HTML-to-PDF Java Client (No Signup Required)

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Build your API with SPRING - book cover

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Input validation that verifies a boolean assignment using a Boolean object

Taking online college course and I'm new to Java. We just learned about input validation. I've used input validation pretty comfortably for strings, ints, and whatnot. But I had to validate a boolean value so I tried using a Boolean object (for a null assignment) and it worked.

Instructor feedback is slow at best and I want to learn while it's fresh in my head.

Wondering if there is a more efficient way of doing this in the future?

Code snippet is as follows:

My rescue animal class (Superclass)

My Dog class (extends rescue animal)

And finally my monkey class (extends rescue animal class)

mdfst13's user avatar

  • \$\begingroup\$ Added them, sorry it's my first time posting to the site. Thank you for the corrections. \$\endgroup\$ –  Ryan Jones Commented Apr 13, 2022 at 22:58

2 Answers 2

Small things first:

  • You can use the diamond operator <> , which preciously saves repetitive typing.
  • You can change the implementation later.
  • As method return, you can use use any implementation, especially Collections.singleton/emptyList() . Most important.
  • As method parameter you can pass any kind of List like a LinkedList .

For the optional boolean value you are overthinking things. Good meaning by good naming might have helped. A while may be even better:

inputVal is only needed for looping as long as the input is not valid. More reserved would be candidate for yes, no, I do not know yet / later. Then a Boolean null would be one solution; nowadays one can use Optional<Boolean> , without any null value. But that probably still is not treated.

Calling overridable methods in a constructor is very bad. The reason is that any child is still not initialized (fields are filled later, rest of child constructor executed after super constructor). When then an overriden child method is called it uses uninitialized child fields, that will be overwritten after the child method. You could make a Setter final to repair it.

Joop Eggen's user avatar

ArrayList is not a good choice of data structure for your animals. Prefer instead a HashMap by String , so that lookups by name are more efficient.

Convert Driver to an instance class instead of a static class, and instantiate it in your main() . Make your dogs and monkeys (drop the "List" suffix) final instance members instead of mutable static members. Keep a single scanner member rather than passing it around to subroutines.

Don't have an appQuit loop flag; just return . Other loop flag variables like inputVal should also go away.

Convert your if on userInput into a switch .

Do not repeat displayMenu() and nextLine() after each option; do this only once on the inside of the loop at the start.

Do not hard-code \n , which is a system-specific newline. Instead, rely on println() or use %n in a printf call.

Delete your initializeList() methods. Driver is not the place for testing; move this to an actual JUnit unit test.

Delete basically all of your comments. Writing //returns to menu helps no one.

Age, weight and length variables must not be String s, and should be instead some numeric like float .

Factor out a yes/no loop and validation method rather than copying and pasting it. Also, rather than equalsIgnoreCase , a more forgiving predicate would be just checking to see that the string starts with y or n after being lower-cased.

Your animal classes are problematic - they have mutable-by-default members, when they should have immutable-by-default members. Note: the only member variable in the entire application that needs to mutate is reserved , so make a reserve() mutation method for that, delete every set() method in the application, and mark all but boolean reserved as final .

RescueAnimal() needs to populate its constructor arguments rather than having a default constructor. Dog() and Monkey() need to call super() . No constructor should be calling set() methods, and should instead directly initialise members like this.breed = breed .

For the reservation logic, doing a country and reservation status lookup can be done with streams instead of a loop.

In a case like Your newly reserved dog is , prefer printf over string concatenation.

Driver.java

RescueAnimal.java

Monkey.java

Reinderien's user avatar

  • \$\begingroup\$ Don't import java.lang.String; There is always an implicit import java.lang.*; . \$\endgroup\$ –  swpalmer Commented Apr 14, 2022 at 21:15
  • \$\begingroup\$ @swpalmer Fine; though that's only an error that I inherited from the OP. Fixed. \$\endgroup\$ –  Reinderien Commented Apr 14, 2022 at 21:18

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java homework classes or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags

Hot Network Questions

  • Using commented dashes to divide up code chunks
  • Is it possible to avoid ending Time Stop by making attacks from inside an Antimagic Field?
  • Bringing a game console into Saudi Arabia
  • Academic Interview Question: "What is the title of your second book?"
  • Can I remove an appimage file?
  • How can photons interact with nuclei?
  • How can I calculate how much power an isolation transformer itself consumes if no load is provided?
  • Is this homebrew "Firemind Dragonborn" race overpowered?
  • Is "Shopping malls are a posh place" grammatical when "malls" is a plural and "place" is a singular?
  • How to not make my series repetitive?
  • Why can't I connect a hose to this outdoor faucet?
  • Round Cake Pan with Parchment Paper
  • Eye Spy: Where are the other two (of six) vehicles docked to the ISS in this Maxar image (& what are they?)
  • Can a creature with Mimicry activate command word magic items?
  • Keeping ECU powered up on a bench/standalone setup?
  • How does gravity overpower a vacuum?
  • Is parapsychology a science?
  • Where from the standard do I read that exceptions of derived class held by base class reference are sliced when caught?
  • An instrument that sounds like flute but a bit lower
  • How do I open the locked door in Fungal Wastes?
  • What would large scale war with tactical nukes look like?
  • Freezing Meat in Butcher Paper
  • 9-16-25 2D Matrix
  • Plant identification, please

java boolean assignment

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Best practice boolean assignment [closed]

I came across the following conditional in a program that I have taken over from another developer:

I believe this code is redundant and ugly, so I changed it to what I thought was a simple boolean assignment based on a comparison:

Upon seeing this, someone reviewing my code commented that although my change is functionally correct, it might confuse someone else looking at it. He believes that using a ternary operator makes this assignment more clear, whereas I don't like the addition of more redundant code:

His reasoning is that doing something in the most concise way is not worth it, if it causes another developer to have to stop and puzzle out exactly what you've done.

The real question here is which of these three methods of assigning a value to the boolean obj.NeedsChange is the most clear and the most maintainable?

  • maintainability

Useless's user avatar

  • 26 The third form is ridiculous; it's just stating what should already be blatantly obvious in the second form. –  Robert Harvey Commented Jun 17, 2015 at 14:44
  • 7 This is entirely up to personal preference. We can pretend otherwise, but because they're all functionally equivalent it boils down to style . Sure, there's a difference in readability, but my "readable and transparent" might be your "obtuse and opaque" –  MetaFight Commented Jun 17, 2015 at 15:03
  • 3 @MetaFight 5-8 lines vs 1 line is not just a personal preference. There's more room for typos, which matters if it's an interpreted language. Also it sounds more like a excuse of not understanding of "expression vs statement" topic. –  scriptin Commented Jun 17, 2015 at 15:19
  • 3 @scriptin 5-8 lines v 1 line is more than preference, the 5-8 liner is usually clearer and better for it. In this simple example, I prefer the 1 line, but in general I've seen too many 10 liners that were obfuscated into 1-liners for comfort. Given that, I'd never complain about variant 1, it may not be pretty but it does the job just as clearly and obviously. –  gbjbaanb Commented Jun 17, 2015 at 15:24
  • 6 Options 1 and 3 say to me "The author doesn't really understand boolean logic". –  17 of 26 Commented Jun 17, 2015 at 16:19

6 Answers 6

I prefer 2, but I might go for a small adjustment to it:

To me the parentheses makes the line easier to parse and makes it clear at a glance that you are assigning the result of a comparison, and not performing a double assignment. I'm not sure why that is (as off-hand I can't think of a language where parentheses would actually prevent a double assignment), but if you must satisfy your reviewer then perhaps this will be an acceptable compromise.

Jacob is on Codidact's user avatar

  • 4 this is the correct answer - although the code in the question is correct, adding the brackets does tell the reader that it is not as assignment. If you were quickly looking through code, the brackets give you that instant extra info that stops you looking closer to see if the code meant to be like that, and wasn't an accidental bug. For example, imagine the line was a = b == c , did you mean assign a bool or did you mean assign c to both b and a. –  gbjbaanb Commented Jun 17, 2015 at 15:26
  • Parentheses would prevent a double assignment in Python. Even in languages where they don't prevent double assignment, the parentheses definitely help indicate that you're dealing with two kinds of operations. –  user2357112 Commented Jun 17, 2015 at 18:15

Variant 1 is easily understood, but that is its only advantage. I automatically assume that anyone who writes like this doesn't really understand what booleans are all about, and will be writing similarly infantile code in many other respects.

Variant 2 is what I would always write, and expect to read. I think that anyone who is confused by that idiom shouldn't be a professional writer of software.

Variant 3 combines the disadvantages of both 1 and 2. 'nuff said.

Kilian Foth's user avatar

  • Well, variant 1 shares its advantage with variant 2... –  Deduplicator Commented Jun 17, 2015 at 16:56
  • 1 +1 for infantile code. I've been looking at such code for years, I just lacked the right word to identify it. –  Lilienthal Commented Jun 17, 2015 at 18:22
  • 1 My first assumption with code like Variant 1 is that the two branches at one point in the past were more complicated, and someone wasn't paying attention when refactoring. If however that's how it was when first written, then I agree with "not understanding booleans" –  Izkata Commented Jun 17, 2015 at 18:30

Anytime code is more complicated than it needs to be triggers a "what is this supposed to be doing?" smell in the reader.

For example, the first example makes me wonder, "was there other functionality in the if/else statement at some point that was removed?"

Example (2) is simple, clear, and does exactly what is needed. I read it and immediately understand what the code does.

The extra fluff in (3) would cause me to wonder why the author wrote it that way instead of (2). There should be a reason, but in this case there doesn't seem to be, so it's not helpful at all and harder to read because the syntax suggests something present which is not there. Trying to learn what is present (when nothing is) makes code harder to read.

enderland's user avatar

It is easy to see that Variant 2 and Variant 1 are related via a series of obvious and simple refactorings:

Here, we have needless code duplication, we can factor out the assignment:

or written more concisely:

Now, it should be immediately obvious that this will assign true if the condition is true and assign false if the condition is false, IOW it will simply assign the value of the condition, i.e. it is equivalent to

Variants 1 and 3 are typical rookie code written by someone who doesn't understand what the return value of a comparison is.

Jörg W Mittag's user avatar

  • I would add your if (...)...false part as a comment just before the nice one, then you get the simple scan through the code clarity and the better code. –  DaveM Commented Jun 17, 2015 at 17:57

While your programming should tend towards explicit over implicit "as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live", you can assume a few basic things that your psycho successor will be competent in.

One of those is the syntax of the language he is using.

is very clear to anyone who knows C/C++/C#/Java/Javascript syntax.

It's also much more readable than 8 lines.

and less prone to mistakes

And it's better than adding unnecessary characters, as if you half-forgot the syntax of the language:

I think there is much wrong about the C-like syntax of many languages: inconsistent order of operations, inconsistent left/right associativity, overloaded uses of symbols, braces/indentation duplication, ternary operators, infix notation, etc.

But the solution isn't to invent your own proprietary version of it. That way lies madness, as everyone creates their own.

Generally the #1 thing that makes Real World TM code unreadable is the amount of it.

Between a non-pathological 200 line program and an trivially identical 1,600 line program, the shorter one will almost always be easier to parse and understand. I would welcome your change any day.

Paul Draper's user avatar

Most of the developers will be able to understand the 2nd form with a glance. In my opinion over simplification as in 1st form is simply unnecessary.

You can improve the readability by adding spaces and braces such as:

as mentioned by Jacob Raihle.

Uday Shankar's user avatar

Not the answer you're looking for? Browse other questions tagged clean-code maintainability boolean or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags

Hot Network Questions

  • If humans colonized Earth 100,000 years ago, would we know it?
  • Parts of Humans
  • Could a ground fault cause high power consumption? Why?
  • How would I fix this leaking garage?
  • Eye Spy: Where are the other two (of six) vehicles docked to the ISS in this Maxar image (& what are they?)
  • Composition of vectorvalued functions
  • How to not make my series repetitive?
  • Bringing a game console into Saudi Arabia
  • Can a creature with Mimicry activate command word magic items?
  • Why can't I connect a hose to this outdoor faucet?
  • How do I open the locked door in Fungal Wastes?
  • How do I know how many enemies have I not found in the Hunter's Journal?
  • Count predictor and binary outcome
  • How does gravity overpower a vacuum?
  • Why is MSS important? Why can't we just rely on the MTU?
  • Is parapsychology a science?
  • How does this tensegrity table work?
  • Is “stuff” used correctly in “ There are all kinds of animals: lions, elephants and stuff.”
  • What is the time-travel story where "ugly chickens" are trapped in the past and brought to the present to become ingredients for a soup?
  • Keeping ECU powered up on a bench/standalone setup?
  • Why are worldships not shaped like worlds?
  • Can I remove an appimage file?
  • In the US, are employers liable for torts caused by their employees working from home
  • Academic Interview Question: "What is the title of your second book?"

java boolean assignment

Java - Compound Boolean Logical Assignment Operators

What are compound boolean logical assignment operators.

There are three compound Boolean logical assignment operators.

The operand1 must be a boolean variable and op may be &, |, or ^.

Java does not have any operators like &&= and ||=.

Compound Boolean Logical Assignment Operators are used in the form

The above form is equivalent to writing

The following table lists the compound logical assignment operators and their equivalents.

Expression is equivalent to
operand1 &= operand2 operand1 = operand1 & operand2
operand1 |= operand2 operand1 = operand1 | operand2
operand1 ^= operand2 operand1 = operand1 ^ operand2

For &= operator, if both operands evaluate to true, &= returns true. Otherwise, it returns false.

For != operator, if either operand evaluates to true, != returns true. Otherwise, it returns false.

For ^= operator, if both operands evaluate to different values, that is, one of the operands is true but not both, ^= returns true. Otherwise, it returns false.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Expressions and operators

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that purely evaluate .

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to 7 .

The expression 3 + 4 is an example of the second type. This expression uses the + operator to add 3 and 4 together and produces a value, 7 . However, if it's not eventually part of a bigger construct (for example, a variable declaration like const z = 3 + 4 ), its result will be immediately discarded — this is usually a programmer mistake because the evaluation doesn't produce any effects.

As the examples above also illustrate, all complex expressions are joined by operators , such as = and + . In this section, we will introduce the following operators:

Assignment operators

Comparison operators, arithmetic operators, bitwise operators, logical operators, bigint operators, string operators, conditional (ternary) operator, comma operator, unary operators, relational operators.

These operators join operands either formed by higher-precedence operators or one of the basic expressions . A complete and detailed list of operators and expressions is also available in the reference .

The precedence of operators determines the order they are applied when evaluating an expression. For example:

Despite * and + coming in different orders, both expressions would result in 7 because * has precedence over + , so the * -joined expression will always be evaluated first. You can override operator precedence by using parentheses (which creates a grouped expression — the basic expression). To see a complete table of operator precedence as well as various caveats, see the Operator Precedence Reference page.

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

For example, 3 + 4 or x * y . This form is called an infix binary operator, because the operator is placed between two operands. All binary operators in JavaScript are infix.

A unary operator requires a single operand, either before or after the operator:

For example, x++ or ++x . The operator operand form is called a prefix unary operator, and the operand operator form is called a postfix unary operator. ++ and -- are the only postfix operators in JavaScript — all other operators, like ! , typeof , etc. are prefix.

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Name Shorthand operator Meaning

Assigning to properties

If an expression evaluates to an object , then the left-hand side of an assignment expression may make assignments to properties of that expression. For example:

For more information about objects, read Working with Objects .

If an expression does not evaluate to an object, then assignments to properties of that expression do not assign:

In strict mode , the code above throws, because one cannot assign properties to primitives.

It is an error to assign values to unmodifiable properties or to properties of an expression without properties ( null or undefined ).

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

Without destructuring, it takes multiple statements to extract values from arrays and objects:

With destructuring, you can extract multiple values into distinct variables using a single statement:

Evaluation and nesting

In general, assignments are used within a variable declaration (i.e., with const , let , or var ) or as standalone statements.

However, like other expressions, assignment expressions like x = f() evaluate into a result value. Although this result value is usually not used, it can then be used by another expression.

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, some JavaScript style guides discourage chaining or nesting assignments . Nevertheless, assignment chaining and nesting may occur sometimes, so it is important to be able to understand how they work.

By chaining or nesting an assignment expression, its result can itself be assigned to another variable. It can be logged, it can be put inside an array literal or function call, and so on.

The evaluation result matches the expression to the right of the = sign in the "Meaning" column of the table above. That means that x = f() evaluates into whatever f() 's result is, x += f() evaluates into the resulting sum x + f() , x **= f() evaluates into the resulting power x ** f() , and so on.

In the case of logical assignments, x &&= f() , x ||= f() , and x ??= f() , the return value is that of the logical operation without the assignment, so x && f() , x || f() , and x ?? f() , respectively.

When chaining these expressions without parentheses or other grouping operators like array literals, the assignment expressions are grouped right to left (they are right-associative ), but they are evaluated left to right .

Note that, for all assignment operators other than = itself, the resulting values are always based on the operands' values before the operation.

For example, assume that the following functions f and g and the variables x and y have been declared:

Consider these three examples:

Evaluation example 1

y = x = f() is equivalent to y = (x = f()) , because the assignment operator = is right-associative . However, it evaluates from left to right:

  • The y on this assignment's left-hand side evaluates into a reference to the variable named y .
  • The x on this assignment's left-hand side evaluates into a reference to the variable named x .
  • The function call f() prints "F!" to the console and then evaluates to the number 2 .
  • That 2 result from f() is assigned to x .
  • The assignment expression x = f() has now finished evaluating; its result is the new value of x , which is 2 .
  • That 2 result in turn is also assigned to y .
  • The assignment expression y = x = f() has now finished evaluating; its result is the new value of y – which happens to be 2 . x and y are assigned to 2 , and the console has printed "F!".

Evaluation example 2

y = [ f(), x = g() ] also evaluates from left to right:

  • The y on this assignment's left-hand evaluates into a reference to the variable named y .
  • The function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 result from g() is assigned to x .
  • The assignment expression x = g() has now finished evaluating; its result is the new value of x , which is 3 . That 3 result becomes the next element in the inner array literal (after the 2 from the f() ).
  • The inner array literal [ f(), x = g() ] has now finished evaluating; its result is an array with two values: [ 2, 3 ] .
  • That [ 2, 3 ] array is now assigned to y .
  • The assignment expression y = [ f(), x = g() ] has now finished evaluating; its result is the new value of y – which happens to be [ 2, 3 ] . x is now assigned to 3 , y is now assigned to [ 2, 3 ] , and the console has printed "F!" then "G!".

Evaluation example 3

x[f()] = g() also evaluates from left to right. (This example assumes that x is already assigned to some object. For more information about objects, read Working with Objects .)

  • The x in this property access evaluates into a reference to the variable named x .
  • Then the function call f() prints "F!" to the console and then evaluates to the number 2 .
  • The x[f()] property access on this assignment has now finished evaluating; its result is a variable property reference: x[2] .
  • Then the function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 is now assigned to x[2] . (This step will succeed only if x is assigned to an object .)
  • The assignment expression x[f()] = g() has now finished evaluating; its result is the new value of x[2] – which happens to be 3 . x[2] is now assigned to 3 , and the console has printed "F!" then "G!".

Avoid assignment chains

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, chaining assignments in the same statement is discouraged .

In particular, putting a variable chain in a const , let , or var statement often does not work. Only the outermost/leftmost variable would get declared; other variables within the assignment chain are not declared by the const / let / var statement. For example:

This statement seemingly declares the variables x , y , and z . However, it only actually declares the variable z . y and x are either invalid references to nonexistent variables (in strict mode ) or, worse, would implicitly create global variables for x and y in sloppy mode .

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:

Comparison operators
Operator Description Examples returning true
( ) Returns if the operands are equal.

( ) Returns if the operands are not equal.
( ) Returns if the operands are equal and of the same type. See also and .
( ) Returns if the operands are of the same type but not equal, or are of different type.
( ) Returns if the left operand is greater than the right operand.
( ) Returns if the left operand is greater than or equal to the right operand.
( ) Returns if the left operand is less than the right operand.
( ) Returns if the left operand is less than or equal to the right operand.

Note: => is not a comparison operator but rather is the notation for Arrow functions .

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:

In addition to the standard arithmetic operations ( + , - , * , / ), JavaScript provides the arithmetic operators listed in the following table:

Arithmetic operators
Operator Description Example
( ) Binary operator. Returns the integer remainder of dividing the two operands. 12 % 5 returns 2.
( ) Unary operator. Adds one to its operand. If used as a prefix operator ( ), returns the value of its operand after adding one; if used as a postfix operator ( ), returns the value of its operand before adding one. If is 3, then sets to 4 and returns 4, whereas returns 3 and, only then, sets to 4.
( ) Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. If is 3, then sets to 2 and returns 2, whereas returns 3 and, only then, sets to 2.
( ) Unary operator. Returns the negation of its operand. If is 3, then returns -3.
( ) Unary operator. Attempts to , if it is not already.

returns .

returns .

( ) Calculates the to the power, that is, returns .
returns .

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Operator Usage Description
Returns a one in each bit position for which the corresponding bits of both operands are ones.
Returns a zero in each bit position for which the corresponding bits of both operands are zeros.
Returns a zero in each bit position for which the corresponding bits are the same. [Returns a one in each bit position for which the corresponding bits are different.]
Inverts the bits of its operand.
Shifts in binary representation bits to the left, shifting in zeros from the right.
Shifts in binary representation bits to the right, discarding bits shifted off.
Shifts in binary representation bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer: Before: 1110 0110 1111 1010 0000 0000 0000 0110 0000 0000 0001 After: 1010 0000 0000 0000 0110 0000 0000 0001
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Expression Result Binary Description

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation). ~x evaluates to the same value that -x - 1 evaluates to.

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of either type Number or BigInt : specifically, if the type of the left operand is BigInt , they return BigInt ; otherwise, they return Number .

The shift operators are listed in the following table.

Bitwise shift operators
Operator Description Example

( )
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, yields -3, because the sign is preserved.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

Logical operators
Operator Usage Description
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if both operands are true; otherwise, returns .
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if either operand is true; if both are false, returns .
( ) Returns if its single operand that can be converted to ; otherwise, returns .

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

The following code shows examples of the || (logical OR) operator.

The following code shows examples of the ! (logical NOT) operator.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

Note that for the second case, in modern code you can use the Nullish coalescing operator ( ?? ) that works like || , but it only returns the second expression, when the first one is " nullish ", i.e. null or undefined . It is thus the better alternative to provide defaults, when values like '' or 0 are valid values for the first expression, too.

Most operators that can be used between numbers can be used between BigInt values as well.

One exception is unsigned right shift ( >>> ) , which is not defined for BigInt values. This is because a BigInt does not have a fixed width, so technically it does not have a "highest bit".

BigInts and numbers are not mutually replaceable — you cannot mix them in calculations.

This is because BigInt is neither a subset nor a superset of numbers. BigInts have higher precision than numbers when representing large integers, but cannot represent decimals, so implicit conversion on either side might lose precision. Use explicit conversion to signal whether you wish the operation to be a number operation or a BigInt one.

You can compare BigInts with numbers.

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

The shorthand assignment operator += can also be used to concatenate strings.

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .

The comma operator ( , ) evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop. It is regarded bad style to use it elsewhere, when it is not necessary. Often two separate statements can and should be used instead.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:

A unary operation is an operation with only one operand.

The delete operator deletes an object's property. The syntax is:

where object is the name of an object, property is an existing property, and propertyKey is a string or symbol referring to an existing property.

If the delete operator succeeds, it removes the property from the object. Trying to access it afterwards will yield undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

Since arrays are just objects, it's technically possible to delete elements from them. This is, however, regarded as a bad practice — try to avoid it. When you delete an array property, the array length is not affected and other elements are not re-indexed. To achieve that behavior, it is much better to just overwrite the element with the value undefined . To actually manipulate the array, use the various array methods such as splice .

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

For the keywords true and null , the typeof operator returns the following results:

For a number or string, the typeof operator returns the following results:

For property values, the typeof operator returns the type of value the property contains:

For methods and functions, the typeof operator returns results as follows:

For predefined objects, the typeof operator returns results as follows:

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them to avoid precedence issues.

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

The in operator returns true if the specified property is in the specified object. The syntax is:

where propNameOrNumber is a string, numeric, or symbol expression representing a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

Basic expressions

All operators eventually operate on one or more basic expressions. These basic expressions include identifiers and literals , but there are a few other kinds as well. They are briefly introduced below, and their semantics are described in detail in their respective reference sections.

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

Suppose a function called validate validates an object's value property, given the object and the high and low values:

You could call validate in each form element's onChange event handler, using this to pass it to the form element, as in the following example:

Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Java Operators : |= bitwise OR and assign example [duplicate]

I just going through code someone has written and I saw |= usage, looking up on Java operators, it suggests bitwise or and assign operation, can anyone explain and give me an example of it?

Here is the code that read it:

  • bit-manipulation
  • variable-assignment

Chris Chambers's user avatar

  • Could you show us the code you read? –  talnicolas Commented Apr 13, 2012 at 13:49
  • @talnicolas: updated question with code . –  Rachel Commented Apr 13, 2012 at 13:50
  • What is the type of matches ? int or boolean ? –  adranale Commented Apr 13, 2012 at 13:51
  • see my answer, probably bitwise-or is not meant at all here! –  adranale Commented Apr 13, 2012 at 13:56

6 Answers 6

is the same as

It calculates the bitwise OR of the two operands, and assigns the result to the left operand.

To explain your example code:

I presume matches is a boolean ; this means that the bitwise operators behave the same as logical operators.

On each iteration of the loop, it OR s the current value of matches with whatever is returned from field.contains() . This has the effect of setting it to true if it was already true, or if field.contains() returns true.

So, it calculates if any of the calls to field.contains() , throughout the entire loop, has returned true .

Graham Borland's user avatar

  • can you put in some values for a and b? –  Rachel Commented Apr 13, 2012 at 13:51
  • oh ok, now it make some sense –  Rachel Commented Apr 13, 2012 at 13:57
  • "this means that the bitwise operators behave the same as logical operators". Actually, logical operators will short-circuit. Short circuiting is probably desired here. –  smp7d Commented Apr 13, 2012 at 14:13
  • 3 It should also be noted that if contains() has no side-effects, this is rather inefficient. Adding at least an if (matches) { break; } inside the loop would be so much nicer... (Although I suppose getValue() may be returning so few searches that it won't make a noticeable difference...) –  Izkata Commented Apr 13, 2012 at 18:03

a |= b is the same as a = (a | b)

Boolean Variables

In a boolean context, it means:

that is, if b is true then a will be true, otherwise a will be unmodified.

Bitwise Operations

In a bit wise context it means that every binary bit that's set in b will become set in a . Bits that are clear in b will be unmodified in a .

So if bit 0 is set in b , it'll also become set in a , per the example below:

This will set the bottom bit of an integer:

This will clear the bottom bit:

a &= ~0x01

This will toggle the bottom bit:

Alnitak's user avatar

  • can put in some number values for a and explain the detail ooperation. –  Rachel Commented Apr 13, 2012 at 13:52

is equivalent to this code:

Similarly, this code:

is equivalent to this one:

In the first example, a bit-wise OR is being performed. In the second example, a boolean OR is performed.

Óscar López's user avatar

a |= b is the same as a = a | b

a | b is a bitwise operator if both operands are integral types (int, short, etc...). If both operands are booleans, then its is a boolean or.

When both a and b are booleans, the difference between a | b and a || b is that in the first, both sides are always evaluated, in the later b is only evaluated if a is false. It is sort of a "shortcut" operator.

This is useful for situations like this:

On the other hand, || actually is implemented as another conditional jump in the bytecode/machine-code. In some cases, it may be faster to evaluate boolean conditions using the | operator to avoid the additional jump (and thus branch predition, etc...). Definitely something for low-level micro-benchmarking to figure out which is better (and usually not important in most applications).

When you do a |= b you are always evaluating both a and b . It doesn't really make sense to have an a ||= b operators, since the equivalent a = a || b would translate to:

...due to the conditional nature of || evaluation. In other words, b would not be evaluated if a was already true.

ɲeuroburɳ's user avatar

Could it be possible that the code has a bug and it was meant

matches = matches || field.contains(search);

so that matches should be true if at least one field contains the search variable?

adranale's user avatar

  • 2 your code is not functionally the same - if matches is already true then the short circuit operator will prevent evaluation of field.contains(search) . AFAIK the |= operator won't do that. –  Alnitak Commented Apr 13, 2012 at 14:05
  • Which means my code is optimization of the original code –  adranale Commented Apr 13, 2012 at 14:06
  • 1 only if it's truly intended that .contains() is not called in those circumstances. –  Alnitak Commented Apr 13, 2012 at 14:07
  • 1 you mean if the .contains() method does not have side-effects –  adranale Commented Apr 13, 2012 at 14:14
  • 1 yeah, mostly - in this case it probably doesn't matter, but it's worth knowing that for boolean variables a |= func() is the same as a = a | func() which is not functionally the same as a = a || func() , even though the end result on a is the same. –  Alnitak Commented Apr 13, 2012 at 16:26

That code snippet is a poor example of when to use that operator. Honestly I can't think of a great example of when to use this operator, but here's my best attempt:

Note: You need 3 ifs because otherwise you could just do somethingIsTrue | testSomethingElseTrue() for the second if.

In case you were wondering why you shouldn't use the operator in the first example, here's why:

From a performance standpoint, it is poor because it does a compare and an assign for each loop instead of just a compare. Also, it continues iterating even when future iterations will have no effect (once matches gets set to true it will not change, and String.contains has no side effects).

It is also poor from a readability standpoint, based solely on the existence of this question ;)

Thus, in place of that snippet I'd go for:

On a side note, it seems to me like the original coder might have been playing a bit too much code-golf when (s)he wrote this :)

Community's user avatar

  • There are many good use cases for this operator. Imagine methods like addAll or removeAll in a set, provided that you iterate over the collection in parameter. You add or remove in a loop, and you want to return true if you actually added or removed at least one entry. –  Vlasec Commented Nov 24, 2019 at 21:45

Not the answer you're looking for? Browse other questions tagged java operators bit-manipulation variable-assignment or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The return of Staging Ground to Stack Overflow
  • The 2024 Developer Survey Is Live

Hot Network Questions

  • An instrument that sounds like flute but a bit lower
  • Definability properties of box-open subsets of Polish space
  • Can a creature with Mimicry activate command word magic items?
  • Why was the 1540 a computer in its own right?
  • Composition of vectorvalued functions
  • What enemies can you kill in one hit with Pure Nail?
  • Aligning surveyed point layers in QGIS
  • Is “stuff” used correctly in “ There are all kinds of animals: lions, elephants and stuff.”
  • Eye Spy: Where are the other two (of six) vehicles docked to the ISS in this Maxar image (& what are they?)
  • Simple Bank Management System
  • How can student grades from different countries (e.g., India and China) be compared when applying for academic positions?
  • Why are worldships not shaped like worlds?
  • How to find stationary points graphically?
  • Is there a way knowledge checks can be done without an Intelligence trait?
  • Using commented dashes to divide up code chunks
  • Why does setting a variable readonly in the outer scope prevents defining a local variable with the same name?
  • How does gravity overpower a vacuum?
  • How does the June 2024 Ukraine peace summit hope to achieve peace, if Russia is not invited?
  • Will a rack-mounted child seat be safe if the rack's maximum load is 2kg less than the seat manufacturer describes as the minimum load?
  • How would I fix this leaking garage?
  • Is there a reason why countries in the Global South don't complain about Chinese overcapacity?
  • Do I need to replace \DeclareCollectionInstance after recent package change?
  • why std::is_same<int, *(int*)>::value is false?
  • Is there any difference between “essential to something” and “essential for something”?

java boolean assignment

IMAGES

  1. Last Minute Java Boolean Logical Operators and Priority Tutorial

    java boolean assignment

  2. how to create a boolean method in java

    java boolean assignment

  3. Boolean Logical Operators

    java boolean assignment

  4. Java String to boolean Conversion with examples

    java boolean assignment

  5. Booleans in Java explained

    java boolean assignment

  6. how to create a boolean method in java

    java boolean assignment

VIDEO

  1. Section 3 Operators Part 2 UNIT-4: INTRODUCTION TO DYNAMIC WEBSITES USING JAVASCRIPT 803

  2. Boolean in C #java #coder #coding #cprogramming

  3. #20. Assignment Operators in Java

  4. Waiting to execute program until a Boolean value has been changed externally (Java)

  5. Core

  6. Datentyp Boolean

COMMENTS

  1. Java Booleans

    Java Booleans. Very often, in programming, you will need a data type that can only have one of two values, like: YES / NO. ON / OFF. TRUE / FALSE. For this, Java has a boolean data type, which can store true or false values.

  2. Boolean value assignment in Java

    Boolean value assignment in Java. Ask Question Asked 11 years, 4 months ago. Modified 11 years, 4 months ago. Viewed 29k times 2 Apologies for the total noob question, but can anyone explain what's happening to the value of match after the for-each loop has finished in the following method? Attempts to compile ...

  3. Boolean (Java Platform SE 8 )

    The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean . In addition, this class provides many methods for converting a boolean to a String and a String to a boolean, as well as other constants and methods useful when dealing with a boolean.

  4. Assignment, Arithmetic, and Unary Operators (The Java™ Tutorials

    This beginner Java tutorial describes fundamentals of programming in the Java programming language ... You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For ... negating an expression, or inverting the value of a boolean. Operator Description + Unary plus operator; indicates ...

  5. Operators (The Java™ Tutorials > Learning the Java Language

    Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest ...

  6. Java Assignment Operators with Examples

    Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.

  7. Java

    One of the primitive data types in Java is the boolean.A boolean object takes a value of true or false.. Boolean logic describes how boolean values can be combined and manipulated. Java implements boolean logic through a set of operators and methods.. Boolean Logical Operators. The boolean logical operators available in Java are described in the following table:

  8. Java Operators

    We can use it to invert the value of a boolean variable or value: boolean aTrue = true; boolean bFalse = !aTrue; 3.4. The Increment Operator ... Next, let's see which assignment operators we can use in Java. 9.1. The Simple Assignment Operator. The simple assignment operator (=) is a straightforward but important operator in Java. Actually ...

  9. Java Booleans Explained [Easy Examples]

    Java Boolean is an inbuilt class that wraps are used for wrapping the value of primitive data type, i.e. boolean in an object. The boolean class contains two values, i.e. true or false. ... Example-1 Equal and not equal assignment operators and Java booleans. Equal to the operator (==) return true if both the operands are equal. It can be used ...

  10. Java boolean |= operator

    From Java Language Specification 15.22: When both operands of a &, ^, or | operator are of type boolean or Boolean, then the type of the bitwise operator expression is boolean. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary. For &, the result value is true if both operand values are true; otherwise, the ...

  11. Java Operators

    Java Comparison Operators. Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions. The return value of a comparison is either true or false. These values are known as Boolean values, and you will learn more about them in the Booleans and If ...

  12. Toggle a Boolean Variable in Java

    We've seen that a primitive boolean variable can only have two values: true and false.However, unlike the primitive boolean, the boxed Boolean variable can hold null.. Java automatically unboxes Boolean to boolean when we perform NOT or XOR operation on a Boolean variable. But if we don't handle the null case properly, we'll encounter NullPointerException:

  13. Java Boolean, String, Assignment Operators

    Java also supports a number of Boolean, string, and assignment operators. Boolean operators are used to perform logical comparisons, and always result in one of two values: true or false. Following are the most commonly used Boolean operators :

  14. Java Programing: Section 2.5

    Java has boolean variables and boolean-valued expressions that can be used to express conditions that can be either true or false. ... Java has several variations on the assignment operator, which exist to save typing. For example, "A += B" is defined to be the same as "A = A + B". Every operator in Java that applies to two operands gives rise ...

  15. Java Compound Operators

    Compound Assignment Operators. An assignment operator is a binary operator that assigns the result of the right-hand side to the variable on the left-hand side. The simplest is the "=" assignment operator: int x = 5; This statement declares a new variable x, assigns x the value of 5 and returns 5. Compound Assignment Operators are a shorter ...

  16. Cleanest way to toggle a boolean variable in Java?

    Since the assignment operator always returns what has been assigned, this will toggle the value via the bitwise operator, and then return the newly assigned value to be used in the method call. Share. ... This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from ...

  17. java

    Taking online college course and I'm new to Java. We just learned about input validation. I've used input validation pretty comfortably for strings, ints, and whatnot. But I had to validate a boolean value so I tried using a Boolean object (for a null assignment) and it worked.

  18. clean code

    else. {. obj.NeedsChange = false; } I believe this code is redundant and ugly, so I changed it to what I thought was a simple boolean assignment based on a comparison: obj.NeedsChange = obj.Performance <= LOW_PERFORMANCE; Upon seeing this, someone reviewing my code commented that although my change is functionally correct, it might confuse ...

  19. Java

    There are three compound Boolean logical assignment operators. The operand1 must be a boolean variable and op may be &, |, or ^. Java does not have any operators like &&= and ||=. Compound Boolean Logical Assignment Operators are used in the form. The above form is equivalent to writing. The following table lists the compound logical assignment ...

  20. java

    Boolean value assignment in Java. 28. Java boolean |= operator. 43. How Does The Bitwise & (AND) Work In Java? 2. Need help understanding this line. 3. Bitwise and (&) operator. 0. Unable to understand Bitwise & operator in java. Hot Network Questions Travelling to Iceland via Germany with Germany-issued Schengen visa

  21. Expressions and operators

    This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that ...

  22. Java Operators : |= bitwise OR and assign example

    a |= b; is the same as. a = (a | b); It calculates the bitwise OR of the two operands, and assigns the result to the left operand. To explain your example code: for (String search : textSearch.getValue()) matches |= field.contains(search); I presume matches is a boolean; this means that the bitwise operators behave the same as logical operators.