Transact-SQL
Reinforcement Learning
R Programming
React Native
Python Design Patterns
Python Pillow
Python Turtle
Verbal Ability
Interview Questions
Company Questions
Artificial Intelligence
Cloud Computing
Data Science
Machine Learning
Data Structures
Operating System
Computer Network
Compiler Design
Computer Organization
Discrete Mathematics
Ethical Hacking
Computer Graphics
Software Engineering
Web Technology
Cyber Security
C Programming
Control System
Data Mining
Data Warehouse
JavaScript disabled. A lot of the features of the site won't work. Find out how to turn on JavaScript HERE .
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.
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 .
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. |
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 |
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:
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.
Fundamentals Quiz 8 - Assignment Operators Quiz
In this lesson we looked at the assignment operators used in Java.
In the next lesson we look at the bitwise logical operators used in Java.
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
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.
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.
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,
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:
Java Code Editor:
Previous: Wrapper classes Next: Arithmetic Operator
Follow us on Facebook and Twitter for latest update.
Last updated: January 8, 2024
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
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.
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, 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
Do JSON right with Jackson
Download the E-book
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?
We’ve opened a new Java/Spring Course Team Lead position. Part-time and entirely remote, of course: Read More
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
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
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
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .
Get started with Spring Data JPA through the guided reference course:
>> CHECK OUT THE COURSE
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.
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.
The addition operator (+) allows us to add two values or concatenate two strings:
Usually, we use the subtraction operator (-) to subtract one value from another:
The multiplication operator (*) is used to multiply two values or variables:
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 .
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 (%):
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.
The unary plus operator (+) indicates a positive value. If the number is positive, we can omit the ‘+’ operator:
Opposite to the unary plus operator, the unary minus operator (-) negates a value or an expression:
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:
The increment operator (++) allows us to increase the value of a variable by 1:
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.
Relational operators can be called “comparison operators” as well. Basically, we use these operators to compare two values or variables.
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 .
The “not equal to” operator (!=) does the opposite of the ‘==’ operator. If the values on both sides are not equal, the operation returns true :
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:
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:
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:
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:
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.
The logical AND operator ( && ) returns true only if both operands are true :
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.
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:
As the article “ Java bitwise operators ” covers the details of bitwise and bit shift operators, we’ll briefly summarize these operators in this tutorial.
The bitwise AND operator (&) returns the bit-by-bit AND of input values:
The bitwise OR operator (|) returns the bit-by-bit OR of input values:
The bitwise XOR (exclusive OR) operator (^) returns the bit-by-bit XOR of input values:
The bitwise complement operator (~) is a unary operator. It returns the value’s complement representation, which inverts all bits from the input value:
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.
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.
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 .
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:
We use assignment operators to assign values to variables. Next, let’s see which assignment operators we can use 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:
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:
Java provides many groups of operators for different functionalities. In this article, we’ve passed through the operators in Java.
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.
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.
Learn Java practically and Get Certified .
Popular examples, reference materials, learn java interactively, java introduction.
Java Ternary Operator
Java instanceof Operator
Java Operator Precedence
Java Bitwise and Shift Operators
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 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) |
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.
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 |
---|---|---|
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 |
Note : Relational operators are used in decision making and loops.
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 |
Working of Program
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 |
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 .
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 .
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 .
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.
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 .
Sorry about that.
Java Tutorial
Assignment operator is one of the simplest and most used operator in java programming language. As the name itself suggests, the assignment operator is used to assign value inside a variable. In java we can divide assignment operator in two types :
The = operator in java is known as assignment or simple assignment operator. It assigns the value on its right side to the operand(variable) on its left side. For example :
The left-hand side of an assignment operator must be a variable while the right side of it should be a value which can be in the form of a constant value, a variable name, an expression, a method call returning a compatible value or a combination of these.
The value at right side of assignment operator must be compatible with the data type of left side variable, otherwise compiler will throw compilation error. Following are incorrect assignment :
Another important thing about assignment operator is that, it is evaluated from right to left . If there is an expression at right side of assignment operator, it is evaluated first then the resulted value is assigned in left side variable.
Here in statement int x = a + b + c; the expression a + b + c is evaluated first, then the resulted value( 60 ) is assigned into x . Similarly in statement a = b = c , first the value of c which is 30 is assigned into b and then the value of b which is now 30 is assigned into a .
The variable at left side of an assignment operator can also be a non-primitive variable. For example if we have a class MyFirstProgram , we can assign object of MyFirstProgram class using = operator in MyFirstProgram type variable.
No , it's not an assignment operator, it's a relational operator used to compare two values.
Yes , as it requires two operands.
a = 2 b = 2 c = 4 d = 4 e = false
The assignment operator can be mixed or compound with other operators like addition, subtraction, multiplication etc. We call such assignment operators as compound assignment operator. For example :
Here the statement a += 10; is the short version of a = a + 10; the operator += is basically addition compound assignment operator. Similarly b *= 5; is short version of b = b * 5; the operator *= is multiplication compound assignment operator. The compound assignment can be in more complex form as well, like below :
The table below shows the list of all possible assignment(simple and compound) operators in java. Consider a is an integer variable for this table.
Operator | Example | Same As |
---|---|---|
= | a = 10 | a = 10 |
+= | a += 5 | a = a + 5 |
-= | a -= 3 | a = a - 3 |
*= | a *= 6 | a = a * 6 |
/= | a /= 5 | a = a / 5 |
%= | a %= 7 | a = a % 7 |
&= | a &= 3 | a = a & 3 |
|= | a |= 3 | a = a | 3 |
^= | a ^= 2 | a = a ^ 2 |
>>= | a >>= 3 | a = a >> 3 |
>>>= | a >>>= 3 | a = a >>> 3 |
<<= | a <<= 2 | a = a << 2 |
Including simple and compound assignment we have total 12 assignment operators in java as given in above table.
Shorthand operators are nothing new they are just a shorter way to write something that is already available in java language. For example the code a += 5 is shorter way to write a = a + 5 , so += is a shorthand operator. In java all the compound assignment operator(given above) and the increment/decrement operators are basically shorthand operators.
a = 20 b = 80 c = 30 s = 64 s2 = 110 b2 = 15
An expression a += 1 will result as a = a + 1 while the expression a =+ 1 will result as a = +1 . The correct compound statement is += , not =+ , so do not use the later one.
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.
The following quick reference summarizes the operators supported by the Java programming language.
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.
Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improving readability.
Table of Content
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 the variable on the left side.
Below is a table summarizing common assignment operators along with their symbols, description, and examples:
Operator | Description | Examples |
---|---|---|
= (Assignment) | Assigns the value on the right to the variable on the left. | assigns the value 10 to the variable x. |
+= (Addition Assignment) | Adds the value on the right to the current value of the variable on the left and assigns the result to the variable. | is equivalent to |
-= (Subtraction Assignment) | Subtracts the value on the right from the current value of the variable on the left and assigns the result to the variable. | is equivalent to |
*= (Multiplication Assignment) | Multiplies the current value of the variable on the left by the value on the right and assigns the result to the variable. | is equivalent to |
/= (Division Assignment) | Divides the current value of the variable on the left by the value on the right and assigns the result to the variable. | is equivalent to |
%= (Modulo Assignment) | Calculates the modulo of the current value of the variable on the left and the value on the right, then assigns the result to the variable. | is equivalent to |
Here are the implementation of Assignment Operator in C language:
Here are the implementation of Assignment Operator in C++ language:
Here are the implementation of Assignment Operator in java language:
Here are the implementation of Assignment Operator in python language:
Here are the implementation of Assignment Operator in C# language:
Here are the implementation of Assignment Operator in javascript language:
In conclusion, assignment operators in programming are essential tools for assigning values to variables and performing operations in a concise and efficient manner. They allow programmers to manipulate data and control the flow of their programs effectively. Understanding and using assignment operators correctly is fundamental to writing clear, efficient, and maintainable code in various programming languages.
Similar reads.
Toli and Rachel Lee
The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.
An operator is one or more symbols in combination, such as the well-known arithmetic operators minus ( - ) and plus ( + ) or the more advanced instanceof . When you apply operators on values or variables, you get a result from the operation. Such operations are fundamental in programming because their result is assigned to a variable or further evaluated until the final goal of the program is accomplished.
For this tutorial, you have to be familiar with an operand , which is the value or variable on which the operators are applied. Depending on the number of operands, operators can be divided into three groups. First, when there is only one operand in the operation, the operators are called unary . Similarly, binary operators involve two operands. Finally, when there are three operands, the operator is ternary . Following this categorization, this tutorial is organized into three main parts for each type of operator.
In this tutorial, you will use all three types of operators to manipulate primitive data types, such as in math equations. You will also use operators in more advanced scenarios with reference types and explore some of the rules for operator precedence.
To follow this tutorial, you will need:
An environment in which you can execute Java programs to follow along with the examples. To set this up on your local machine, you will need the following:
Familiarity with Java and object-oriented programming, which you can find in our tutorial, How To Write Your First Program in Java .
An understanding of Java data types, which is discussed in our tutorial, Understanding Data Types in Java .
Unary operators are applied to one operand, which makes them the most straightforward. Unary operators are often used because they make your code more concise and readable. They replace the need to explicitly describe operations like increasing and decreasing values. However, when combined with other operators, unary operators can also be challenging to use, as you’ll discover later in this section.
Next, you’ll use unary operators to increase and decrease values, as well as flip boolean values.
Increment and decrement operators, as their names suggest, increase and decrease numbers. The increment operator is the combination of two plus signs ( ++ ) and the decrement operator is two minus signs ( -- ). These operators are used before and after operands.
When you use the operators before an operand, you are preincrementing or predecrementing depending on whether you use ++ or -- . When you use the pre operators, you change the value of the operand before using it. Thus, when you actually use the value, it is already changed.
Info: To follow along with the example code in this tutorial, open the Java Shell tool on your local system by running the jshell command. Then you can copy, paste, or edit the examples by adding them after the jshell> prompt and hitting ENTER . To exit jshell , type /exit .
To use the preincrementing operator, type the following into jshell :
On the first line, you define a variable theAnswer with the value 42 . On the second line, you use the println() method to print it and thus demonstrate how it has changed.
The preincrement operator in the above example is ++ , and it is placed before theAnswer . By using the preincrement operator in this way, you are first incrementing the value of theAnswer to 43 . After that, when println() processes it, it is already 43 , and thus you see printed:
Predecrementing works similarly, but instead of incrementing, you are decrementing the value of the operand. As an exercise, modify the above example so that instead of the preincrement operator ++ , you use the predecrement -- .
In contrast to the pre operators, the post operators change the value of an operand after it is used. There are some specific cases in which post or pre operators are commonly used, but as a whole, it is a matter of personal preference.
To demonstrate how post operators work, you will postincrement the value of theAnswer and examine how its value changes. Add the following lines to jshell :
The variable theAnswer first equals to 42 . Then, it is printed and postincremented. On the last line, you print it again to see its final value.
Your output should be:
As you can see, theAnswer remains 42 during the postincrementing. It is when you print it again after postincrementing that it is 43 ( Final value: 43 ).
Postdecrementing works the same way. The value is first retrieved and used, and only after that, is it decremented. As an exercise, try replacing the postincrement operator ++ with the postdecrement operator -- , or even include one of the pre operators.
The NOT operator, also known as the logical complement operator , flips the value of a boolean operand. It is represented by the exclamation mark ! . Usually, you use the NOT operator when you have a boolean variable or value, and you want to reuse it with the opposite value. Thus, you don’t have to create another variable with the opposite value unnecessarily.
Here is an example of how the NOT operator works. For simplicity, you’ll flip the value of true :
You define the boolean variable isJavaFun as true . However, the NOT operator precedes true ; thus, the value of true is flipped to false . When you run the above code, the following output will print:
This is how the NOT operator works. It might be confusing and hard to spot it sometimes, so you should use it sparingly.
In the above case, instead of !true , you could have used false . This is the right approach because it’s cleaner and more intuitive. As a general rule, it’s best practice to use a literal or method directly, rather than alternatives that require additional operations. However, in some cases, it may not always make sense or even be possible. For example, it’s common to use the NOT operator to flip the result from a boolean method.
As an example, to check if a string contains another string, you can use the method contains() . However, if you want to check the opposite (that is, when a string does not contain another string), there is no alternative built-in method. You’ll need to use contains() with the NOT operator.
Imagine you have the string Java is smart. and you want to check whether:
To check these, you’ll use the following code:
On the first line, you define a String variable javaIsSmart . On the second line, you define a boolean variable isSmartPartOfJava as the result of the operation from the method contains() — in this case, whether the string smart is part of the javaIsSmart string. Similarly, on the third line, you define a boolean variable isHardNotPartOfJava , which is determined by whether hard is not found in javaIsSmart .
When you run this code in jshell , you will get the following output:
According to the above output:
In this section, you explored incrementing, decrementing, and the NOT operator using one operand. Even though these operators have only one operand, they can be challenging to use, as demonstrated by the NOT operator. In the next step, you’ll build on this knowledge by using operators with two operands.
Binary operators act on two operands and are commonly associated with arithmetic operations such as addition and subtraction. There are also other non-math related binary operators, such as logical operators and the special relational operator instanceof . In this section, you’ll begin with the arithmetic binary operators, which may be more familiar.
These are the well-known operators used for arithmetic operations, such as addition ( + ) and subtraction ( - ). Here is an example with addition:
On the first line, you add 40 to 2 and assign the result to theAnswer variable. When you print it, you get the final value 42 :
**NOTE:**In addition to arithmetic operations, the plus sign ( + ) is also used for concatenating strings. You have seen it in action in most of our examples with printing values, such as the one above. There, using the plus sign, you have concatenated "The result is: " with the variable theAnswer . However, this use of the plus sign is an exception, and no other arithmetic operators can be used similarly on reference types. So, for example, you cannot use the minus sign to remove parts of a string.
For additional practice, try using the other arithmetic operators, which you can find in the Java documentation .
The assignment operators assign the left operand to the value of the right operand. Usually, the left operand is a variable and the right one is a value or a reference to an object. This may sound familiar because you’ve used such assignments in all of your examples. In this section, you’ll practice using the basic assignment operator, some compound assignment operators, and the casting operator.
The basic assignment operator ( = ) is a well-known and commonly used operator.
In this example, you declare an int variable x and assign it the value 1 . Using the equals sign ( = ) is how you assign a value to a variable.
The compound assignment operators ( += , -= , *= , \= ) combine assignment along with an additional arithmetic operation such as addition or subtraction. These operators allow you to avoid boilerplate code, especially in arithmetic operations that are straightforward to follow and understand.
For example, use the compound += assignment operator to combine addition and assignment like this:
In the first two lines, you declare two integer variables called x and y , both with a value of 1 . Next, you reassign x using the compound += assignment, which means that x is added to y and then is assigned back to x .
The above code will return an output similar to this:
According to the above output, x and y get a value of 1 . On the third line, there is a temporary variable with a randomly-assigned name ( $11 ). It holds the value of x as a result of the compound assignment operation. On the last line, the value of x is printed: 2 .
The same code can be rewritten without the compound assignment operator like this:
In contrast to the previous example, you write additional code to describe explicitly the addition of x plus y on line 3.
Running this code will return the following output:
Ultimately, in both examples, x equals 2 . However, in the second example, jshell didn’t print a temporary variable name such as $11 . Instead, it used x directly to show that its value has changed ( x ==> 2 ). Such verbose output is very helpful for learning and is available only in jshell .
The rest of the compound operators combine subtraction ( -= ), multiplication ( *= ) and division ( /= ) along with assignment. Try changing the above examples to see how they can work.
It’s good to know about compound operators because they are frequently used. However, there is no performance benefit to using them, so using compound operators is a matter of personal choice. If they seem unnecessarily confusing, you don’t have to use them.
The last assignment operator you’ll review is the casting operator, which is a data type surrounded by parentheses: (data type) . The casting operator is used for casting values, which is interpreting one data type as another.
The data types have to be compatible, though. Whether one data type is compatible with another is determined by their relation, such as whether one class is a parent or sibling to another. For example, you can cast int to short because both data types are used for storing whole numbers. However, you cannot cast int to boolean because the two data types are incompatible.
In this section, you’ll explore some common examples of and problems with casting. For educational purposes, you’ll begin with an incorrect and incompatible casting:
With this line, you are trying to cast the integer 1 to a boolean value and assign it to the variable y . When you paste this in jshell , you’ll get the following error:
As the error message explains, you cannot convert an int value to a boolean . Boolean values are either true or false , and it’s impossible to determine which boolean value 1 should be.
Now, you’ll try an example with compatible data types. You’ll use two primitive types for storing whole numbers: int and short . The difference is in their capacity, that is, the amount of memory available to store information. int has a larger capacity and thus can store larger numbers.
Add the following lines to jshell :
In the first line, you define the lottery prize as an int primitive type with the value of 32767 . On the second line, however, you decide that a short primitive type will be more suitable for the value of the wonprize , and you cast prize to short using (short) .
When you run the above code in jshell , the output is:
The above output confirms that prize and wonPrize values have been correctly set to 32767 . The last row uses the wonPrize variable to state how much you have won.
In the case of int and short , casting may seem unnecessary and you will probably not see such casting in reality. However, this example is useful for demonstrating the idea of casting.
Casting seems straightforward, but there is one caveat. When you cast from a data type with a larger capacity to a data type with a smaller capacity, you could exceed the smaller capacity limit, which is called overflow . To demonstrate this problem, reuse the previous example and increase the prize from 32767 to 32768 , like so:
When you run the above in jshell , you will get the following output:
In this case, you lose information and get unexpected results. When cast to short , the value of 32768 becomes -32768 . This is because short ’s storage capacity ranges from - 32768 to 32767 . When you try to store a value larger than the maximum value, you overflow it and start from the beginning. In this case, you exceed the maximum capacity ( 32767 ) by 1 when you try to store 32768 . Because of this, the next value is assigned, starting from the lowest possible. In this case, this is the minimum value of -32768 .
That’s why the above output seems unexpected — the final prize has become a negative number. These kinds of problems are not always easy to spot, so you should use casting carefully. You may use casting in more complex scenarios, which will be addressed in future tutorials from the Java series.
Relational operators compare two operands and return a boolean result. If the relation is asserted, the result is true . If not, the result is false .
The first types of relational operators are equals == and not equals != . They are used to assert the equality of values and objects. With primitive values and literals, their use is similar to mathematics.
To demonstrate the equals equality operator, compare two integer literals. In fact, it will be one and the same number: 1 . You’ll compare whether it is equal to itself so that you can get a true result. Paste the following code into jshell :
In the above code, you are asserting whether 1 equals 1 . Since the numbers are equal, this expression evaluates to true. Thus, println() prints true :
As an exercise, try changing one of the values in order to get a false result.
Note: Make sure to differentiate between the operator for equality == and the assignment operator = . Even when you know they’re different, it is easy to confuse them. You may not always get a syntax error in your code, which can lead to problems that are hard to debug.
In contrast to comparing primitive values, comparing objects for equality is more complex because you are asserting whether two variables point to the same object. Try comparing two Integers as an example:
In the above code, you create two Integer variables, each with a value of 42 . On the last line, you compare them for equality and print true if they are equal. From our previous tutorial Understanding Data Types in Java , you may know that Integer.valueOf() first checks the cache for an object with the same value and returns the same object if there is one already with this value. That’s how both myAnswer and yourAnswer receive the same object.
When you paste the above code in jshell , you will get the following output:
Such object comparison seems straightforward, but sometimes it’s challenging. The most confusing example is with strings. Try comparing two strings with the same values:
First, you declare two new String variables ( answer1 and answer2 ) with the values "yes" . However, you used the new keyword to create the new String objects. Because of that, the two variables do not point to the same object — they actually point to two different objects (with the same value).
Even though answer1 and answer2 have the same value ( "yes" ), their equality is evaluated to false , which means they are not equal. It can be confusing if you intend to compare values, such as whether both answers are affirmative, and you’re not interested in the underlying objects. For this purpose, many classes, including String , have dedicated methods for asserting equality.
In the case of String, this method is equals() . Try changing the code to use equals() (instead of == ) like this:
The equals() method verifies that the strings contained in the compared objects are equal.
When you paste this code in jshell , you will get the following output:
The above output is similar to the previous output, but it finishes with true , confirming that the values of the two objects are equal. This example demonstrates that you have to be careful when comparing reference types and use corresponding methods when available.
The alternative equality operator, not equals != , is used similarly, but it asserts whether two variables or values are not the same (or unequal). As an exercise, try replacing == with != in some of the previous examples.
Similar to == and != , the next four relational operators also come from mathematics: less than < , less than or equal to <= , greater than > , and greater than or equal to => .
Here’s an example using the greater than operator:
The above code first compares whether 4 is greater than 5 . Since it is not, the expression evaluates to false . The result of the comparison ( false ) is then printed by the println() method.
The last relational operator is instanceof , which evaluates whether a variable is an instance of a given class (or subclass) or an implementation of an interface. As explained in our Understanding Data Types in Java tutorial, an interface is an abstract entity with a group of requirements.
Use the following example to explore how instanceof works:
First, you create a String variable called greeting . Then, you evaluate in the parentheses whether greeting is an instance of String .
When you paste the code in jshell , you will get the following output:
Since greeting is an instance of String , the expression evaluates to true , which is printed on the screen by println() .
The logical operators are logical AND ( & ), logical OR ( | ), and exclusive OR ( ^ ). They all evaluate two values as follows:
When the logical operators are not true as per the above conditions, they are false.
To use the logical AND ( & ) operator, paste the following example into jshell :
The first two lines define the boolean variables isJavaFun and isJavaPowerful both to true . On line three, in the parentheses, you perform a logical AND operation on isJavaFun and isJavaPowerful and the result is printed by println() .
Both variables are set to true , and a final true is printed as the result of the logical AND operation.
To extend your skills, try using the previous code example with some variations. You can try switching the values of the variables between true and false . You can also try changing the logical operators to logical OR ( | ) and exclusive OR ( ^ ).
An extended version of the logical operators are the so-called short-circuit logical operators : short-circuit AND ( && ) and short-circuit OR ( || ). They are similar to the regular logical AND and OR operators, but they have one important difference: if evaluating the first operator is sufficient for the operation, the second one is not evaluated. Thus, in order for the short-circuit AND to be true, both sides surrounding it have to be true . However, if the left side is false , the right side is not evaluated. Similarly, with the short-circuit OR , if the left side is false , the right is not evaluated.
Here is an example with short-circuit OR :
First, you assign the variable isJavaFun to true . For consistency with the previous examples, this variable is of the primitive type boolean . However, for the next variable, isNullFun , you use the Boolean reference type so that you can assign it to null . For the example, it’s important that you have a null pointing variable, but as you may recall from the tutorial on Understanding Java Data Types , primitives types cannot be null, and that’s why you are using a reference type.
When the short circuit OR takes place in the parentheses, isNullFun is ignored because the left side is true , and this is enough for the whole expression to be true . Thus, when you run the code in jshell , the following output will print:
The first and the second lines confirm that the variables are assigned to true and null . The third line prints true because the short-circuit OR operation has returned true .
The above example was chosen specifically with null in order to demonstrate how short-circuit operators work and that isNullFun will not be evaluated. To see isNullFun evaluated, try changing the short-circuit OR with a regular OR like this:
The regular logical OR evaluates both sides of the expression.
When the logical OR tries to evaluate null , you get the java.lang.NullPointerException . Because of this, short-circuit operators are preferred and are almost always used instead of regular logical operators.
As an exercise, practice using the short-circuit && and || , which are the most popular and useful of all.
In this section, you used binary operators in a range of examples, from basic arithmetic to more challenging operations involving casting and comparing objects for equality. In this next section, you’ll work with three operands.
In the previous sections, you practiced using operators with one and two operands. In this final section, you’ll use the ternary operator, the only operator for three operands. Its syntax is this: first operand ? second operand : third operand . The first operand must be a boolean. If it is true , then the second operand is returned from the expression. If the first operand is false , then the third operand is returned.
The ternary operator is popular and frequently used because it can save you from writing complex statements, such as conditionals, and storing their results in temporary variables.
Try a ternary operator with the following example:
isJavaFun is set to true , and the variable shouldILearnJava is determined by it in a ternary operation. Because the first operand, isJavaFun , is true, the second operand is returned, which is the string "yes" . To verify this, the third line prints the variable shouldILearnJava , which should be yes at this point.
When you run the above code, you will get the following output:
For additional practice, try using the NOT operator in front of isJavaFun :
By flipping the value of isJavaFun , you set it from true to false . As a result, the ternary expression will return the last operand, which is "no" .
Ternary expressions can be confusing, especially when you use additional operators such as the NOT operator. However, they can save you some boilerplate code and that’s why they are popular.
Once you know the important operators, you will be able to use and even combine them. But before you start combining them, you will need to know the rules for operator precedence.
Operator precedence determines in what order operators are evaluated. Since you are likely to use more than one operator, it’s important to understand operator precedence. While the rules are not always intuitive, you will likely need to know only a few essential rules in practice.
Understanding operator precedence helps you write clean code , which is the de-facto standard for modern programming. To write clean code means to write understandable and maintainable code. In regards to operators, the clean code paradigm translates to using as few operators as possible and creating separate statements instead of nesting and combining operators.
For example, statements such as the one below should be avoided because they are too confusing:
Even if you consult the operators documentation , you might not be able to guess the end result ( isThisCleanCode is false ).
Here are some of the most important and commonly used precedence rules, starting with the rules with the highest precedence:
Now, you’ll use a math problem to explore operator precedence:
According to the above output, x gets the value of 6 . This is because the following operations have been completed with decreasing priority:
Even though this math equation is relatively straightforward, you can always make it more verbose and ensure that precedence is easily understood by using parentheses. Consider rewriting it like this:
When you paste the above in jshell , the same result as before will print:
In the last example, you didn’t change the precedence by using parentheses around 10 / 2 . Instead, their purpose was only to make the precedence of the operation inside them more obvious. Using parentheses like this helps you make your code more clean and understandable, which is especially important when the operations are more complex.
Precedence rules are interesting and spending some time learning them is a good idea. Keep in mind the clean code paradigm and consider the fact that unnecessary nesting and combining of operators is seen as a weakness in the code.
In this tutorial, you learned about the primary operators in Java. You wrote a few test code snippets in which you saw some of the most useful and interesting scenarios related to operators. You also learned about clean code and the fact that operators shouldn’t be overused unnecessarily.
For more on Java, check out our How To Code in Java series.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Learn more about our products
Java is a mature and well-designed programming language with a wide range of uses. One of its unique benefits is that it is cross-platform: once you create a Java program, you can run it on many operating systems, including servers (Linux/Unix), desktop (Windows, macOS, Linux), and mobile operating systems (Android, iOS).
Technical Editor
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Click below to sign up and get $200 of credit to try our products over 60 days!
Please complete your information!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Digitalocean products, welcome to the developer cloud.
DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.
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.
I'm studying some Java at the moment at I've come across the following piece of code. I understand how the typical ternary operator (e.g. the line beginning with "boolean a" below), but I can't understand how to read the expression on the line beginning with "boolean b". Any help on how to read this line would be much appreciated! Thanks!
Break it up like this:
So here the testing condition is always set to true . So the branch of the ternary that executes is the ++i > 2 ? true : false part.
This simply checks to see if after incrementing, i is greater than 2 . If so, it will return true . Otherwise it will return false .
This whole expression is actually needlessly complex. It can simply be written as such:
However, the code is probably logically incorrect since this abstruse expression doesn't make that much sense. Since the previous line sets the value of a , I'm assuming that the next line actually intends to test a . So the actual intent might be:
In which case you can break it up as:
But you don't need to actually do a == true since a is already a boolean , so you can do:
Here, it checks to see if a is true . If it is, it performs the check we already went over (i.e., to see if the incremented value of i is greater than 2 ), otherwise it returns false .
But even this complicated expression can be simplified to just:
Ah! Never write code like that. But I would assume that is not written by you. But you can read it like this:
which can be broken further as:
which can be further broken down as:
Also, the first assignment:
can also be written as:
In boolean b = a = true ? ++i > 2 ? true:false:false; the following happens:
This will give a true value and evaluate to true .
Than we get another condition, ++i > 2 from ++i > 2 ? true:false , which will be also true in this case. The outcome will be true .
Ternary operators are
condition then true or false
The condition is always true (because a equals true).
Then the result is true because ++i is greater than 2 (it's 3).
Therefore, it assigns true to b . If the condition was false, it would assign false. That false would be assigned from the last false.
It would help if you could use parentheses and review that code as follows;
You can think it as:
Where if(true) is a Tautology and If Number:2 will always be executed. Therefore; it becomes;
Which can be evaluated to; a = (++i > 2) ? true : false); and which becomes: a = ++i > 2 as a result b = a which is ++i > 2 .
With some guesses at what is being attempted and some renaming of variables, and assuming the a = true was meant to be a == true you get:
This can then be tidied up to the much more logical:
Horrible code!
There are a couple of clues that the b = a = true ? ... should be b = a == true ? ... , since otherwise the previous line is a useless assignment (a is never read), and the final false of the line becomes unreachable code. The compiler will tell you that.
I'm going to answer assuming a corrected == - but you'll know whether it was a typo on your part, an unreliable source, or a 'spot the bug' test, and be able to use the same techniques on whatever code you like.
The trick is to refactor it step by step. First add brackets and indentation based on precedence rules.
Next note that:
If this is "serious" code, the way to approach this would be to write a set of unit tests that cover all the possible input cases. Then make these refactorings one at a time, each time re-running the tests to ensure that you've not changed the behaviour of the code.
Notice that there are no true or false literals in the reduced form. Seeing boolean literals in a ternary operation -- or indeed, ternary expressions for boolean values at all -- is a code smell, since the non-ternary version is usually simpler and clearer.
Ternary expressions are very useful for their intended purpose, which is mapping boolean conditions to non-boolean outputs:
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
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 .
COMMENTS
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.
Assignment Operators in Java: An Overview. We already discussed the Types of Operators in the previous tutorial Java. In this Java tutorial, we will delve into the different types of assignment operators in Java, and their syntax, and provide examples for better understanding.Because Java is a flexible and widely used programming language. Assignment operators play a crucial role in ...
Test yourself with multiple choice questions. Get Certified. Document your knowledge. ... 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: Example
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. Example: int x = 10; int x = 10; In the above example, the variable x is assigned the value 10.
This operator can also be used on objects to assign object references, as discussed in Creating Objects. The Arithmetic Operators. The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics.
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.
Java assignment operators are classified into two types: simple and compound. The Simple assignment 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 ...
Java Assignment Operators are used to optionally perform an action with given operands and assign the result back to given variable (left operand). The syntax of any Assignment Operator with operands is. operand1 operator_symbol operand2. In this tutorial, we will learn about different Assignment Operators available in Java programming language ...
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.
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 =. ... Java also has the facility of chain assignment operators, where we can specify a single value for multiple variables. Example:
There are mainly two types of assignment operators in Java, which are as follows: Simple Assignment Operator ; We use the simple assignment operator with the "=" sign, where the left side consists of an operand and the right side is a value. The value of the operand on the right side must be of the same data type defined on the left side.
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 ...
Learn about all the different types of operators available in Java like Arithmetic, Assignment, Relational and Logical operators. Practice Problems to solidify your knowledge. ... When you have an expression with multiple operators, Java needs to know which operation to do first. This is where operator precedence and associativity come in.
Walk through all Java operators to understand their functionalities and how to use them. ... 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.
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 ...
9. Python's multiple assignment is fairly powerful in that it can also be used for parallel assignment, like this: (x,y) = (y,x) # Swap x and y. There is no equivalent for parallel assignment in Java; you'd have to use a temporary variable: t = x; x = y; y = t; You can assign several variables from expressions in a single line like this:
2. Java Assignment Operators. Assignment operators are used in Java to assign values to variables. For example, int age; age = 5; 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.
The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2. -= (compound subtraction assignment operator) 3. *= (compound multiplication assignment operator) 4. /= (compound division assignment operator) 5. %= (compound modulo assignment operator)
The = operator in java is known as assignment or simple assignment operator. It assigns the value on its right side to the operand (variable) on its left side. For example : int a = 10; // value 10 is assigned in variable a double d = 20.25; // value 20.25 is assigned in variable d char c = 'A'; // Character A is assigned in variable c. a = 20 ...
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.
Java does not allow returning multiple values. Python allows this: def foo(): return 1, 2, 3. a, b, c = foo() The main point, why this does not work in Java is, that the left hand side (LHS) of the assignment must be one variable: Wrapper wrapper = WrapperGenrator.generateWrapper(); You can not assign to a tuple on the LHS as you can in Python.
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 ...
These operators allow you to avoid boilerplate code, especially in arithmetic operations that are straightforward to follow and understand. For example, use the compound += assignment operator to combine addition and assignment like this: int x = 1; int y = 1; x += y; System.out.println ("x is: " + x);
0. Ternary operators are. condition then true or false. The condition is always true (because a equals true). Then the result is true because ++i is greater than 2 (it's 3). Therefore, it assigns true to b. If the condition was false, it would assign false. That false would be assigned from the last false.