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
COLOR PICKER
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.
Java Assignment Operators
Java programming tutorial index.
The Java Assignment Operators are used when you want to assign a value to the expression. The assignment operator denoted by the single equal sign = .
In a Java assignment statement, any expression can be on the right side and the left side must be a variable name. For example, this does not mean that "a" is equal to "b", instead, it means assigning the value of 'b' to 'a'. It is as follows:
Java also has the facility of chain assignment operators, where we can specify a single value for multiple variables.
Java Tutorial
- Java - Home
- Java - Overview
- Java - History
- Java - Features
- Java Vs. C++
- JVM - Java Virtual Machine
- Java - JDK vs JRE vs JVM
- Java - Hello World Program
- Java - Environment Setup
- Java - Basic Syntax
- Java - Variable Types
- Java - Data Types
- Java - Type Casting
- Java - Unicode System
- Java - Basic Operators
- Java - Comments
- Java - User Input
- Java - Date & Time
Java Control Statements
- Java - Loop Control
- Java - Decision Making
- Java - If-else
- Java - Switch
- Java - For Loops
- Java - For-Each Loops
- Java - While Loops
- Java - do-while Loops
- Java - Break
- Java - Continue
Object Oriented Programming
- Java - OOPs Concepts
- Java - Object & Classes
- Java - Class Attributes
- Java - Class Methods
- Java - Methods
- Java - Variables Scope
- Java - Constructors
- Java - Access Modifiers
- Java - Inheritance
- Java - Aggregation
- Java - Polymorphism
- Java - Overriding
- Java - Method Overloading
- Java - Dynamic Binding
- Java - Static Binding
- Java - Instance Initializer Block
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java - Inner Classes
- Java - Static Class
- Java - Anonymous Class
- Java - Singleton Class
- Java - Wrapper Classes
- Java - Enums
- Java - Enum Constructor
- Java - Enum Strings
- Java - Reflection
Java Built-in Classes
- Java - Number
- Java - Boolean
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Math Class
Java File Handling
- Java - Files
- Java - Create a File
- Java - Write to File
- Java - Read Files
- Java - Delete Files
- Java - Directories
- Java - I/O Streams
Java Error & Exceptions
- Java - Exceptions
- Java - try-catch Block
- Java - try-with-resources
- Java - Multi-catch Block
- Java - Nested try Block
- Java - Finally Block
- Java - throw Exception
- Java - Exception Propagation
- Java - Built-in Exceptions
- Java - Custom Exception
- Java - Annotations
- Java - Logging
- Java - Assertions
Java Multithreading
- Java - Multithreading
- Java - Thread Life Cycle
- Java - Creating a Thread
- Java - Starting a Thread
- Java - Joining Threads
- Java - Naming Thread
- Java - Thread Scheduler
- Java - Thread Pools
- Java - Main Thread
- Java - Thread Priority
- Java - Daemon Threads
- Java - Thread Group
- Java - Shutdown Hook
Java Synchronization
- Java - Synchronization
- Java - Block Synchronization
- Java - Static Synchronization
- Java - Inter-thread Communication
- Java - Thread Deadlock
- Java - Interrupting a Thread
- Java - Thread Control
- Java - Reentrant Monitor
Java Networking
- Java - Networking
- Java - Socket Programming
- Java - URL Processing
- Java - URL Class
- Java - URLConnection Class
- Java - HttpURLConnection Class
- Java - Socket Class
- Java - ServerSocket Class
- Java - InetAddress Class
- Java - Generics
Java Collections
- Java - Collections
- Java - Collection Interface
Java Interfaces
- Java - List Interface
- Java - Queue Interface
- Java - Map Interface
- Java - SortedMap Interface
- Java - Set Interface
- Java - SortedSet Interface
Java Data Structures
- Java - Data Structures
- Java - Enumeration
Java Collections Algorithms
- Java - Collections Algorithms
- Java - Iterators
- Java - Comparators
- Java - Comparable Interface in Java
Advanced Java
- Java - Command-Line Arguments
- Java - Lambda Expressions
- Java - Sending Email
- Java - Applet Basics
- Java - Javadoc Comments
- Java - Autoboxing and Unboxing
- Java - File Mismatch Method
- Java - REPL (JShell)
- Java - Multi-Release Jar Files
- Java - Private Interface Methods
- Java - Inner Class Diamond Operator
- Java - Multiresolution Image API
- Java - Collection Factory Methods
- Java - Module System
- Java - Nashorn JavaScript
- Java - Optional Class
- Java - Method References
- Java - Functional Interfaces
- Java - Default Methods
- Java - Base64 Encode Decode
- Java - Switch Expressions
- Java - Teeing Collectors
- Java - Microbenchmark
- Java - Text Blocks
- Java - Dynamic CDS archive
- Java - Z Garbage Collector (ZGC)
- Java - Null Pointer Exception
- Java - Packaging Tools
- Java - NUMA Aware G1
- Java - Sealed Classes
- Java - Record Classes
- Java - Hidden Classes
- Java - Pattern Matching
- Java - Compact Number Formatting
- Java - Programming Examples
- Java - Garbage Collection
- Java - JIT Compiler
Java Miscellaneous
- Java - Recursion
- Java - Regular Expressions
- Java - Serialization
- Java - Process API Improvements
- Java - Stream API Improvements
- Java - Enhanced @Deprecated Annotation
- Java - CompletableFuture API Improvements
- Java - Maths Methods
- Java - Streams
- Java - Datetime Api
- Java 8 - New Features
- Java 9 - New Features
- Java 10 - New Features
- Java 11 - New Features
- Java 12 - New Features
- Java 13 - New Features
- Java 14 - New Features
- Java 15 - New Features
- Java 16 - New Features
- Java - Keywords Reference
Java APIs & Frameworks
- JDBC Tutorial
- SWING Tutorial
- AWT Tutorial
- Servlets Tutorial
- JSP Tutorial
Java Class References
- Java - Scanner
- Java - Date
- Java - ArrayList
- Java - Vector
- Java - Stack
- Java - PriorityQueue
- Java - Deque Interface
- Java - LinkedList
- Java - ArrayDeque
- Java - HashMap
- Java - LinkedHashMap
- Java - WeakHashMap
- Java - EnumMap
- Java - TreeMap
- Java - IdentityHashMap
- Java - HashSet
- Java - EnumSet
- Java - LinkedHashSet
- Java - TreeSet
- Java - BitSet
- Java - Dictionary
- Java - Hashtable
- Java - Properties
- Java - Collection
- Java - Array
Java Useful Resources
- Java Compiler
- Java - Questions and Answers
- Java 8 - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
Java - Assignment Operators with Examples
Java assignment operators.
Following are the assignment operators supported by Java language −
Operator | Description | Example |
---|---|---|
= | Simple assignment operator. Assigns values from right side operands to left side operand. | C = A + B will assign value of A + B into C |
+= | Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. | C += A is equivalent to C = C + A |
-= | Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand. | C -= A is equivalent to C = C − A |
*= | Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand. | C *= A is equivalent to C = C * A |
/= | Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand. | C /= A is equivalent to C = C / A |
%= | Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand. | C %= A is equivalent to C = C % A |
<<= | Left shift AND assignment operator. | C <<= 2 is same as C = C << 2 |
>>= | Right shift AND assignment operator. | C >>= 2 is same as C = C >> 2 |
&= | Bitwise AND assignment operator. | C &= 2 is same as C = C & 2 |
^= | bitwise exclusive OR and assignment operator. | C ^= 2 is same as C = C ^ 2 |
|= | bitwise inclusive OR and assignment operator. | C |= 2 is same as C = C | 2 |
The following programs are simple examples which demonstrate the assignment operators. Copy and paste the following Java programs as Test.java file, and compile and run the programs −
In this example, we're creating three variables a,b and c and using assignment operators . We've performed simple assignment, addition AND assignment, subtraction AND assignment and multiplication AND assignment operations and printed the results.
In this example, we're creating two variables a and c and using assignment operators . We've performed Divide AND assignment, Multiply AND assignment, Modulus AND assignment, bitwise exclusive OR AND assignment, OR AND assignment operations and printed the results.
In this example, we're creating two variables a and c and using assignment operators . We've performed Left shift AND assignment, Right shift AND assignment, operations and printed the results.
JavaScript disabled. A lot of the features of the site won't work. Find out how to turn on JavaScript HERE .
- Fundamentals
- Objects & Classes
- OO Concepts
- API Contents
- Input & Output
- Collections
- Concurrency
- Swing & RMI
- Certification
Assignment Operators J8 Home « Assignment Operators
- << Relational & Logical Operators
- Bitwise Logical Operators >>
Symbols used for mathematical and logical manipulation that are recognized by the compiler are commonly known as operators in Java. In the third of five lessons on operators we look at the assignment operators available in Java.
Assignment Operators Overview Top
The single equal sign = is used for assignment in Java and we have been using this throughout the lessons so far. This operator is fairly self explanatory and takes the form variable = expression; . A point to note here is that the type of variable must be compatible with the type of expression .
Shorthand Assignment Operators
The shorthand assignment operators allow us to write compact code that is implemented more efficiently.
Operator | Meaning | Example | Result | Notes |
---|---|---|---|---|
+= | Addition | 10 | ||
-= | Subtraction | 0 | ||
/= | Division | 3 | When used with an type, any remainder will be truncated. | |
*= | Multiplication | 25 | ||
%= | Modulus | 1 | Holds the remainder value of a division. | |
&= | AND | | Will check both operands for values and assign or to the first operand dependant upon the outcome of the expression. | |
|= | OR | | Will check both operands for values and assign or to the first operand dependant upon the outcome of the expression. | |
^= | XOR | | Will check both operands for different values and assign or to the first operand dependant upon the outcome of the expression. |
Automatic Type Conversion, Assignment Rules Top
The following table shows which types can be assigned to which other types, of course we can assign to the same type so these boxes are greyed out.
When using the table use a row for the left assignment and a column for the right assignment. So in the highlighted permutations byte = int won't convert and int = byte will convert.
Type | ||||||||
---|---|---|---|---|---|---|---|---|
NO | NO | NO | NO | NO | NO | NO | ||
NO | NO | NO | NO | NO | NO | NO | ||
NO | NO | NO | NO | NO | NO | NO | ||
NO | NO | YES | NO | NO | NO | NO | ||
NO | YES | YES | YES | NO | NO | NO | ||
NO | YES | YES | YES | YES | NO | NO | ||
NO | YES | YES | YES | YES | YES | NO | ||
NO | YES | YES | YES | YES | YES | YES |
Casting Incompatible Types Top
The above table isn't the end of the story though as Java allows us to cast incompatible types. A cast instructs the compiler to convert one type to another enforcing an explicit type conversion.
A cast takes the form target = (target-type) expression .
There are a couple of things to consider when casting incompatible types:
- With narrowing conversions such as an int to a short there may be a loss of precision if the range of the int exceeds the range of a short as the high order bits will be removed.
- When casting a floating-point type to an integer type the fractional component is lost through truncation.
- The target-type can be the same type as the target or a narrowing conversion type.
- The boolean type is not only incompatible but also inconvertible with other types.
Lets look at some code to see how casting works and the affect it has on values:
Running the Casting class produces the following output:
The first thing to note is we got a clean compile because of the casts, all the type conversions would fail otherwise. You might be suprised by some of the results shown in the screenshot above, for instance some of the values have become negative. Because we are truncating everything to a byte we are losing not only any fractional components and bits outside the range of a byte , but in some cases the signed bit as well. Casting can be very useful but just be aware of the implications to values when you enforce explicit type conversion.
Related Quiz
Fundamentals Quiz 8 - Assignment Operators Quiz
Lesson 9 Complete
In this lesson we looked at the assignment operators used in Java.
What's Next?
In the next lesson we look at the bitwise logical operators used in Java.
Getting Started
Code structure & syntax, java variables, primitives - boolean & char data types, primitives - numeric data types, method scope, arithmetic operators, relational & logical operators, assignment operators, assignment operators overview, automatic type conversion, casting incompatible types, bitwise logical operators, bitwise shift operators, if construct, switch construct, for construct, while construct.
Java 8 Tutorials
01 Career Opportunities
02 beginner, 03 intermediate, 04 questions, 05 training programs, assignment operator in java, java online course free with certificate (2024), assignment operators in java: an overview, what are the assignment operators in java.
| |
(Guaranteed Path to ₹3 - ₹9 LPA* Jobs) | ! |
Types of Assignment Operators in Java
1. simple assignment operator (=):, explanation, 2. addition assignment operator (+=) :, 3. subtraction operator (-=):, 4. multiplication operator (*=):, 5. division operator (/=):, 6. modulus assignment operator (%=):, example of assignment operator in java, q1. can i use multiple assignment operators in a single statement, q2. are there any other compound assignment operators in java, q3. how many types of assignment operators, live classes schedule.
Filling Fast | |
Filling Fast | |
Filling Fast | |
Filling Fast | |
Filling Fast | |
Filling Fast | |
Filling Fast |
About Author
- Java Operators
Last updated: January 8, 2024
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
>> Download the E-book
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:
>> Explore a clean Baeldung
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.
Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.
To learn more about Java features on Azure Container Apps, visit the documentation page .
You can also ask questions and leave feedback on the Azure Container Apps GitHub page .
Java applications have a notoriously slow startup and a long warmup time. The CRaC (Coordinated Restore at Checkpoint) project from OpenJDK can help improve these issues by creating a checkpoint with an application's peak performance and restoring an instance of the JVM to that point.
To take full advantage of this feature, BellSoft provides containers that are highly optimized for Java applications. These package Alpaquita Linux (a full-featured OS optimized for Java and cloud environment) and Liberica JDK (an open-source Java runtime based on OpenJDK).
These ready-to-use images allow us to easily integrate CRaC in a Spring Boot application:
Improve Java application performance with CRaC support
Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.
Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.
With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.
Try a 14-Day Free Trial of Orkes Conductor today.
To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .
And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .
Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.
Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.
Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.
The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:
>> Become an efficient full-stack developer with Jmix
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
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
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
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Download the E-book
Do JSON right with Jackson
Get the most out of the Apache HTTP Client
Get Started with Apache Maven:
Working on getting your persistence layer right with Spring?
Explore the eBook
Building a REST API with Spring?
Get started with Spring and Spring Boot, through the Learn Spring course:
Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
>> The New “REST With Spring Boot”
Get started with Spring and Spring Boot, through the reference Learn Spring course:
>> LEARN SPRING
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
1. Overview
Operators are a fundamental building block of any programming language. We use operators to perform operations on values and variables.
Java provides many groups of operators. They are categorized by their functionalities.
In this tutorial, we’ll walk through all Java operators to understand their functionalities and how to use them.
2. Arithmetic Operators
We use arithmetic operators to perform simple mathematical operations. We should note that arithmetic operators only work with primitive number types and their boxed types , such as int and Integer .
Next, let’s see what operators we have in the arithmetic operator group.
2.1. The Addition Operator
The addition operator (+) allows us to add two values or concatenate two strings:
2.2. The Subtraction Operator
Usually, we use the subtraction operator (-) to subtract one value from another:
2.3. The Multiplication Operator
The multiplication operator (*) is used to multiply two values or variables:
2.4. The Division Operator
The division operator (/) allows us to divide the left-hand value by the right-hand one:
When we use the division operator on two integer values ( byte , short , int , and long ), we should note that the result is the quotient value. The remainder is not included .
As the example above shows, if we calculate 15 / 2 , the quotient is 7, and the remainder is 1 . Therefore, we have 15 / 2 = 7 .
2.5. The Modulo Operator
We can get the quotient using the division operator. However, if we just want to get the remainder of a division calculation, we can use the modulo operator (%):
3. Unary Operators
As the name implies, unary operators only require one single operand . For example, we usually use unary operators to increment, decrement, or negate a variable or value.
Now, let’s see the details of unary operators in Java.
3.1. The Unary Plus Operator
The unary plus operator (+) indicates a positive value. If the number is positive, we can omit the ‘+’ operator:
3.2. The Unary Minus Operator
Opposite to the unary plus operator, the unary minus operator (-) negates a value or an expression:
3.3. The Logical Complement Operator
The logical complement operator (!) is also known as the “NOT” operator . We can use it to invert the value of a boolean variable or value:
3.4. The Increment Operator
The increment operator (++) allows us to increase the value of a variable by 1:
3.5. The Decrement Opeartor
The decrement operator (–) does the opposite of the increment operator. It decreases the value of a variable by 1:
We should keep in mind that the increment and decrement operators can only be used on a variable . For example, “ int a = 5; a++; ” is fine. However, the expression “ 5++ ” won’t be compiled.
4. Relational Operators
Relational operators can be called “comparison operators” as well. Basically, we use these operators to compare two values or variables.
4.1. The “Equal To” Operator
We use the “equal to” operator (==) to compare the values on both sides. If they’re equal, the operation returns true :
The “equal to” operator is pretty straightforward. On the other hand, the Object class has provided the equals() method. As the Object class is the superclass of all Java classes, all Java objects can use the equals() method to compare each other.
When we want to compare two objects – for instance, when we compare Long objects or compare String s – we should choose between the comparison method from the equals() method and that of the “equal to” operator wisely .
4.2. The “Not Equal To” Operator
The “not equal to” operator (!=) does the opposite of the ‘==’ operator. If the values on both sides are not equal, the operation returns true :
4.3. The “Greater Than” Operator
When we compare two values with the “greater than” operator (>), it returns true if the value on the left-hand side is greater than the value on the right-hand side:
4.4. The “Greater Than or Equal To” Operator
The “greater than or equal to” operator (>=) compares the values on both sides and returns true if the left-hand side operand is greater than or equal to the right-hand side operand:
4.5. The “Less Than” Operator
The “less than” operator (<) compares two values on both sides and returns true if the value on the left-hand side is less than the value on the right-hand side:
4.6. The “Less Than or Equal To” Operator
Similarly, the “less than or equal to” operator (<=) compares the values on both sides and returns true if the left-hand side operand is less than or equal to the right-hand side:
5. Logical Operators
We have two logical operators in Java: the logical AND and OR operators. Basically, their function is pretty similar to the AND gate and the OR gate in digital electronics.
Usually, we use a logical operator with two operands, which are variables or expressions that can be evaluated as boolean .
Next, let’s take a closer look at them.
5.1. The Logical AND Operator
The logical AND operator ( && ) returns true only if both operands are true :
5.2. The Logical OR Operator
Unlike the ‘ && ‘ operator, the logical OR operator ( || ) returns true if at least one operand is true :
We should note that the logical OR operator has the short-circuiting effect : It returns true as soon as one of the operands is evaluated as true, without evaluating the remaining operands.
6. Ternary Operator
A ternary operator is a short form of the if-then-else statement. It has the name ternary as it has three operands. First, let’s have a look at the standard if-then-else statement syntax:
We can convert the above if-then-else statement into a compact version using the ternary operator:
Let’s look at its syntax:
Next, let’s understand how the ternary operator works through a simple example:
7. Bitwise and Bit Shift Operators
As the article “ Java bitwise operators ” covers the details of bitwise and bit shift operators, we’ll briefly summarize these operators in this tutorial.
7.1. The Bitwise AND Operator
The bitwise AND operator (&) returns the bit-by-bit AND of input values:
7.2. The Bitwise OR Operator
The bitwise OR operator (|) returns the bit-by-bit OR of input values:
7.3. The Bitwise XOR Operator
The bitwise XOR (exclusive OR) operator (^) returns the bit-by-bit XOR of input values:
7.4. The Bitwise Complement Operator
The bitwise complement operator (~) is a unary operator. It returns the value’s complement representation, which inverts all bits from the input value:
7.5. The Left Shift Operator
Shift operators shift the bits to the left or right by the given number of times.
The left shift operator (<<) shifts the bits to the left by the number of times defined by the right-hand side operand. After the left shift, the empty space in the right is filled with 0.
Next, let’s left shift the number 12 twice:
n << x has the same effect of multiplying the number n with x power of two.
7.6. The Signed Right Shift Operator
The signed right shift operator (>>) shifts the bits to the right by the number of times defined by the right-hand side operand and fills 0 on voids left as a result.
We should note that the leftmost position after the shifting depends on the sign extension .
Next, let’s do “signed right shift” twice on the numbers 12 and -12 to see the difference:
As the second example above shows, if the number is negative, the leftmost position after each shift will be set by the sign extension.
n >> x has the same effect of dividing the number n by x power of two.
7.7. The Unsigned Right Shift Operator
The unsigned right shift operator (>>>) works in a similar way as the ‘>>’ operator. The only difference is that after a shift, the leftmost bit is set to 0 .
Next, let’s unsigned right shift twice on the numbers 12 and -12 to see the difference:
As we can see in the second example above, the >>> operator fills voids on the left with 0 irrespective of whether the number is positive or negative .
8. The “ instanceof ” Operator
Sometimes, when we have an object, we would like to test if it’s an instance of a given type . The “ instanceof ” operator can help us to do it:
9. Assignment Operators
We use assignment operators to assign values to variables. 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, we’ve used it many times in previous examples. It assigns the value on its right to the operand on its left:
9.2. Compound Assignments
We’ve learned arithmetic operators. We can combine the arithmetic operators with the simple assignment operator to create compound assignments.
For example, we can write “ a = a + 5 ” in a compound way: “ a += 5 “.
Finally, let’s walk through all supported compound assignments in Java through examples:
10. Conclusion
Java provides many groups of operators for different functionalities. In this article, we’ve passed through the operators in Java.
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.
Get started with Spring Boot and with core Spring, through the Learn Spring course:
>> CHECK OUT THE COURSE
- C Programming
- Java Programming
- Data Structures
- Web Development
- Tech Interview
Java's Basic and Shorthand Assignment Operators
Reference assignment, primitive assignment, primitive casting, shorthand assignment operators, basic assignment operator.
Java's basic assignment operator is a single equals-to (=) sign that assigns the right-hand side value to the left-hand side operand. On left side of the assignment operator there must be a variable that can hold the value assigned to it. Assignment operator operates on both primitive and reference types. It has the following syntax: var = expression; Note that the type of var must be compatible with the type of expression .
Chaining of assignment operator is also possible where we can create a chain of assignments in order to assign a single value to multiple variables. For example,
The above piece of code sets the variables x, y, and z to 100 using a single statement. This works because the = is an operator that yields the value of the right-hand expression. Thus, the value of z = 100 is 100, which is then assigned to y , which in turn is assigned to x . Using a "chain of assignment" is an easy way to set a group of variables to a common value.
A variable referring to an object is a reference variable not an object. We can assign a newly created object to an object reference variable as follows:
The above line of code performs three tasks
- Creates a reference variable named st1 , of type Student .
- Creates a new Student object on the heap.
- Assigns the newly created Student object to the reference variable st1
We can also assign null to an object reference variable, which simply means the variable is not referring to any object:
Above line of code creates space for the Student reference variable st2 but doesn't create an actual Student object.
Note that, we can also use a reference variable to refer to any object that is a subclass of the declared reference variable type.
Primitive variables can be assigned either by using a literal or the result of an expression. For example,
The most important point that we should keep in mind, while assigning primitive types is if we are going to assign a bigger value to a smaller type, we have to typecast it properly. In Above piece of code the literal integer 130 is implicitly an int but it is acceptable here because the variable x is of type int . It gets weird if you try 130 to assign to a byte variable. For example, The below piece of code will not compile because literal 130 is implicitly an integer and it does not fit into a smaller type byte x . Likewise, byte c = a + b will also not compile because the result of an expression involving anything int-sized or smaller is always an int .
Casting lets us convert primitive values from one type to another (specially from bigger to smaller types). Casts can be implicit or explicit. An implicit cast means we don't have to write code for the cast; the conversion happens automatically. Typically, an implicit cast happens when we do a widening conversion. In other words, putting a smaller thing (say, a byte ) into a bigger container (like an int ). Remember those "possible loss of precision" compiler errors we saw during assignments. Those happened when we tried to put a larger thing (say, an int ) into a smaller container (like a byte ). The large-value-into-small-container conversion is referred to as narrowing and requires an explicit cast, where we tell the compiler that we are aware of the danger and accept full responsibility.
As a final note on casting, it is very important to note that the shorthand assignment operators let us perform addition, subtraction, multiplication or division without putting in an explicit cast. In fact, +=, -=, *=, and /= will all put in an implicit cast. Below is an example:
In addition to the basic assignment operator, Java also defines 12 shorthand assignment operators that combine assignment with the 5 arithmetic operators ( += , -= , *= , /= , %= ) and the 6 bitwise and shift operators ( &= , |= , ^= , <<= , >>= , >>>= ). For example, the += operator reads the value of the left variable, adds the value of the right operand to it, stores the sum back into the left variable as a side effect, and returns the sum as the value of the expression. Thus, the expression x += 2 is almost the same x = x + 2 .
The difference between these two expressions is that when we use the += operator, the left operand is evaluated only once. This makes a difference when that operand has a side effect. Consider the following two expressions a[i++] += 2; and a[i++] = a[i++] + 2; , which are not equivalent:
In this tutorial we discussed basic and shorthand (compound) assignment operators of Java. Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!
- Core Java Volume I - Fundamentals
- Java: The Complete Reference, Seventh Edition
- Operators: Sun tutorial
- Bit Twiddling Hacks
- C Programming Tutorials
- Java Programming Tutorials
- Data Structures Tutorials
- All Tech Interview Questions
- C Interview Question Answers
- Java Interview Question Answers
- DSA Interview Question Answers
Get Free Tutorials by Email
About the Author
Krishan Kumar is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.
Today's Tech News
- Write For Us
- ▼Java Tutorial
- Introduction
- Java Program Structure
- Java Primitive data type
- ▼Development environment setup
- Download and Install JDK, Eclipse (IDE)
- Compiling, running and debugging Java programs
- ▼Declaration and Access control
- Class, methods, instance variables
- Java Packages
- ▼OOPS Concepts
- Java Object Oriented Programming concepts
- Is-A and Has-A relationship
- ▼Assignments
- Arrays - 2D array and Multi dimension array
- Wrapper classes
- ▼Operators
- Assignment Operator
- Arithmetic Operator
- Conditional Operator
- Logical Operator
- ▼Flow Control
- Switch Satement
- While and Do loop
- Java Branching Statements
- ▼Exceptions
- Handling Exceptions
- Checked and unchecked
- Custom Exception
- Try with resource feature of Java 7
- ▼String Class
- String Class
- Important methods of String class with example
- String buffer class and string builder class
- ▼File I/O and serialization
- File Input and Output
- Reading file
- Writing file
- Java Property File Processing
- Java Serialization
- ▼Java Collection
- Java Collection Framework
- Java ArrayList and Vector
- Java LinkedList Class
- Java HashSet
- Java TreeSet
- Java Linked HashSet
- Java Utility Class
- ▼Java Thread
- Java Defining, Instantiating and Starting Thread
- Java Thread States and Transitions
- Java Thread Interaction
- Java Code Synchronization
- ▼Java Package
- ▼Miscellaneous
- Garbage Collection in Java
- BigDecimal Method
Java Assignment Operators
Description.
Assigning a value to a variable seems straightforward enough; you simply assign the stuff on the right side of the '= 'to the variable on the left. Below statement 1 assigning value 10 to variable x and statement 2 is creating String object called name and assigning value "Amit" to it.
Assignment can be of various types. Let’s discuss each in detail.
Primitive Assignment:
The equal (=) sign is used for assigning a value to a variable. We can assign a primitive variable using a literal or the result of an expression.
Primitive Casting
Casting lets you convert primitive values from one type to another. We need to provide casting when we are trying to assign higher precision primitive to lower precision primitive for example If we try to assign int variable (which is in the range of byte variable) to byte variable then the compiler will throw an exception called "possible loss of precision". Eclipse IDE will suggest the solution as well as shown below. To avoid such problem we should use type casting which will instruct compiler for type conversion.
For cases where we try to assign smaller container variable to larger container variables we do not need of explicit casting. The compiler will take care of those type conversions. For example, we can assign byte variable or short variable to an int without any explicit casting.
Assigning Literal that is too large for a variable
When we try to assign a variable value which is too large (or out of range ) for a primitive variable then the compiler will throw exception “possible loss of precision” if we try to provide explicit cast then the compiler will accept it but narrowed down the value using two’s complement method. Let’s take an example of the byte which has 8-bit storage space and range -128 to 127. In below program we are trying to assign 129 literal value to byte primitive type which is out of range for byte so compiler converted it to -127 using two’s complement method. Refer link for two’s complement calculation (http://en.wikipedia.org/wiki/Two's_complement)
Java Code: Go to the editor
Reference variable assignment
We can assign newly created object to object reference variable as below
First line will do following things,
- Makes a reference variable named s of type String
- Creates a new String object on the heap memory
- Assigns the newly created String object to the reference variables
You can also assign null to an object reference variable, which simply means the variable is not referring to any object. The below statement creates space for the Employee reference variable (the bit holder for a reference value) but doesn't create an actual Employee object.
Compound Assignment Operators
Sometime we need to modify the same variable value and reassigned it to a same reference variable. Java allows you to combine assignment and addition operators using a shorthand operator. For example, the preceding statement can be written as:
The += is called the addition assignment operator. Other shorthand operators are shown below table
Operator | Name | Example | Equivalent |
---|---|---|---|
+= | Addition assignment | i+=5; | i=i+5 |
-= | Subtraction assignment | j-=10; | j=j-10; |
*= | Multiplication assignment | k*=2; | k=k*2; |
/= | Division assignment | x/=10; | x=x/10; |
%= | Remainder assignment | a%=4; | a=a%4; |
Below is the sample program explaining assignment operators:
- Assigning a value to can be straight forward or casting.
- If we assign the value which is out of range of variable type then 2’s complement is assigned.
- Java supports shortcut/compound assignment operator.
Java Code Editor:
Previous: Wrapper classes Next: Arithmetic Operator
Follow us on Facebook and Twitter for latest update.
- Weekly Trends and Language Statistics
Learn Java practically and Get Certified .
Popular Tutorials
Popular examples, reference materials, learn java interactively, java introduction.
- Get Started With Java
- Your First Java Program
- Java Comments
Java Fundamentals
- Java Variables and Literals
- Java Data Types (Primitive)
Java Operators
- Java Basic Input and Output
- Java Expressions, Statements and Blocks
Java Flow Control
- Java if...else Statement
Java Ternary Operator
- Java for Loop
- Java for-each Loop
- Java while and do...while Loop
- Java break Statement
- Java continue Statement
- Java switch Statement
- Java Arrays
- Java Multidimensional Arrays
- Java Copy Arrays
Java OOP(I)
- Java Class and Objects
- Java Methods
- Java Method Overloading
- Java Constructors
- Java Static Keyword
- Java Strings
- Java Access Modifiers
- Java this Keyword
- Java final keyword
- Java Recursion
Java instanceof Operator
Java OOP(II)
- Java Inheritance
- Java Method Overriding
- Java Abstract Class and Abstract Methods
- Java Interface
- Java Polymorphism
- Java Encapsulation
Java OOP(III)
- Java Nested and Inner Class
- Java Nested Static Class
- Java Anonymous Class
- Java Singleton Class
- Java enum Constructor
- Java enum Strings
- Java Reflection
- Java Package
- Java Exception Handling
- Java Exceptions
- Java try...catch
- Java throw and throws
- Java catch Multiple Exceptions
- Java try-with-resources
- Java Annotations
- Java Annotation Types
- Java Logging
- Java Assertions
- Java Collections Framework
- Java Collection Interface
- Java ArrayList
- Java Vector
- Java Stack Class
- Java Queue Interface
- Java PriorityQueue
- Java Deque Interface
- Java LinkedList
- Java ArrayDeque
- Java BlockingQueue
- Java ArrayBlockingQueue
- Java LinkedBlockingQueue
- Java Map Interface
- Java HashMap
- Java LinkedHashMap
- Java WeakHashMap
- Java EnumMap
- Java SortedMap Interface
- Java NavigableMap Interface
- Java TreeMap
- Java ConcurrentMap Interface
- Java ConcurrentHashMap
- Java Set Interface
- Java HashSet Class
- Java EnumSet
- Java LinkedHashSet
- Java SortedSet Interface
- Java NavigableSet Interface
- Java TreeSet
- Java Algorithms
- Java Iterator Interface
- Java ListIterator Interface
Java I/o Streams
- Java I/O Streams
- Java InputStream Class
- Java OutputStream Class
- Java FileInputStream Class
- Java FileOutputStream Class
- Java ByteArrayInputStream Class
- Java ByteArrayOutputStream Class
- Java ObjectInputStream Class
- Java ObjectOutputStream Class
- Java BufferedInputStream Class
- Java BufferedOutputStream Class
- Java PrintStream Class
Java Reader/Writer
- Java File Class
- Java Reader Class
- Java Writer Class
- Java InputStreamReader Class
- Java OutputStreamWriter Class
- Java FileReader Class
- Java FileWriter Class
- Java BufferedReader
- Java BufferedWriter Class
- Java StringReader Class
- Java StringWriter Class
- Java PrintWriter Class
Additional Topics
- Java Keywords and Identifiers
Java Operator Precedence
Java Bitwise and Shift Operators
- Java Scanner Class
- Java Type Casting
- Java Wrapper Class
- Java autoboxing and unboxing
- Java Lambda Expressions
- Java Generics
- Nested Loop in Java
- Java Command-Line Arguments
Java Tutorials
- Java Math IEEEremainder()
Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while * is also an operator used for multiplication.
Operators in Java can be classified into 5 types:
- Arithmetic Operators
- Assignment Operators
- Relational Operators
- Logical Operators
- Unary Operators
- Bitwise Operators
1. Java Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For example,
Here, the + operator is used to add two variables a and b . Similarly, there are various other arithmetic operators in Java.
Operator | Operation |
Addition | |
Subtraction | |
Multiplication | |
Division | |
Modulo Operation (Remainder after division) |
Example 1: Arithmetic Operators
In the above example, we have used + , - , and * operators to compute addition, subtraction, and multiplication operations.
/ Division Operator
Note the operation, a / b in our program. The / operator is the division operator.
If we use the division operator with two integers, then the resulting quotient will also be an integer. And, if one of the operands is a floating-point number, we will get the result will also be in floating-point.
% Modulo Operator
The modulo operator % computes the remainder. When a = 7 is divided by b = 4 , the remainder is 3 .
Note : The % operator is mainly used with integers.
2. Java Assignment Operators
Assignment operators are used in Java to assign values to variables. For example,
Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is assigned to the variable age .
Let's see some more assignment operators available in Java.
Operator | Example | Equivalent to |
---|---|---|
Example 2: Assignment Operators
3. java relational operators.
Relational operators are used to check the relationship between two operands. For example,
Here, < operator is the relational operator. It checks if a is less than b or not.
It returns either true or false .
Operator | Description | Example |
---|---|---|
Is Equal To | returns | |
Not Equal To | returns | |
Greater Than | returns | |
Less Than | returns | |
Greater Than or Equal To | returns | |
Less Than or Equal To | returns |
Example 3: Relational Operators
Note : Relational operators are used in decision making and loops.
4. Java Logical Operators
Logical operators are used to check whether an expression is true or false . They are used in decision making.
Operator | Example | Meaning |
---|---|---|
(Logical AND) | expression1 expression2 | only if both and are |
(Logical OR) | expression1 expression2 | if either or is |
(Logical NOT) | expression | if is and vice versa |
Example 4: Logical Operators
Working of Program
- (5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true .
- (5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false .
- (5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true .
- (5 > 3) || (8 < 5) returns true because the expression (5 > 3) is true .
- (5 < 3) || (8 < 5) returns false because both (5 < 3) and (8 < 5) are false .
- !(5 == 3) returns true because 5 == 3 is false .
- !(5 > 3) returns false because 5 > 3 is true .
5. Java Unary Operators
Unary operators are used with only one operand. For example, ++ is a unary operator that increases the value of a variable by 1 . That is, ++5 will return 6 .
Different types of unary operators are:
Operator | Meaning |
---|---|
: not necessary to use since numbers are positive without using it | |
: inverts the sign of an expression | |
: increments value by 1 | |
: decrements value by 1 | |
: inverts the value of a boolean |
- Increment and Decrement Operators
Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the value of the operand by 1 , while -- decrease it by 1 . For example,
Here, the value of num gets increased to 6 from its initial value of 5 .
Example 5: Increment and Decrement Operators
In the above program, we have used the ++ and -- operator as prefixes (++a, --b) . We can also use these operators as postfix (a++, b++) .
There is a slight difference when these operators are used as prefix versus when they are used as a postfix.
To learn more about these operators, visit increment and decrement operators .
6. Java Bitwise Operators
Bitwise operators in Java are used to perform operations on individual bits. For example,
Here, ~ is a bitwise operator. It inverts the value of each bit ( 0 to 1 and 1 to 0 ).
The various bitwise operators present in Java are:
Operator | Description |
---|---|
Bitwise Complement | |
Left Shift | |
Right Shift | |
Unsigned Right Shift | |
Bitwise AND | |
Bitwise exclusive OR |
These operators are not generally used in Java. To learn more, visit Java Bitwise and Bit Shift Operators .
Other operators
Besides these operators, there are other additional operators in Java.
The instanceof operator checks whether an object is an instanceof a particular class. For example,
Here, str is an instance of the String class. Hence, the instanceof operator returns true . To learn more, visit Java instanceof .
The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example,
Here's how it works.
- If the Expression is true , expression1 is assigned to the variable .
- If the Expression is false , expression2 is assigned to the variable .
Let's see an example of a ternary operator.
In the above example, we have used the ternary operator to check if the year is a leap year or not. To learn more, visit the Java ternary operator .
Now that you know about Java operators, it's time to know about the order in which operators are evaluated. To learn more, visit Java Operator Precedence .
Table of Contents
- Introduction
- Java Arithmetic Operators
- Java Assignment Operators
- Java Relational Operators
- Java Logical Operators
- Java Unary Operators
- Java Bitwise Operators
Before we wrap up, let’s put your knowledge of Java Operators: Arithmetic, Relational, Logical and more to the test! Can you solve the following challenge?
Write a function to return the largest of two given numbers.
- Return the largest of two given numbers num1 and num2 .
- For example, if num1 = 4 and num2 = 5 , the expected output is 5 .
Sorry about that.
Our premium learning platform, created with over a decade of experience and thousands of feedbacks .
Learn and improve your coding skills like never before.
- Interactive Courses
- Certificates
- 2000+ Challenges
Related Tutorials
Java Tutorial
Java Operators
Learn about available Java operators, and precedence order and understand their usages with examples. We will also try to understand when to use which operator and what to expect in the result. 1. Java Operators An operator is a symbol that performs a specific operation on one, two, …
Lokesh Gupta
December 27, 2022
Learn about available Java operators , and precedence order and understand their usages with examples. We will also try to understand when to use which operator and what to expect in the result.
1. Java Operators
An operator is a symbol that performs a specific operation on one, two, or three operands, producing a result. The type of the operator and its operands determine the kind of operation performed on the operands and the type of result produced.
Operators in Java can be categorized based on two criteria:
- Number of operands – There are three types of operators based on the number of operands. An operator is called a unary, binary, or ternary operator based on the number of operands. If an operator takes one operand, it is called a unary operator; if it takes two operands, it is called a binary operator; if it takes three operands, it is called a ternary operator .
- Type of operation they perform – An operator is called an arithmetic operator , a relational operator , a logical operator , or a bitwise operator , depending on the kind of operation it performs on its operands.
Operator | Description |
---|---|
+ – * / | Arithmetic unary or binary operators |
++ — | Increment and decrement unary operators |
== != | Equality operators |
< > <= => | Relational operators |
! & | | Logical operators |
&& || ?: | Conditional operators |
= += -= *= /= %= | Assignment operators |
&= |= ^= <<= >>= >>>= | Assignment operators |
& | ~ ^ << >> >>> | Bitwise operators |
-> :: | Arrow and method reference operators |
Instance creation iterator | |
instanceOf | Type comparison operator |
+ | String concatenation operator |
Let us learn about few most used operators with examples.
2. Assignment Operator
- An assignment operator (=) is used to assign a value to a variable.
- It is a binary operator. It takes two operands.
- The value of the right-hand operand is assigned to the left-hand operand.
- The left-hand operand must be a variable.
Java ensures that the value of the right-hand operand of the assignment operator is assignment compatible to the data type of the left-hand operand. Otherwise, a compile-time error occurs.
In case of reference variables, you may be able to compile the source code and get a runtime ClassCastException error if the object represented by the right-hand operand is not assignment compatible to the reference variable as the left-hand operand.
3. Arithmetic Operators
- Operators like ( + (plus), – (minus), * (multiply), / (divide)) are called arithmetic operators in Java.
- It can only be used with numeric type operands. It means, both operands to arithmetic operators must be one of types byte , short , char , int , long , float , and double .
- These operators cannot have operands of boolean primitive type and reference type.
3.1. Unary Arithmetic Operators
; indicates positive value (numbers are positive without this, however) | |
; negates an expression value | |
; increments a value by 1 | |
; decrements a value by 1 | |
; inverts the value of a boolean |
3.2. Binary Arithmetic Operators
– Adds values on either side of the operator | |
– Subtracts right hand operand from left hand operand | |
– Multiplies values on either side of the operator | |
– Divides left hand operand by right hand operand | |
– Divides left hand operand by right hand operand and returns remainder |
4. String Concatenation Operator
The '+' operator is overloaded in Java. An operator is said to be overloaded if it is used to perform more than one function.
4.1. Concatenating Two Strings
So far, you have seen its use as an arithmetic addition operator to add two numbers. It can also be used to concatenate two strings .
4.2. Concatenating Primitive Types to String
The string concatenation operator is also used to concatenate a primitive and a reference data type value to a string.
4.3. Concatenate null
If a reference variable contains the ‘ null ‘ reference, the concatenation operator uses a string “null”.
5. Relational Operators
- All relational operators are binary operators.
- They take two operands.
- The result produced by a relational operator is always a Boolean value true or false .
- They are mostly used in Java control statements such as if statements , while statements etc.
Let’s see below all available relational operators in java.
– Checks if the values of two operands are equal or not, if yes then condition becomes true. | |
– Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. | |
– Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | |
– Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | |
– Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | |
– Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. |
6. Boolean Logical Operators
- All Boolean logical operators can be used only with boolean operand(s).
- They are mostly used in control statements to compare two (or more) conditions.
returns true if the operand is false, and false if the operand is true. | |
returns true if both operands are true. If either operand is false, it returns false. | |
returns true if both operands are true. If either operand is false, it returns false. | |
returns true if either operand is true. If both operands are false, it returns false. | |
returns true if either operand is true. If both operands are false, it returns false. | |
it returns true if one of the operands is true, but not both. If both operands are the same, it returns false. | |
if both operands evaluate to true, &= returns true. Otherwise, it returns false. | |
if either operand evaluates to true, != returns true. Otherwise, it returns false. | |
if both operands evaluate to different values, that is, one of the operands is true but not both, ^= returns true. Otherwise, it returns false. |
The logical AND operator ( & ) works the same way as the logical short-circuit AND operator ( && ), except for one difference. The logical AND operator (&) evaluates its right-hand operand even if its left-hand operand evaluates to false. The logical OR operator works the same way as the logical short-circuit OR operator, except for one difference. The logical OR operator evaluates its right-hand operand even if its left-hand operand evaluates to true.
7. Bitwise Operators
A bitwise operator manipulates individual bits of its operands. Java defines several bitwise operators, which can be applied to the integer types, long , int , short , char , and byte .
copies a bit to the result if it exists in both operands. | |
copies a bit if it exists in either operand. | |
copies the bit if it is set in one operand but not both. | |
is unary and has the effect of ‘flipping’ bits. | |
. The left operands value is moved left by the number of bits specified by the right operand. | |
. The left operands value is moved right by the number of bits specified by the right operand. | |
. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. |
8. Ternary Operator
- Java has one conditional operator. It is called a ternary operator as it takes three operands .
- The two symbols of “?” and “:” make the ternary operator.
- If the boolean-expression evaluates to true , it evaluates the true-expression ; otherwise, it evaluates false-expression.
9. Operators Precedence Table
Java has well-defined rules for specifying the order in which the operators in an expression are evaluated when the expression has several operators. For example, multiplication and division have higher precedence than addition and subtraction.
Precedence rules can be overridden by explicit parentheses.
When two operators share an operand the operator with the higher precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3) because the precedence of multiplication is higher than addition.
In the above expression, if you want to add values first then use explicit parentheses like this – (1 + 2) * 3 .
Precedence | Operator | Type | Associativity |
---|---|---|---|
15 | () [] · | Parentheses Array subscript Member selection | Left to Right
|
14 | ++ — | Unary post-increment Unary post-decrement | Right to left |
13 | ++ — + – ! ~ ( ) | Unary pre-increment Unary pre-decrement Unary plus Unary minus Unary logical negation Unary bitwise complement Unary type cast | Right to left |
12 | * / % | Multiplication Division Modulus | Left to right |
11 | + – | Addition Subtraction | Left to right |
10 | << >> >>> | Bitwise left shift Bitwise right shift with sign extension Bitwise right shift with zero extension | Left to right |
9 | < <= > >= instanceof | Relational less than Relational less than or equal Relational greater than Relational greater than or equal Type comparison (objects only) | Left to right |
8 | == != | Relational is equal to Relational is not equal to | Left to right |
7 | & | Bitwise AND | Left to right |
6 | ^ | Bitwise exclusive OR | Left to right |
5 | | | Bitwise inclusive OR | Left to right |
4 | && | Logical AND
| Left to right |
3 | || | Logical OR | Left to right |
2 | ? : | Ternary conditional | Right to left |
1 | = += -= *= /= %= | Assignment Addition assignment Subtraction assignment Multiplication assignment Division assignment Modulus assignment | Right to left |
That’s all for the operators in java.
Happy Learning !!
Weekly Newsletter
Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.
Little-Endian and Big-Endian in Java
Types of statements in java.
HowToDoInJava provides tutorials and how-to guides on Java and related technologies.
It also shares the best practices, algorithms & solutions and frequently asked interview questions.
Tutorial Series
Privacy Policy
REST API Tutorial
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.
Summary of Operators
The following quick reference summarizes the operators supported by the Java programming language.
Simple Assignment Operator
Arithmetic operators, unary operators, equality and relational operators, conditional operators, type comparison operator, bitwise and bit shift operators.
About Oracle | Contact Us | Legal Notices | Terms of Use | Your Privacy Rights
Copyright © 1995, 2022 Oracle and/or its affiliates. All rights reserved.
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
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.
Shortcut "or-assignment" (|=) operator in Java
I have a long set of comparisons to do in Java, and I'd like to know if one or more of them come out as true. The string of comparisons was long and difficult to read, so I broke it up for readability, and automatically went to use a shortcut operator |= rather than negativeValue = negativeValue || boolean .
I expect negativeValue to be true if any of the default<something> values are negative. Is this valid? Will it do what I expect? I couldn't see it mentioned on Sun's site or stackoverflow, but Eclipse doesn't seem to have a problem with it and the code compiles and runs.
Similarly, if I wanted to perform several logical intersections, could I use &= instead of && ?
- assignment-operator
- compound-assignment
- or-operator
- 13 Why don't you try it? – Roman Commented Mar 21, 2010 at 9:09
- This is general boolean logic, not Java only. so you can look it up on other places. And why don't you just try it? – Dykam Commented Mar 21, 2010 at 9:10
- 16 @Dykam: No, there's specific behaviour here. Java could choose to make |= short-circuiting, such that it won't evaluate the RHS if the LHS is already true - but it doesn't. – Jon Skeet Commented Mar 21, 2010 at 9:14
- 3 @Jon Skeet: Short-circuiting would be appropriate for the non-existent ||= operator, but |= is the combination form of the bitwise or operator. – David Thornley Commented Mar 22, 2010 at 14:07
- 1 @Jon Skeet: Sure, but making |= short-circuiting would be inconsistent with other compound assignment operators, since a |= b; would not be the same as a = a | b; , with the usual caveat about evaluating a twice (if it matters). It looks to me like the big language behavior decision was not having ||= , so I'm missing your point. – David Thornley Commented Mar 22, 2010 at 14:59
8 Answers 8
The |= is a compound assignment operator ( JLS 15.26.2 ) for the boolean logical operator | ( JLS 15.22.2 ); not to be confused with the conditional-or || ( JLS 15.24 ). There are also &= and ^= corresponding to the compound assignment version of the boolean logical & and ^ respectively.
In other words, for boolean b1, b2 , these two are equivalent:
The difference between the logical operators ( & and | ) compared to their conditional counterparts ( && and || ) is that the former do not "shortcircuit"; the latter do. That is:
- & and | always evaluate both operands
- (because no matter what the right operand evaluates to, the entire expression is false )
- (because no matter what the right operand evaluates to, the entire expression is true )
So going back to your original question, yes, that construct is valid, and while |= is not exactly an equivalent shortcut for = and || , it does compute what you want. Since the right hand side of the |= operator in your usage is a simple integer comparison operation, the fact that | does not shortcircuit is insignificant.
There are cases, when shortcircuiting is desired, or even required, but your scenario is not one of them.
It is unfortunate that unlike some other languages, Java does not have &&= and ||= . This was discussed in the question Why doesn't Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=) .
- +1, very thorough. it seems plausible that a compiler might well convert to a short-circuit operator, if it could determine that the RHS has no side effects. any clue about that? – Carl Commented Mar 22, 2010 at 14:23
- I read that when RHS is trivial and SC is not necessary, the "smart" SC operators are actually a bit slower. If true, then it's more interesting to wonder if some compilers can convert SC to NSC under certain circumstances. – polygenelubricants Commented Mar 22, 2010 at 15:08
- @polygenelubricants short-circuited operators involve a branch of some sort under the hood, so if there's no branch-prediction-friendly pattern to the truth values used with the operators and/or the architecture in use does not have good/any branch prediction (and assuming the compiler and/or virtual machine don't do any related optimizations themselves), then yes, SC operators will introduce some slowness compared to non-short-circuiting. The best way to find out of the compiler does anything would be to compile a program using SC vs. NSC and then compare the bytecode to see if it differs. – JAB Commented Jun 18, 2014 at 19:16
- Also, not to be confused with the bitwise OR operator which is also | – user20574 Commented Jan 27, 2015 at 9:16
It's not a "shortcut" (or short-circuiting) operator in the way that || and && are (in that they won't evaluate the RHS if they already know the result based on the LHS) but it will do what you want in terms of working .
As an example of the difference, this code will be fine if text is null:
whereas this won't:
(Obviously you could do "".equals(text) for that particular case - I'm just trying to demonstrate the principle.)
You could just have one statement. Expressed over multiple lines it reads almost exactly like your sample code, only less imperative:
For simplest expressions, using | can be faster than || because even though it avoids doing a comparison it means using a branch implicitly and that can be many times more expensive.
- I did start with just one, but as stated in the original question I felt that "The string of comparisons was long and difficult to read, so I broke it up for readability". That aside, in this case I'm more interested in learning the behaviour of |= than in making this particular piece of code work. – David Mason Commented Mar 21, 2010 at 21:48
- I can't seem to be find a nice use case for this specific operator. I mean if all you care is the result why not stop where your condition are met? – Farid Commented Dec 23, 2020 at 13:11
- 1 @Farid sometimes you don't want to stop, say I want to detect if any of a number of tasks did something. I have a busy flag, just because one of my tasks did something doesn't mean I don't want to run my other tasks, but if no task is busy, I want to take an action instead. – Peter Lawrey Commented Dec 24, 2020 at 22:19
Though it might be overkill for your problem, the Guava library has some nice syntax with Predicate s and does short-circuit evaluation of or/and Predicate s.
Essentially, the comparisons are turned into objects, packaged into a collection, and then iterated over. For or predicates, the first true hit returns from the iteration, and vice versa for and.
If it is about readability I've got the concept of separation tested data from the testing logic. Code sample:
The code looks more verbose and self-explanatory. You may even create an array in method call, like this:
It's more readable than 'comparison string', and also has performance advantage of short-circuiting (at the cost of array allocation and method call).
Edit: Even more readability can be simply achieved by using varargs parameters:
Method signature would be:
And the call could look like this:
- 1 Array allocation and a method call are a pretty big cost for short-circuiting, unless you've got some expensive operations in the comparisons (the example in the question is cheap though). Having said that, most of the time the maintainability of the code is going to trump performance considerations. I would probably use something like this if I were doing the comparison differently in a bunch of different places or comparing more than 4 values, but for a single case it's somewhat verbose for my tastes. – David Mason Commented Apr 25, 2013 at 23:31
- @DavidMason I agree. However keep in mind, that most modern calculators would swallow that kind of overhead in less than a few millis. Personally I wouldn't care about overhead until performance issues, which appears to be reasonable . Also, code verbosity is an advantage, especially when javadoc is not provided or generated by JAutodoc. – Krzysztof Jabłoński Commented Apr 26, 2013 at 8:04
It's an old post but in order to provide a different perspective for beginners, I would like give an example.
I think the most common use case for a similar compound operator would be += . I'm sure we all wrote something like this:
What was the point of this? The point was to avoid boilerplate and eliminate the repetitive code.
So, next line does exactly the same, avoiding to type the variable b1 twice in the same line.
- 1 It it harder to spot mistakes in the operation and the operator names, especially when the names are long. longNameOfAccumulatorAVariable += 5; vs. longNameOfAccumulatorAVariable = longNameOfAccumulatorVVariable + 5; – Andrei Commented Mar 8, 2019 at 9:21
- I think I'd prefer negativeValue = defaultStock < 0 || defaultWholesale < 0 etc. Aside from the inefficiency of all the boxing and wrapping going on here, I don't find it nearly as easy to understand what your code would really mean. – Jon Skeet Commented Mar 21, 2010 at 9:17
- I he has even more then 4 parameters and the criterion is the same for all of them then I like my solution, but for the sake of readability I would separate it into several lines (i.e. create List, find minvalue, compare minvalue with 0). – Roman Commented Mar 21, 2010 at 9:20
- That does look useful for a large number of comparisons. In this case I think the reduction in clarity isn't worth the saving in typing etc. – David Mason Commented Mar 21, 2010 at 10:07
|| logical boolean OR | bitwise OR
|= bitwise inclusive OR and assignment operator
The reason why |= doesn't shortcircit is because it does a bitwise OR not a logical OR. That is to say:
Tutorial for java operators
- there is NO bitwise OR with booleans! The operator | is integer bitwise OR but is also logical OR - see Java Language Specification 15.22.2. – user85421 Commented Jan 11, 2013 at 19:40
- You are correct because for a single bit (a boolean) bitwise and logical OR are equivalent. Though practically, the result is the same. – oneklc Commented Mar 20, 2013 at 22:26
Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
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 assignment-operator compound-assignment or-operator or ask your own question .
- The Overflow Blog
- The evolution of full stack engineers
- One of the best ways to get value for AI coding tools: generating tests
- Featured on Meta
- Bringing clarity to status tag usage on meta sites
- Join Stack Overflow’s CEO and me for the first Stack IRL Community Event in...
- Feedback requested: How do you use tag hover descriptions for curating and do...
- Staging Ground Reviewer Motivation
- What does a new user need in a homepage experience on Stack Overflow?
Hot Network Questions
- What is the purpose of long plastic sleeve tubes around connections in appliances?
- Text processing: Filter & re-publish HTML table
- Is there a name for this condition on monomorphisms?
- Do images have propositional content?
- Curve factor at position
- Analog story - US provides food machines to other nations, with hidden feature
- Who was the French detective mentioned in Hitchcock's "Shadow of a Doubt"?
- Thread-safe write-efficient register() method for a Load balancer
- How to fold or expand the wingtips on Boeing 777?
- Are there epistemic vices?
- Understanding the parabolic state of a quantum particle in the infinite square well
- How are you supposed to trust SSO popups in desktop and mobile applications?
- What does "Mas que nada" mean and how does that derive from the individual words?
- Error while Docker setup version is obsolete error during connect
- Can someone confirm this observed bug for `bc`? `scale=0` has no effect!
- What are the steps to write a book?
- Canonical decomposition as wedge sum up to homotopy equivalence
- Is this a misstatement of Euclid in Halmos' Naive Set Theory book?
- How resiliant is a private key passphase to brute force attacks?
- The meaning of "sharp" in "sharp sweetness"
- How long should a wooden construct burn (and continue to take damage) until it burns out (and stops doing damage)
- Is this map real?
- Does this policy mean that my work has flawed password storage?
- Why would the GPL be viral, while EUPL isn't, according to the EUPL authors?
- Java Course
- 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 Arithmetic Operators with Examples
Operators constitute the basic building block to 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. Here are a few types:
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 Arithmetic Operators.
These operators involve the mathematical operators that can be used to perform various simple or advanced arithmetic operations on the primitive data types referred to as the operands. These operators consist of various unary and binary operators that can be applied on a single or two operands. Let’s look at the various operators that Java has to provide under the arithmetic operators.
Now let’s look at each one of the arithmetic operators in Java:
1. Addition(+): This operator is a binary operator and is used to add two operands.
Syntax:
Example:
2. Subtraction(-): This operator is a binary operator and is used to subtract two operands.
3. Multiplication(*): This operator is a binary operator and is used to multiply two operands.
4. Division(/): This is a binary operator that is used to divide the first operand(dividend) by the second operand(divisor) and give the quotient as a result.
5. Modulus(%): This is a binary operator that is used to return the remainder when the first operand(dividend) is divided by the second operand(divisor).
Here is an example program in Java that implements all basic arithmetic operators for user input:
Explanation
- The program implements basic arithmetic operations using user input in Java. The program uses the Scanner class from the java.util package to read user input from the console. The following steps describe how the program works in detail:
- Import the java.util.Scanner class: The program starts by importing the Scanner class, which is used to read input from the console.
- Create a Scanner object : Next, a Scanner object sc is created and associated with the standard input stream System.in.
- Read the first number from the user: The program prompts the user to enter the first number and uses the nextDouble() method of the Scanner class to read the input. The input is stored in the num1 variable of type double.
- Read the second number from the user : The program prompts the user to enter the second number and uses the nextDouble() method of the Scanner class to read the input. The input is stored in the num2 variable of type double.
- Perform arithmetic operations: The program performs the four basic arithmetic operations (addition, subtraction, multiplication, and division) using the num1 and num2 variables and stores the results in separate variables sum, difference, product, and quotient.
- Print the results: The program prints out the results of the arithmetic operations using the println method of the System.out object.
- This program demonstrates how to implement basic arithmetic operations using user input in Java. The Scanner class makes it easy to read user input from the console, and the basic arithmetic operations are performed using standard mathematical operators in Java.
Please Login to comment...
Similar reads.
- Java-Operators
- Best Twitch Extensions for 2024: Top Tools for Viewers and Streamers
- Discord Emojis List 2024: Copy and Paste
- Best Adblockers for Twitch TV: Enjoy Ad-Free Streaming in 2024
- PS4 vs. PS5: Which PlayStation Should You Buy in 2024?
- 10 Best Free VPN Services in 2024
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
Java Tutorial
Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.
IMAGES
VIDEO
COMMENTS
Java Assignment Operators with Examples
Assignment, Arithmetic, and Unary Operators
Java Operators - W3Schools ... Java Operators
Simple Assignment Operator (=) To assign a value to a variable, use the basic assignment operator (=). It is the most fundamental assignment operator in Java. It assigns the value on the right side of the operator to the variable on the left side. In the above example, the variable x is assigned the value 10.
All Java Assignment Operators (Explained With Examples)
Java Assignment Operators. The Java Assignment Operators are used when you want to assign a value to the expression. The assignment operator denoted by the single equal sign =. In a Java assignment statement, any expression can be on the right side and the left side must be a variable name. For example, this does not mean that "a" is equal to ...
Java - Assignment Operators with Examples
Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...
Java assignment operators are classified into two types: simple and compound. The Simpleassignment operator is the equals (=) sign, which is the most straightforward of the bunch. It simply assigns the value or variable on the right to the variable on the left. Compound operators are comprised of both an arithmetic, bitwise, or shift operator ...
Assignment Operators Overview Top. The single equal sign = is used for assignment in Java and we have been using this throughout the lessons so far. This operator is fairly self explanatory and takes the form variable = expression; . A point to note here is that the type of variable must be compatible with the type of expression.
Assignment operator in Java
The simple assignment operator (=) is a straightforward but important operator in Java. Actually, we've used it many times in previous examples. It assigns the value on its right to the operand on its left: int seven = 7; 9.2. Compound Assignments
Operators - Learning the Java Language
Java's basic assignment operator is a single equals-to (=) sign that assigns the right-hand side value to the left-hand side operand. On left side of the assignment operator there must be a variable that can hold the value assigned to it. Assignment operator operates on both primitive and reference types. It has the following syntax: var ...
Compound Assignment Operators. Sometime we need to modify the same variable value and reassigned it to a same reference variable. Java allows you to combine assignment and addition operators using a shorthand operator. For example, the preceding statement can be written as: i +=8; //This is same as i = i+8; The += is called the addition ...
Java Operators: Arithmetic, Relational, Logical and more
The basic assignment operator is =. For example: int length = 15; This sets the value of length to 15. But there are also compound assignment operators that combine an operation with assignment: +=: Add and assign. -=: Subtract and assign. *=: Multiply and assign. /=: Divide and assign.
Learn about available Java operators, and precedence order and understand their usages with examples.We will also try to understand when to use which operator and what to expect in the result. 1. Java Operators. An operator is a symbol that performs a specific operation on one, two, or three operands, producing a result. The type of the operator and its operands determine the kind of operation ...
Summary of Operators (The Java™ Tutorials > ...
An assignment operator is used to update the value of a variable. Java supports all standard math functions (addition, subtraction, multiplication, etc), as well as some powerful shortcuts to ...
The |= is a compound assignment operator (JLS 15.26.2) for the boolean logical operator | (JLS 15.22.2); not to be confused with the conditional-or || (JLS 15.24). There are also &= and ^= corresponding to the compound assignment version of the boolean logical & and ^ respectively. In other words, for boolean b1, b2, these two are equivalent:
Java Arithmetic Operators with Examples
The compound assignment operator is the combination of more than one operator. It includes an assignment operator and arithmetic operator or bitwise operator. The specified operation is performed between the right operand and the left operand and the resultant assigned to the left operand. Generally, these operators are used to assign results ...