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.

Assignment, Arithmetic, and Unary Operators

The simple assignment operator.

One of the most common operators that you'll encounter is the simple assignment operator " = ". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:

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. The only symbol that might look new to you is " % ", which divides one operand by another and returns the remainder as its result.

The following program, ArithmeticDemo , tests the arithmetic operators.

This program prints the following:

You can also combine the arithmetic operators with the simple assignment operator to create compound assignments . For example, x+=1; and x=x+1; both increment the value of x by 1.

The + operator can also be used for concatenating (joining) two strings together, as shown in the following ConcatDemo program:

By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output.

The Unary Operators

The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.

The following program, UnaryDemo , tests the unary operators:

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version ( ++result ) evaluates to the incremented value, whereas the postfix version ( result++ ) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

The following program, PrePostDemo , illustrates the prefix/postfix unary increment operator:

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

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

  • 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

Author Photo

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
  • Number Theory
  • Data Structures
  • Cornerstones

Shortcut Assignment Operators

We can use the following shortcut operators in the assignment of variables:

Incrementing and decrementing a value by one is so common, there are special (even shorter) shortcut operators for these tasks:

Be careful about using the increment and decrement operators within an expression. Consider the following examples:

The character-counting program uses several operators including = , != , ++ , and + highlighted in this listing: class Count { public static void main(String[] args) throws java.io.IOException { int count = 0; while (System.in.read() != -1) count ++ ; System.out.println("Input has " + count + " chars."); } }
operator op
op operator
op1 operator op2

Arithmetic Operators

The Java language supports various arithmetic operators--including + (addition), - (subtraction), * (multiplication), / (division), and % (modulo)--on all floating point and integer numbers. For example, you can use this Java code to add two numbers: addThis + toThis
divideThis % byThis
System.out.println("Input has " + count + " chars.");
do { . . . } while (count++

Relational and Conditional Operators

Relational operators compare two values and determine the relationship between them. For example, != returns true if the two operands are unequal. The character-counting program uses != to determine whether the value returned by System.in.read is not equal to -1. This table summarizes Java's relational operators: Operator Use Return true if > op1 > op2 op1 is greater than op2 >= op1 >= op2 op1 is greater than or equal to op2 op1 op1 is less than op2 op1 op1 is less than or equal to op2 == op1 == op2 op1 and op2 are equal != op1 != op2 op1 and op2 are not equal Often the relational operators are used with another set of operators, the conditional operators, to construct more complex decision making expressions. One such operator is && which performs the boolean and operation. For example, you can use two different relational operators along with && to determine if both relationships are true. The following line of code uses this technique to determine if an array index is between two boundaries--that is, to determine if the index is both greater than 0 and less than NUM_ENTRIES (which is a previously defined constant value): 0 < index && index < NUM_ENTRIES
((count > NUM_ENTRIES) && (System.in.read() != -1))

Bitwise Operators

The bitwise operators allow you to perform bit manipulation on data. This table summarizes the bitwise and logical operators available in the Java language. Operator Use Operation >> op1 >> op2 shift bits of op1 right by distance op2 op1 shift bits of op1 left by distance op2 >>> op1 >>> op2 shift bits of op1 right by distance op2 (unsigned) & op1 & op2 bitwise and | op1 | op2 bitwise or ^ op1 ^ op2 bitwise xor ~ ~op2 bitwise complement The three shift operators simply shift the bits of the left-hand operand over by the number of positions indicated by the right-hand operand. The shift occurs in the direction indicated by the operator itself. For example: 13 >> 1;
1101 & 1100 ------ 1100
final int VISIBLE = 1; final int DRAGGABLE = 2; final int SELECTABLE = 4; final int EDITABLE = 8; int flags = 0;
flags = flags | VISIBLE;
flags & VISIBLE

Assignment Operators

You use the assignment operator, = , to assign one value to another. The character-counting program uses = to initialize count with this statement: int count = 0;

Assignment Operators

You use the basic assignment operator, = , to assign one value to another. The MaxVariablesDemo program uses = to initialize all its local variables: //integers byte largestByte = Byte.MAX_VALUE ; short largestShort = Short.MAX_VALUE ; int largestInteger = Integer.MAX_VALUE ; long largestLong = Long.MAX_VALUE ; //real numbers float largestFloat = Float.MAX_VALUE ; double largestDouble = Double.MAX_VALUE ; //other primitive types char aChar = 'S' ; boolean aBoolean = true ;

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.

JavaScript disabled. A lot of the features of the site won't work. Find out how to turn on JavaScript  HERE .

Java8 Homepage

  • 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.

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.

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:

run casting

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
The countChars method uses several operators including = , != , ++ , and + , which are highlighted in this listing: import java.io.*; public class Count { public static void countChars(Reader in) throws IOException { int count = 0; while (in.read() != -1) count ++ ; System.out.println("Counted " + count + " chars."); } // ... main method omitted ... }
operator op
op operator
op1 operator op2
expr ? op1 : op2

Arithmetic Operators

The Java language supports various arithmetic operators for all floating-point and integer numbers. These include + (addition), - (subtraction), * (multiplication), / (division), and % (modulo). For example, you can use this Java code to add two numbers: addThis + toThis
divideThis % byThis
System.out.println("Counted " + count + " chars.");
do { . . . } while (count++ < 6);

Relational and Conditional Operators

A relational operator compares two values and determines the relationship between them. For example, != returns true if the two operands are unequal. The countChars method uses != to determine whether the value returned by in.read is not equal to -1 . This table summarizes Java's relational operators: Operator Use Return true if > op1 > op2 op1 is greater than op2 >= op1 >= op2 op1 is greater than or equal to op2 op1 < op2 op1 is less than op2 <= op1 <= op2 op1 is less than or equal to op2 == op1 == op2 op1 and op2 are equal != op1 != op2 op1 and op2 are not equal Relational operators often are used with the conditional operators to construct more complex decision-making expressions. One such operator is && , which performs the boolean and operation. For example, you can use two different relational operators along with && to determine if both relationships are true. The following line of code uses this technique to determine if an array index is between two boundaries. It determines if the index is both greater than 0 and less than NUM_ENTRIES (which is a previously defined constant value): 0 < index && index < NUM_ENTRIES
((count > NUM_ENTRIES) && (in.read() != -1))
expression ? op1 : op2

Bitwise Operators

A bitwise operator allows you to perform bit manipulation on data. This table summarizes the bitwise and logical operators available in the Java language. Operator Use Operation >> op1 >> op2 shift bits of op1 right by distance op2 op1 shift bits of op1 left by distance op2 >>> op1 >>> op2 shift bits of op1 right by distance op2 (unsigned) & op1 & op2 bitwise and | op1 | op2 bitwise or ^ op1 ^ op2 bitwise xor ~ ~op2 bitwise complement The three shift operators simply shift the bits of the left-hand operand over by the number of positions indicated by the right-hand operand. The shift occurs in the direction indicated by the operator itself. For example, the following statement, shifts the bits of the integer 13 to the right by one position: 13 >> 1;
1101 & 1100 ------ 1100
final int VISIBLE = 1; final int DRAGGABLE = 2; final int SELECTABLE = 4; final int EDITABLE = 8; int flags = 0;
flags = flags | VISIBLE;
flags & VISIBLE

Assignment Operators

You use the basic assignment operator, = , to assign one value to another. The countChars method uses = to initialize count with this statement: int count = 0;

CS101: Introduction to Computer Science I

shortcut assignment operator java

Java Data and Operators

This chapter goes into more depth about relational and logical operators. You will have to use these concepts to write complex programs that other people can read and follow.

3. Numeric Data and Operators

3.4. assignment operators.

In addition to the simple assignment operator (=), Java supplies a number of shortcut assignment operators that allow you to combine an arithmetic operation and an assignment in one operation. These operations can be used with either integer or floating-point operands. For example, the += operator allows you to combine addition and assignment into one expression. The statement

is equivalent to the statement

Similarly, the statement

is equivalent to

As these examples illustrate, when using the += operator, the expression on its right-hand side is first evaluated and then added to the current value of the variable on its left-hand side.

Table 5.8 lists the other assignment operators that can be used in combination with the arithmetic operators. 

Table 5.8 Java's assignment operators

For each of these operations, the interpretation is the same: Evaluate the expression on the right-hand side of the operator and then perform the arithmetic operation (such as addition or multiplication) to the current value of the variable on the left of the operator.

shortcut assignment operator java

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 1.1 Preface
  • 1.2 Why Programming? Why Java?
  • 1.3 Variables and Data Types
  • 1.4 Expressions and Assignment Statements
  • 1.5 Compound Assignment Operators
  • 1.6 Casting and Ranges of Variables
  • 1.7 Java Development Environments (optional)
  • 1.8 Unit 1 Summary
  • 1.9 Unit 1 Mixed Up Code Practice
  • 1.10 Unit 1 Coding Practice
  • 1.11 Multiple Choice Exercises
  • 1.12 Lesson Workspace
  • 1.4. Expressions and Assignment Statements" data-toggle="tooltip">
  • 1.6. Casting and Ranges of Variables' data-toggle="tooltip" >

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

1.5. Compound Assignment Operators ¶

Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to x and assigns the sum to x. It is the same as x = x + 1 . This pattern is possible with any operator put in front of the = sign, as seen below.

The most common shortcut operator ++ , the plus-plus or increment operator, is used to add 1 to the current value; x++ is the same as x += 1 and the same as x = x + 1 . It is a shortcut that is used a lot in loops. If you’ve heard of the programming language C++, the ++ in C++ is an inside joke that C has been incremented or improved to create C++. The -- decrement operator is used to subtract 1 from the current value: y-- is the same as y = y - 1 . These are the only two double operators; this shortcut pattern does not exist with other operators. Run the following code to see these shortcut operators in action!

coding exercise

Run the code below to see what the ++ and shorcut operators do. Use the Codelens to trace through the code and observe how the variable values change. Try creating more compound assignment statements with shortcut operators and guess what they would print out before running the code.

exercise

1-5-2: What are the values of x, y, and z after the following code executes?

  • x = -1, y = 1, z = 4
  • This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y.
  • x = -1, y = 2, z = 3
  • x = -1, y = 2, z = 2
  • x = -1, y = 2, z = 4

1-5-3: What are the values of x, y, and z after the following code executes?

  • x = 6, y = 2.5, z = 2
  • This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3).
  • x = 4, y = 2.5, z = 2
  • x = 6, y = 2, z = 3
  • x = 4, y = 2.5, z = 3
  • x = 4, y = 2, z = 3

1.5.1. Code Tracing Challenge and Operators Maze ¶

Code Tracing is a technique used to simulate by hand a dry run through the code or pseudocode as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does.

Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column or row in a table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing.

For example, given the following code:

The corresponding trace table looks like this:

Alternatively, we can show a compressed trace by listing the sequence of values assigned to each variable as the program executes. You might want to cross off the previous value when you assign a new value to a variable. The last value listed is the variable’s final value.

Compressed Trace

Use paper and pencil to trace through the following program to determine the values of the variables at the end. Be careful, % is the remainder operator, not division.

The final value for x is

The final value for y is

The final value for z is

1.5.2. Prefix versus Postfix Operator ¶

What do you think is printed when the following code is executed? Try to guess the output before running the code. You might be surprised at the result. Click on CodeLens to step through the execution. Notice that the second println prints the original value 7 even though the memory location for variable count is updated to the value 8.

The code System.out.println(count++) adds one to the variable after the value is printed. Try changing the code to ++count and run it again. This will result in one being added to the variable before its value is printed. When the ++ operator is placed before the variable, it is called prefix increment. When it is placed after, it is called postfix increment.

  • System.out.println(score++);
  • Print the value 5, then assign score the value 6.
  • System.out.println(score--);
  • Print the value 5, then assign score the value 4.
  • System.out.println(++score);
  • Assign score the value 6, then print the value 6.
  • System.out.println(--score);
  • Assign score the value 4, then print the value 4.

When you are new to programming, it is advisable to avoid mixing unary operators ++ and -- with assignment or print statements. Try to perform the increment or decrement operation on a separate line of code from assignment or printing.

For example, instead of writing x=y++; or System.out.println(z--); the code below makes it clear that the increment of y happens after the assignment to x , and that the value of z is printed before it is decremented.

  • System.out.println(score); score++;
  • System.out.println(score); score--;
  • score++; System.out.println(score);
  • score--; System.out.println(score);

1.5.3. Summary ¶

Compound assignment operators (+=, -=, *=, /=, %=) can be used in place of the assignment operator.

The increment operator (++) and decrement operator (–) are used to add 1 or subtract 1 from the stored value of a variable. The new value is assigned to the variable.

  • Enterprise Java
  • Web-based Java
  • Data & Java
  • Project Management
  • Visual Basic
  • Ruby / Rails
  • Java Mobile
  • Architecture & Design
  • Open Source
  • Web Services

Developer.com

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More .

Java Programming tutorials

Java provides many types of operators to perform a variety of calculations and functions, such as logical , arithmetic , relational , and others. With so many operators to choose from, it helps to group them based on the type of functionality they provide. This programming tutorial will focus on Java’s numerous a ssignment operators.

Before we begin, however, you may want to bookmark our other tutorials on Java operators, which include:

  • Arithmetic Operators
  • Comparison Operators
  • Conditional Operators
  • Logical Operators
  • Bitwise and Shift Operators

Assignment Operators in Java

As the name conveys, assignment operators are used to assign values to a variable using the following syntax:

The left side operand of the assignment operator must be a variable, whereas the right side operand of the assignment operator may be a literal value or another variable. Moreover, the value or variable on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. Assignment operators have a right to left associativity in that the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side variable must be declared before assignment.

You can learn more about variables in our programming tutorial: Working with Java Variables .

Types of Assignment Operators in Java

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 in addition to the equals ( = ) sign.

Equals Operator (=) Java Example

First, let’s learn to use the one-and-only simple assignment operator – the Equals ( = ) operator – with the help of a Java program. It includes two assignments: a literal value to num1 and the num1 variable to num2 , after which both are printed to the console to show that the values have been assigned to the numbers:

The += Operator Java Example

A compound of the + and = operators, the += adds the current value of the variable on the left to the value on the right before assigning the result to the operand on the left. Here is some sample code to demonstrate how to use the += operator in Java:

The -= Operator Java Example

Made up of the – and = operators, the -= first subtracts the variable’s value on the right from the current value of the variable on the left before assigning the result to the operand on the left. We can see it at work below in the following code example showing how to decrement in Java using the -= operator:

The *= Operator Java Example

This Java operator is comprised of the * and = operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. Here’s a program that shows the *= operator in action:

The /= Operator Java Example

A combination of the / and = operators, the /= Operator divides the current value of the variable on the left by the value on the right and then assigns the quotient to the operand on the left. Here is some example code showing how to use the  /= operator in Java:

%= Operator Java Example

The %= operator includes both the % and = operators. As seen in the program below, it divides the current value of the variable on the left by the value on the right and then assigns the remainder to the operand on the left:

Compound Bitwise and Shift Operators in Java

The Bitwise and Shift Operators that we just recently covered can also be utilized in compound form as seen in the list below:

  • &= – Compound bitwise Assignment operator.
  • ^= – Compound bitwise ^ assignment operator.
  • >>= – Compound right shift assignment operator.
  • >>>= – Compound right shift filled 0 assignment operator.
  • <<= – Compound left shift assignment operator.

The following program demonstrates the working of all the Compound Bitwise and Shift Operators :

Final Thoughts on Java Assignment Operators

This programming tutorial presented an overview of Java’s simple and compound assignment Operators. An essential building block to any programming language, developers would be unable to store any data in their programs without them. Though not quite as indispensable as the equals operator, compound operators are great time savers, allowing you to perform arithmetic and bitwise operations and assignment in a single line of code.

Read more Java programming tutorials and guides to software development .

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

What is the role of a project manager in software development, how to use optional in java, overview of the jad methodology, microsoft project tips and tricks, how to become a project manager in 2023, related stories, understanding types of thread synchronization errors in java, understanding memory consistency in java threads.

Developer.com

01 Career Opportunities

  • Top 50 Java Interview Questions and Answers
  • Java Developer Salary Guide in India – For Freshers & Experienced

02 Beginner

  • Best Java Developer Roadmap 2024
  • Hierarchical Inheritance in Java
  • Arithmetic operators in Java
  • Unary operator in Java
  • Ternary Operator in Java
  • Relational operators in Java

Assignment operator in Java

  • Logical operators in Java
  • Single Inheritance in Java
  • Primitive Data Types in Java
  • Multiple Inheritance in Java
  • Hybrid Inheritance in Java
  • Parameterized Constructor in Java
  • Constructor Chaining in Java
  • Constructor Overloading in Java
  • What are Copy Constructors In Java? Explore Types,Examples & Use
  • What is a Bitwise Operator in Java? Type, Example and More
  • Top 10 Reasons to know why Java is Important?
  • What is Java? A Beginners Guide to Java
  • Differences between JDK, JRE, and JVM: Java Toolkit
  • Variables in Java: Local, Instance and Static Variables
  • Data Types in Java - Primitive and Non-Primitive Data Types
  • Conditional Statements in Java: If, If-Else and Switch Statement
  • What are Operators in Java - Types of Operators in Java ( With Examples )
  • Looping Statements in Java - For, While, Do-While Loop in Java
  • Java VS Python
  • Jump Statements in JAVA - Types of Statements in JAVA (With Examples)
  • Java Arrays: Single Dimensional and Multi-Dimensional Arrays
  • What is String in Java - Java String Types and Methods (With Examples)

03 Intermediate

  • OOPs Concepts in Java: Encapsulation, Abstraction, Inheritance, Polymorphism
  • Access Modifiers in Java: Default, Private, Public, Protected
  • What is Class in Java? - Objects and Classes in Java {Explained}
  • Constructors in Java: Types of Constructors with Examples
  • Polymorphism in Java: Compile time and Runtime Polymorphism
  • Abstraction in Java: Concepts, Examples, and Usage
  • What is Inheritance in Java: Types of Inheritance in Java
  • Exception handling in Java: Try, Catch, Finally, Throw and Throws

04 Training Programs

  • Java Programming Course
  • C++ Programming Course
  • MERN: Full-Stack Web Developer Certification Training
  • Data Structures and Algorithms Training
  • Assignment Operator In Ja..

Assignment operator in Java

Java Programming For Beginners Free Course

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 manipulating and assigning values to variables. To further enhance your understanding and application of Java assignment operator's concepts, consider enrolling in the best Java Certification Course .

What are the Assignment Operators in Java?

Assignment operators in Java are used to assign values to variables . They are classified into two main types: simple assignment operator and compound assignment operator.

The general syntax for a simple assignment statement is:

And for a compound assignment statement:

Read More - Advanced Java Interview Questions

Types of Assignment Operators in Java

  • Simple Assignment Operator: The Simple Assignment Operator is used with the "=" sign, where the operand is on the left side and the value is on the right. The right-side value must be of the same data type as that defined on the left side.
  • Compound Assignment Operator:  Compound assignment operators combine arithmetic operations with assignments. They provide a concise way to perform an operation and assign the result to the variable in one step. The Compound Operator is utilized when +,-,*, and / are used in conjunction with the = operator.

1. Simple Assignment Operator (=):

The equal sign (=) is the basic assignment operator in Java. It is used to assign the value on the right-hand side to the variable on the left-hand side.

Explanation

2. addition assignment operator (+=) :, 3. subtraction operator (-=):, 4. multiplication operator (*=):.

Read More - Java Developer Salary

5. Division Operator (/=):

6. modulus assignment operator (%=):, example of assignment operator in java.

Let's look at a few examples in our Java Playground to illustrate the usage of assignment operators in Java:

  • Unary Operator in Java
  • Arithmetic Operators in Java
  • Relational Operators in Java
  • Logical Operators 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.

  • 1. (=) operator
  • 1. (+=) operator
  • 2. (-=) operator
  • 3. (*=) operator
  • 4. (/=) operator
  • 5. (%=) operator

About Author

Author image

We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Java Tutorial

Overview of Java

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

Basics of Java

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

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

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

Flow Control in Java

  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Java Arithmetic Operators with Examples
  • Java Unary Operator with Examples
  • Java Assignment Operators with Examples
  • Java Relational Operators with Examples
  • Java Logical Operators with Examples
  • Java Ternary Operator with Examples
  • Bitwise Operators in Java
  • Strings in Java
  • String class in Java
  • Java.lang.String class in Java | Set 2
  • Why Java Strings are Immutable?
  • StringBuffer class in Java
  • StringBuilder Class in Java with Examples
  • String vs StringBuilder vs StringBuffer in Java
  • StringTokenizer Class in Java
  • StringTokenizer Methods in Java with Examples | Set 2
  • StringJoiner Class in Java
  • Arrays in Java
  • Arrays class in Java
  • Multidimensional Arrays in Java
  • Different Ways To Declare And Initialize 2-D Array in Java
  • Jagged Array in Java
  • Final Arrays in Java
  • Reflection Array Class in Java
  • util.Arrays vs reflect.Array in Java with Examples

OOPS in Java

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

Access Modifiers in Java

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

Inheritance in Java

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

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

Constructors in Java

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

Methods in Java

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

Keywords in Java

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

Memory Allocation in Java

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

Classes of Java

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

Packages in Java

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

Exception Handling in Java

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

File Handling in Java

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

JDBC - Java Database Connectivity

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

Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. In this article, we will learn about Java Operators and learn all their types.

What are the Java Operators?

Operators in Java are the symbols used for performing specific operations in Java. Operators make tasks like addition, multiplication, etc which look easy although the implementation of these tasks is quite complex.

Types of Operators in Java

There are multiple types of operators in Java all are mentioned below:

  • Arithmetic Operators
  • Unary Operators
  • Assignment Operator
  • Relational Operators
  • Logical Operators
  • Ternary Operator
  • Bitwise Operators
  • Shift Operators
  • instance of operator

1. Arithmetic Operators

They are used to perform simple arithmetic operations on primitive data types. 

  • * : Multiplication
  • / : Division
  • + : Addition
  • – : Subtraction

2. Unary Operators

Unary operators need only one operand. They are used to increment, decrement, or negate a value. 

  • – : Unary minus , used for negating the values.
  • + : Unary plus indicates the positive value (numbers are positive without this, however). It performs an automatic conversion to int when the type of its operand is the byte, char, or short. This is called unary numeric promotion.
  • Post-Increment: Value is first used for computing the result and then incremented.
  • Pre-Increment: Value is incremented first, and then the result is computed.
  • Post-decrement: Value is first used for computing the result and then decremented.
  • Pre-Decrement: The value is decremented first, and then the result is computed.
  • ! : Logical not operator , used for inverting a boolean value.

3. Assignment Operator

 ‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left associativity, i.e. value given on the right-hand side of the operator is assigned to the variable on the left, and therefore right-hand side value must be declared before using it or should be a constant. 

The general format of the assignment operator is:

In many cases, the assignment operator can be combined with other operators to build a shorter version of the statement called a Compound Statement . For example, instead of a = a+5, we can write a += 5. 

  • += , for adding the left operand with the right operand and then assigning it to the variable on the left.
  • -= , for subtracting the right operand from the left operand and then assigning it to the variable on the left.
  • *= , for multiplying the left operand with the right operand and then assigning it to the variable on the left.
  • /= , for dividing the left operand by the right operand and then assigning it to the variable on the left.
  • %= , for assigning the modulo of the left operand by the right operand and then assigning it to the variable on the left.

4. Relational Operators

These operators are used to check for relations like equality, greater than, and less than. They return boolean results after the comparison and are extensively used in looping statements as well as conditional if-else statements. The general format is, 

Some of the relational operators are- 

  • ==, Equal to returns true if the left-hand side is equal to the right-hand side.
  • !=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
  • <, less than: returns true if the left-hand side is less than the right-hand side.
  • <=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side.
  • >, Greater than: returns true if the left-hand side is greater than the right-hand side.
  • >=, Greater than or equal to returns true if the left-hand side is greater than or equal to the right-hand side.

5. Logical Operators

These operators are used to perform “logical AND” and “logical OR” operations, i.e., a function similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e., it has a short-circuiting effect. Used extensively to test for several conditions for making a decision. Java also has “Logical NOT”, which returns true when the condition is false and vice-versa

Conditional operators are:

  • &&, Logical AND: returns true when both conditions are true.
  • ||, Logical OR: returns true if at least one condition is true.
  • !, Logical NOT: returns true when a condition is false and vice-versa

6. Ternary operator

The ternary operator is a shorthand version of the if-else statement. It has three operands and hence the name Ternary.

The general format is:

The above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else execute the statements after the ‘:’.  

7. Bitwise Operators

These operators are used to perform the manipulation of individual bits of a number. They can be used with any of the integer types. They are used when performing update and query operations of the Binary indexed trees. 

  • &, Bitwise AND operator: returns bit by bit AND of input values.
  • |, Bitwise OR operator: returns bit by bit OR of input values.
  • ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
  • ~, Bitwise Complement Operator: This is a unary operator which returns the one’s complement representation of the input value, i.e., with all bits inverted.

8. Shift Operators

These operators are used to shift the bits of a number left or right, thereby multiplying or dividing the number by two, respectively. They can be used when we have to multiply or divide a number by two. General format- 

  • <<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as multiplying the number with some power of two.
  • >>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit depends on the sign of the initial number. Similar effect to dividing the number with some power of two.
  • >>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit is set to 0.

9. instanceof operator

The instance of the operator is used for type checking. It can be used to test if an object is an instance of a class, a subclass, or an interface. General format- 

Precedence and Associativity of Java Operators

Precedence and associative rules are used when dealing with hybrid equations involving more than one type of operator. In such cases, these rules determine which part of the equation to consider first, as there can be many different valuations for the same equation. The below table depicts the precedence of operators in decreasing order as magnitude, with the top representing the highest precedence and the bottom showing the lowest precedence.

Precedence and Associativity of Operators in Java

Interesting Questions about Java Operators 

1. precedence and associativity:.

 There is often confusion when it comes to hybrid equations which are equations having multiple operators. The problem is which part to solve first. There is a golden rule to follow in these situations. If the operators have different precedence, solve the higher precedence first. If they have the same precedence, solve according to associativity, that is, either from right to left or from left to right. The explanation of the below program is well written in comments within the program itself.

2. Be a Compiler: 

The compiler in our systems uses a lex tool to match the greatest match when generating tokens. This creates a bit of a problem if overlooked. For example, consider the statement a=b+++c ; too many of the readers might seem to create a compiler error. But this statement is absolutely correct as the token created by lex is a, =, b, ++, +, c. Therefore, this statement has a similar effect of first assigning b+c to a and then incrementing b. Similarly, a=b+++++c; would generate an error as the tokens generated are a, =, b, ++, ++, +, c. which is actually an error as there is no operand after the second unary operand.

3. Using + over (): 

When using the + operator inside system.out.println() make sure to do addition using parenthesis. If we write something before doing addition, then string addition takes place, that is, associativity of addition is left to right, and hence integers are added to a string first producing a string, and string objects concatenate when using +. Therefore it can create unwanted results.

Advantages of Operators in Java

The advantages of using operators in Java are mentioned below:

  • Expressiveness : Operators in Java provide a concise and readable way to perform complex calculations and logical operations.
  • Time-Saving: Operators in Java save time by reducing the amount of code required to perform certain tasks.
  • Improved Performance : Using operators can improve performance because they are often implemented at the hardware level, making them faster than equivalent Java code.

Disadvantages of Operators in Java

The disadvantages of Operators in Java are mentioned below:

  • Operator Precedence: Operators in Java have a defined precedence, which can lead to unexpected results if not used properly.
  • Type Coercion : Java performs implicit type conversions when using operators, which can lead to unexpected results or errors if not used properly.

FAQs in Java Operators

1. what is operators in java with example.

Operators are the special symbols that are used for performing certain operations. For example, ‘+’ is used for addition where 5+4 will return the value 9.

Please Login to comment...

Similar reads.

  • Google Introduces New AI-powered Vids App
  • Dolly Chaiwala: The Microsoft Windows 12 Brand Ambassador
  • 10 Best Free Remote Desktop apps for Android in 2024
  • 10 Best Free Internet Speed Test apps for Android in 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

ShorthandoperatorExpl.java

Shorthand Operator in Java

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • Blogs by Topic

The IntelliJ IDEA Blog

IntelliJ IDEA – the Leading Java and Kotlin IDE, by JetBrains

  • Twitter Twitter
  • Facebook Facebook
  • Youtube Youtube

Java 22 and IntelliJ IDEA

Mala Gupta

Java 22 is here, fully supported by IntelliJ IDEA 2024.1 , allowing you to use these features now!

Java 22 has something for all – from new developers to Java experts, features related to performance and security for big organizations to those who like working with bleeding edge technology, from additions to the Java language to improvements in the JVM platform, and more.

It is also great to see how all these Java features, release after release, work together to create more possibilities and have a bigger impact on how developers create their applications that address existing pain points, perform better and are more secure.

This blog post doesn’t include a comprehensive coverage of all the Java 22 features. If you are interested in that, I’d recommend you to check out this link to know everything about what’s new and changing in Java 22, including the bugs.

In this blog post, I’ll cover how IntelliJ IDEA helps you get started, up and running with some of the Java 22 features, such as, String Templates , Implicitly Declared Classes and Instance Main Methods , Statements before super() , and Unnamed variables and patterns .

Over the past month, I published separate blog posts to cover each of these topics in detail. If you are new to these topics, I’d highly recommend you check out those detailed blog posts (I’ve included their links in the relevant subsections in this blog post). In this blog post, I’ll cover some sections from those blog posts, especially how IntelliJ IDEA supports them. Let’s start by configuring IntelliJ IDEA to work with the Java 22 features.

IntelliJ IDEA Configuration

Java 22 support is available in IntelliJ IDEA 2024.1 Beta . The final version will release soon in March 2024.

In your Project Settings, set the SDK to Java 22. For the language level, select ‘22 (Preview) – Statements before super(), string templates (2nd preview etc.)’ on both the Project and Modules tab, as shown in the below settings screenshot:

shortcut assignment operator java

If you do not have Java 22 downloaded to your system yet, don’t worry; IntelliJ IDEA has your back! You could use the same Project settings window, select ‘Download JDK’, after you click on the drop down next to SDK. You’ll see the below popup that would enable you to choose from a list of vendors (such as Oracle OpenJDK, GraalVM, Azul Zulu and others):

shortcut assignment operator java

With the configuration under our belt, let’s get started with covering one of my favorite new features, that is, String Templates.

String Templates (Preview Language feature) The existing String concatenation options are difficult to work with and could be error prone; String templates offer a better alternative, that is, String interpolation with additional benefits such as validation, security and transformations via template processors.

Please check out my detailed blog post on this topic: String Templates in Java – why should you care? if you are new to this topic. It covers all the basics, including why you need String Templates, with multiple hands-on examples on built-in and user defined String processors.

IntelliJ IDEA can highlight code that could be replaced with String Templates Let’s assume you defined the following code to log a message that combines string literals and variable values using the concatenation operator:

The output from the preceding code could be an issue if you miss adding spaces in the String literals. The code isn’t quite easy to read or understand due to multiple opening and closing double quotes, that is, " and the + operator, and it would get worse if you add more literals, or variable values to it.

You could replace the preceding code with either StringBuilder.append() , String.format() or String.formatted() method or by using the class MessageFormat (as shown in my detailed blog post on this topic), but each of these methods have their own issues.

Don’t worry; IntelliJ IDEA could detect such code, suggest that you could replace it with String template, and do that for you, as shown below. It doesn’t matter if you are not even aware of the syntax of the String templates, IntelliJ IDEA has your back 🙂

Embedded expressions in String Templates and IntelliJ IDEA The syntax to embed a remplate expression (variable, expressible or a method call) is still new to what Java developers are used to and could be challenging to use without help. Don’t worry, IntelliJ IDEA has your back!

Each embedded expression must be enclosed within \{}. When you type \{, IntelliJ IDEA adds the closing ‘}’ for you. It also offers code completion to help you select a variable in scope, or any methods on it. If the code that you insert doesn’t compile, IntelliJ IDEA will highlight that too (as a compilation error), as shown in the following gif:

Using String Templates with Text Blocks Text blocks are quite helpful when working with string values that span multiple lines, such as, JSON, XML, HTML, SQL or other values that are usually processed by external environments. It is common for us Java developers to create such string values using a combination of string literals and variable values (variables, expressions or method calls).

The example below shows how IntelliJ IDEA could detect and create a text block using String templates for multiline string values that concatenates string literals with variable values. It also shows how IntelliJ IDEA provides code completion for variable names within such blocks. When you type in \{ , IntelliJ IDEA adds } . As you start typing the variable name countryName , it shows the available variables in that context:

Language injection and String Templates You could also inject a language or a reference in string values that spans single line or multiple lines, such as, a text block. By doing so, you get comprehensive coding assistance to edit the literal value. You could avail of this feature temporarily or permanently by using the @Language annotation, as shown below:

You can check out this link for detailed information on the benefits and usage of injecting language or reference in IntelliJ IDEA.

Predefined Template Processors With the String templates, you get access to predefined processors like the STR , FMT and RAW . I’d highly recommend you to check out my detailed blog post on String templates for multiple hands-on examples on it.

Custom Template Processor

Let’s work with a custom String template that isn’t covered in my previous blog post.

Imagine you’d like to create an instance of a record, say, WeatherData , that stores the details of the JSON we used in the previous section. Assume you define the following records to store this weather data represented by the JSON in the previous section:

You could create a method to return a custom String template that would process interpolated string, accept a class name ( WeatherData for this example) and return its instance:

Depending on the logic of your application, you might want to escape, delete or throw errors for the special characters that you encounter in the the JSON values interpolated via template expressions, as follows (the following method chooses to escape the special characters and include them as part of the JSON value):

You could initialize and use this custom JSON template processor as below. Note how elegant and concise the solution is with a combination of textblocks and String templates. The JSON is easy to read, write and understand (thanks to text blocks). The template expressions make it clear and obvious about the sections that are not constants and would be injected by the variables. At the end, the custom template processor WEATHER_JSON would ensure the resultant JSON is validated according to the logic you defined and returns an instance of WeatherData (doesn’t it sound magical?) :

Do not miss to check out my detailed blog post on this topic: String Templates in Java – why should you care? to discover how you could use the predefined String templates like FMT , to generate properly formatted receipts for, say, your neighborhood stationery store, or, say encode and decode combinations like :) or :( to emojis like 🙂 or ☹️. Does that sound fun to you?

Implicitly Declared Classes and Instance Main Methods (Preview language feature)

Introduced as a preview language feature in Java 21, this feature is in its second preview in Java 22.

It would revolutionize how new Java developers would get started learning Java. It simplifies the initial steps for students when they start learning basics, such as variable assignment, sequence, conditions and iteration. Students no longer need to declare an explicit class to develop their code, or write their main() method using this signature – public static void main(String []) . With this feature, classes could be declared implicitly and the main() method can be created with a shorter list of keywords.

If you are new to this feature, I’d highly recommend you to check out my detailed blog post: ‘HelloWorld’ and ‘main()’ meet minimalistic on this feature. In this blog post, I’ll include a few of the sections from it.

Class ‘HelloWorld’ before and after Java 21

Before Java 21, you would need to define a class, say, HelloWorld , that defined a main() method with a specific list of keywords, to print any text, say, ‘Hello World’ to the console, as follows:

With Java 21, this initial step has been shortened. You can define a source code file, say, HelloWorld.java, with the following code, to print a message to the console (it doesn’t need to define a class; it has a shorter signature for method main() ):

The preceding code is simpler than what was required earlier. Let’s see how this change could help you focus on what you need, rather than what you don’t.

Compiling and executing your code

Once you are done writing your code, the next step is to execute it.

On the command prompt, you could use the javac and java commands to compile and execute your code. Assuming you have defined your code in a source code file HelloWorld.java, you could use the following commands to run and execute it:

Since Java 11, it is possible to skip the compilation process for code defined in a single source code file, so you could use just the second command (by specifying the name of the source code file, as follows):

However, since instance main methods and implicit classes is a preview language feature, you should add the flag --enable-preview with --source 22 with these commands, as follows:

Sooner or later, you might switch to using an IDE to write your code. If you wish to use IntelliJ IDEA for creating instance main methods, here’s a quick list of steps to follow. Create a new Java project, select the build system as IntelliJ (so you could use Java compiler and runtime tools), create a new file, say, HelloWorld.java with your instance main method and set the properties to use Java 22, before you run your code, as shown in the following gif (It could save you from typing out the compilation/ execution commands on the command prompt each time you want to execute your code):

Are you wondering if it would be better to create a ‘Java class’ instead of a ‘File’ in the ‘src’ folder? The option of selecting a Java class would generate the body of a bare minimum class, say, public class HelloWorld { } . Since we are trying to avoid unnecessary keywords in the beginning, I recommended creating a new ‘File’ which wouldn’t include any code.

What else can main() do apart from printing messages to the console?

As included in my detailed post on this topic , I included multiple hand-on examples to show what you could achieve via just the main() method:

  • Example 1. Variable declarations, assignments and simple calculations
  • Example 2. Print patterns, such as, big letters using a specified character
  • Example 3. Animating multiline text – one word at a time
  • Example 4. Data structure problems
  • Example 5. Text based Hangman game

The idea to include multiple examples as listed above is to demonstrate the power of sequence, condition and iteration all of which can be included in the main() method, to build good programming foundations with problem solving skills. By using the run command or the icon to run and execute their code in IntelliJ IDEA, new programmers reduce another step when getting started.

Changing an implicit class to a regular class

When you are ready to level up and work with other concepts like user defined classes, you could also covert the implicit classes and code that we used in the previous examples, to regular classes, as shown below:

What happens when you create a source code file with method main(), but no class declaration?

Behind the scenes, the Java compiler creates an implicit top level class, with a no-argument constructor, so that these classes don’t need to be treated in a way that is different to the regular classes.

Here’s a gif that shows a decompiled class for you for the source code file AnimateText.java:

Variations of the main method in the implicit class

As we are aware, a method can be overloaded. Does that imply an implicit class can define multiple main methods? If yes, which one of them qualifies as the ‘main’ method? This is an interesting question. First of all, know that you can’t define a static and non-static main method with the same signature, that is, with the same method parameters. The following method are considered valid main() methods in an implicit class:

If there is no valid main method detected, IntelliJ IDEA could add one for you, as shown in the following gif:

Educators could use this feature to introduce other concepts to the students in an incremental way

If you are an educator, you could introduce your students to other commonly used programming practices, such as creating methods- that is delegating part of your code to another method and calling it from the main method. You could also talk about passing values vs. variables to these methods.

The following gif shows how to do it:

Statements before super() – a preview language feature

Typically, we create alternative solutions for tasks that are necessary, but not officially permitted. For instance, executing statements before super() in a derived class constructor was not officially allowed, even though it was important for, say, validating values being passed to the base class constructor. A popular workaround involved creating static methods to validate values and then calling these methods on the arguments of super() . Though this approach worked well, it could make the code look complicated. This is changing with Statements before super() , a preview language feature in Java 22.

By using this feature, you can opt for a more direct approach, that is, drop the workaround of creating static methods, and execute code that validates arguments, just before calling super() . Terms and conditions still apply, such as, not accessing instance members of a derived class before execution of super() completes.

An example – Validating values passed to super() in a derived class constructor Imagine you need to create a class, say, IndustryElement , that extends class Element , which is defined as follows:

The constructor of the class Element misses checking if the atomicNumber is in the range of 1-118 (all known elements have atomic numbers between 1 to 118). Often the source code of a base class is not accessible or open for modification. How would you validate the values passed to atomicNumber in the constructor of class IndustryElement ?

Until Java 21, no statements were allowed to execute before super() . Here’s one of the ways we developers found a workaround by defining and calling static methods (static methods belong to a class and not to instances and can be executed before any instance of a class exists):

Starting Java 22, you could inline the contents of your static method in the constructor for your derived class, as shown in the following gif:

Here’s the resultant code for your reference:

Where else would you use this feature? If you are new to this feature, I’d recommend that you check out my detailed blog post, Constructor Makeover in Java 22 , in which I’ve covered this feature in detail using the following examples:

  • Example 2 – base class constructor parameters that use annotations for validations
  • Example 3 – Transforming variable values received in a derived class constructor, before calling a base class constructor.
  • Example 4 – Executing statements before this() in constructor of Records
  • Example 5 – Executing statements before this() in Enum constructors
  • Example 6 – Executing statements before this() in classes

How does it work behind the scenes? The language syntax has been relaxed but it doesn’t change or impact the internal JVM instructions. There are no changes to the JVM instructions for this new feature because the order of execution of the constructors still remains unchanged – from base class to a derived class. Also, this feature still doesn’t allow you to use members of a derived class instance, until super() executes.

Let’s access and compare the instruction set of the constructor of class IndustryElement , before and after its modification – one that can execute statements before super() and the one that doesn’t. To do so, use the following command:

Here’s the instruction set for the constructor that doesn’t explicitly execute statements before super() and calls static methods to validate range of atomic number:

shortcut assignment operator java

Here’s instruction set for the constructor that explicitly executes statements before super() to validate range of atomic number:

shortcut assignment operator java

The most important point to note here is that in both the cases, the constructor of the base class, that is, Element is called, after the execution of all other statements. Essentially, it means, you are still doing the same thing, it is just packaged in a way that makes things easier for you.

I understand it is difficult to remember what each of these instruction codes means. Access the following link and search for the instruction code and following the above instructions set would be a breeze:

https://docs.oracle.com/javase/specs/jvms/se21/html/jvms-6.html#jvms-6.5.aload_n

Can you execute ‘any’ statements before calling super()?

No. If the statements before super() try to access instance variables or execute methods of your derived class, your code won’t compile. For example, if you change the static checkRange() method to an instance method, your code won’t compile, as shown below:

Unnamed Variables and Patterns

Starting Java 22, using Unnamed Variables & Patterns you can mark unused local variables, patterns and pattern variables to be ignored, by replacing their names (or their types and names) with an underscore, that is, _ . Since such variables and patterns no longer have a name, they are referred to as Unnamed variables and patterns. Ignoring unused variables would reduce the time and energy anyone would need to understand a code snippet. In the future, this could prevent errors :-). This language feature doesn’t apply to instance or class variables.

Are you wondering if replacing unused variables with _ is always a good idea, or do they imply code smells and should you consider refactoring your codebase to remove them? Those are good questions to ask. If you are new to this topic, I’d recommend you to check out my detailed blog post: Drop the Baggage: Use ‘_’ for Unnamed Local Variables and Patterns in Java 22 to find out answer to this question.

Since this is not a preview language feature, set Language Level in your Project Settings to ‘22 – Unnamed variables and patterns’ on both the Project and Modules tab, as shown in the below settings screenshot:

shortcut assignment operator java

A quick example

The following gif gives a sneak peek into how an unused local variable, connection, is detected by IntelliJ IDEA, and could be replaced with an underscore, that is, _ .

The modified code shown in the preceding gif makes it clear that the local variable defined in the try-with-resources statement is unused, making it concise and easier to understand.

Unused Patterns and Pattern variables in switch constructs

Imagine you defined a sealed interface, say, GeometricShape , and records to represent shapes, such as, Point , Line , Triangle , Square , as shown in the following code:

Now assume you need a method that accepts an instance of GeometricShape and returns its area. Since Point and a Line are considered one-dimensional shapes, they wouldn’t have an area. Following is one of the ways to define such method that calculates and returns area:

In the previous example, the patterns int x , int y , Point a and Point B (for case label Line) remain unused as detected by IntelliJ IDEA. These could be replaced by an _ . Also, since all the record components of the case Point remain unused, it could be replaced as Point _ . This could also allow us to merge the first and second case labels. All of these steps are shown in the following gif:

Here’s the modified code for your reference:

In the preceding example, you can’t delete the pattern variables even if they are unused. The code must include the cases when the instance passed to the method calcArea() is of type Point and Line , so that it could return 0 for them.

Unused Patterns or variables with nested records

This feature also comes in quite handy for nested records with multiple unused patterns or pattern variables, as demonstrated using the following example code:

In the preceding code, since the if condition in the method checkFirstNameAndCountryCodeAgain uses only two pattern variables, others could be replaced using _ ; it reduced the noise in the code too.

Where else can you use this feature? Checkout my detailed detailed blog post: Drop the Baggage: Use ‘_’ for Unnamed Local Variables and Patterns in Java 22 to learn more about other use cases where this feature can be used:

  • Requirements change, but you need side effects of constructs like an enhanced for-loop
  • Unused parameters in exception handlers; whose signature can’t be modified
  • Unused auto-closeable resources in try-with-resources statements

It isn’t advisable to use this feature without realising if an unused variable or pattern is a code smell or not. I used these examples to show that at times it might be better to refactor your code to get rid of the unused variable instead of just replacing it with an underscore, that is, _ .

  • Unused lambda parameter
  • Methods with multiple responsibilities

Preview Features

‘String Templates’, ‘Implicitly Declared Classes and Instance Main Methods’ and ‘Statements before super()’ are preview language features in Java 22. With Java’s new release cadence of six months, new language features are released as preview features. They may be reintroduced in later Java versions in the second or more preview, with or without changes. Once they are stable enough, they may be added to Java as a standard language feature.

Preview language features are complete but not permanent, which essentially means that these features are ready to be used by developers, although their finer details could change in future Java releases depending on developer feedback. Unlike an API, language features can’t be deprecated in the future. So, if you have feedback about any of the preview language features, feel free to share it on the JDK mailing list (free registration required).

Because of how these features work, IntelliJ IDEA is committed to only supporting preview features for the current JDK. Preview language features can change across Java versions, until they are dropped or added as a standard language feature. Code that uses a preview language feature from an older release of the Java SE Platform might not compile or run on a newer release.

In this blog post, I covered four Java 22 features – String Templates , Implicitly Declared Classes and Instance Main Methods , Statements before super() , and Unnamed variable and patterns .

String Templates is a great addition to Java. Apart from helping developers to work with strings that combine string constants and variables, they provide a layer of security. Custom String templates can be created with ease to accomplish multiple tasks, such as, to decipher letter combinations, either ignoring them or replacing them for added security.

Java language designers are reducing the ceremony that is required to write the first HelloWorld code for Java students, by introducing implicitly declared classes and instance main methods. New students can start with bare minimum main() method, such as, void main() and build strong programming foundation by polishing their skills with basics like sequence, selection and iteration.

In Java 22, the feature Statements before super() lets you execute code before calling super() in your derived class constructors, this() in your records or enums, so that you could validate the method parameters, or transform values, as required. This avoids creating workarounds like creating static methods and makes your code easier to read and understand. This feature doesn’t change how constructors would operate now vs. how they operated earlier – the JVM instructions remain the same.

Unnamed variables are local to a code construct, they don’t have a name, and they are represented by using an underscore, that is, _ . They can’t be passed to methods, or used in expressions. By replacing unused local variables in a code base with _ their intention is conveyed very clearly. It clearly communicates to anyone reading a code snippet that the variable is not used elsewhere. Until now, this intention could only be communicated via comments, which, unfortunately, all developers don’t write.

Happy Coding!

shortcut assignment operator java

Subscribe to IntelliJ IDEA Blog updates

By submitting this form, I agree that JetBrains s.r.o. ("JetBrains") may use my name, email address, and location data to send me newsletters, including commercial communications, and to process my personal data for this purpose. I agree that JetBrains may process said data using third-party services for this purpose in accordance with the JetBrains Privacy Policy . I understand that I can revoke this consent at any time in my profile . In addition, an unsubscribe link is included in each email.

Thanks, we've got you!

Discover more

shortcut assignment operator java

Java Frameworks You Must Know in 2024

Many developers trust Java worldwide because it is adaptable, secure, and versatile, making it perfect for developing various applications across multiple platforms. It also stands out for its readability and scalability. What are frameworks? Why do you need them? Since Java has a long history…

Irina Mariasova

Java Annotated Monthly – April 2024

Welcome to this month’s Java Annotated Monthly, where we’ll cover the most prominent updates, news, and releases in March. This edition is truly special because it introduces a new section – Featured content, where we invite influential people from the industry to share a personal selection of inter…

shortcut assignment operator java

Getting Started with Databases in IntelliJ IDEA 

Have you ever wondered how IntelliJ IDEA handles databases? Well, today is the perfect opportunity to find out in our database tutorial on initial setups and first steps.   All of the features you’ll need when working with databases are available out of the box in IntelliJ IDEA Ultimate…

shortcut assignment operator java

Easy Hacks: How to Throw Java Exceptions

Exceptions in Java are used to indicate that an event occurred during the execution of a program and disrupted the normal flow of instructions. When an exception occurs, the Java runtime automatically stops the execution of the current method. It passes an exception object with information about the…

Maarten Balliauw

IMAGES

  1. Assignment Operators in Java with Examples

    shortcut assignment operator java

  2. Beginner Java Tutorial #11: Shorthand Assignment Operators

    shortcut assignment operator java

  3. What are Operators in Java and its Types?

    shortcut assignment operator java

  4. The Assignment Operator in Java

    shortcut assignment operator java

  5. Java Assignment Operators

    shortcut assignment operator java

  6. Java Assignment Operators

    shortcut assignment operator java

VIDEO

  1. Airthmetical operator java Java Programming

  2. Bit-Wise Operator || java

  3. assignment operator simple program in java..#java # assignment_operator

  4. java

  5. #20. Assignment Operators in Java

  6. Core

COMMENTS

  1. Shortcut "or-assignment" (|=) operator in Java

    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:

  2. Java Assignment Operators with Examples

    variable operator value; Types of Assignment Operators in Java. The Assignment Operator is generally of two types. They are: 1. Simple Assignment Operator: The Simple Assignment Operator is used with the "=" sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

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

    The Simple Assignment Operator. One of the most common operators that you'll encounter is the simple assignment operator "=". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left: ... The Java programming language provides operators that perform addition, subtraction, multiplication, and ...

  4. Java Assignment Operators (Basic & Shorthand) by Example

    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 ...

  5. Java: Assignment Operators

    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 ...

  6. Shortcut Assignment Operators

    Shortcut Assignment Operators. We can use the following shortcut operators in the assignment of variables: Incrementing and decrementing a value by one is so common, there are special (even shorter) shortcut operators for these tasks: The expression ( ++myVar) adds 1 to myVar, and if used in or as an expression, it evaluates to this new ...

  7. Operators

    In addition to the basic assignment operator, Java provides several short cut assignment operators that allow you to perform an arithmetic, logical, or bitwise operation and an assignment operation all with one operator. Specifically, suppose you wanted to add a number to a variable and assign the result back into the variable, like this:

  8. Assignment Operators

    The Java programming language also provides several shortcut assignment operators that allow you to perform an arithmetic, shift, or bitwise operation and an assignment operation all with one operator. Suppose that you wanted to add a number to a variable and assign the result back into the variable, like this:

  9. Java 8

    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.

  10. Java Assignment Operators

    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 ...

  11. Operators

    Assignment Operators You use the basic assignment operator, =, to assign one value to another. The countChars method uses = to initialize count with this statement: int count = 0; Java also provides several short cut assignment operators that allow you to perform an arithmetic, logical, or bitwise operation and an assignment operation all with ...

  12. Java Data and Operators: Assignment Operators

    In addition to the simple assignment operator (=), Java supplies a number of shortcut assignment operators that allow you to combine an arithmetic operation and an assignment in one operation. These operations can be used with either integer or floating-point operands. For example, the += operator allows you to combine addition and assignment ...

  13. 1.5. Compound Assignment Operators

    Compound Assignment Operators — CS Java. 1.5. Compound Assignment Operators ¶. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to x and assigns the sum to x. It is the same as x = x + 1. This pattern is possible with any operator put in front of the = sign, as seen ...

  14. Assignment Operators in Java

    Description:Welcome to Lecture 14 of our Java Programming series! In this enlightening tutorial, we're going to explore a crucial component of Java programmi...

  15. Java Assignment Operators

    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 ...

  16. Assignment operator in Java

    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 ...

  17. Java Assignment operators

    The Java Assignment operators are used to assign the values to the declared variables. The equals ( = ) operator is the most commonly used Java assignment operator. For example: int i = 25; The table below displays all the assignment operators in the Java programming language. Operators.

  18. Types of Assignment Operators in Java

    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.

  19. Operators in Java

    3. Assignment Operator '=' Assignment operator is used to assign a value to any variable. It has right-to-left associativity, i.e. value given on the right-hand side of the operator is assigned to the variable on the left, and therefore right-hand side value must be declared before using it or should be a constant.

  20. What is += Addition Assignment Operator in Java?

    It's the Addition assignment operator. Let's understand the += operator in Java and learn to use it for our day to day programming. x += y in Java is the same as x = x + y. It is a compound assignment operator. Most commonly used for incrementing the value of a variable since x++ only increments the value by one.

  21. Shorthand Operator in Java

    Because it offers a quick way to appoint an expression to a variable, it is known as shorthand. The above operator can be used to link the assignment operator and the algebraic operator. You might, for instance, write: a = a-7; The aforementioned sentence can also be expressed in Java as follows: a -= 7; Java uses a variety of compound ...

  22. Java 22 and IntelliJ IDEA

    IntelliJ IDEA Configuration. Java 22 support is available in IntelliJ IDEA 2024.1 Beta. The final version will release soon in March 2024. In your Project Settings, set the SDK to Java 22. For the language level, select '22 (Preview) - Statements before super (), string templates (2nd preview etc.)' on both the Project and Modules tab, as ...