• Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot
  • Java Ternary Operator with Examples
  • Java Arithmetic Operators with Examples
  • Java Assignment Operators with Examples
  • Equality (==) operator in Java with Examples
  • Java Logical Operators with Examples
  • Java Relational Operators with Examples
  • Short Circuit Logical Operators in Java with Examples
  • Java Unary Operator with Examples
  • Left Shift Operator in Java
  • Java Ternary Operator Puzzle
  • Difference between Simple and Compound Assignment in Java
  • Shift Operator in Java
  • & Operator in Java with Examples
  • || operator in Java
  • && operator in Java with Examples
  • What is Java Ring?
  • Types of References in Java
  • Java Debugger (JDB)
  • Remote Method Invocation in Java

Compound assignment operators in Java

Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. The following are all possible assignment operator in java:

Implementation of all compound assignment operator

Rules for resolving the Compound assignment operators

At run time, the expression is evaluated in one of two ways.Depending upon the programming conditions:

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion to the appropriate standard value set, and the result of the conversion is stored into the variable.
  • First, the array reference sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index sub-expression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
  • Otherwise, the index sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, if the value of the array reference sub-expression is null, then no assignment occurs and a NullPointerException is thrown.
  • Otherwise, the value of the array reference sub-expression indeed refers to an array. If the value of the index sub-expression is less than zero, or greater than or equal to the length of the array, then no assignment occurs and an ArrayIndexOutOfBoundsException is thrown.
  • Otherwise, the value of the index sub-expression is used to select a component of the array referred to by the value of the array reference sub-expression. The value of this component is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Examples : Resolving the statements with Compound assignment operators

We all know that whenever we are assigning a bigger value to a smaller data type variable then we have to perform explicit type casting to get the result without any compile-time error. If we did not perform explicit type-casting then we will get compile time error. But in the case of compound assignment operators internally type-casting will be performed automatically, even we are assigning a bigger value to a smaller data-type variable but there may be a chance of loss of data information. The programmer will not responsible to perform explicit type-casting. Let’s see the below example to find the difference between normal assignment operator and compound assignment operator. A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

For example, the following code is correct:

and results in x having the value 7 because it is equivalent to:

Because here 6.6 which is double is automatically converted to short type without explicit type-casting.

Refer: When is the Type-conversion required?

Explanation: In the above example, we are using normal assignment operator. Here we are assigning an int (b+1=20) value to byte variable (i.e. b) that’s results in compile time error. Here we have to do type-casting to get the result.

Explanation: In the above example, we are using compound assignment operator. Here we are assigning an int (b+1=20) value to byte variable (i.e. b) apart from that we get the result as 20 because In compound assignment operator type-casting is automatically done by compile. Here we don’t have to do type-casting to get the result.

Reference: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2

Please Login to comment...

Similar reads.

  • Java-Operators
  • 10 Best Slack Integrations to Enhance Your Team's Productivity
  • 10 Best Zendesk Alternatives and Competitors
  • 10 Best Trello Power-Ups for Maximizing Project Management
  • Google Rolls Out Gemini In Android Studio For Coding Assistance
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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.

Javatpoint Logo

Java Tutorial

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

JavaTpoint

Using Compound Assignment Operator in a Java Program

CompoundAssignmentOperator.java

Youtube

  • 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

Java Compound Assignment Operators

Java programming tutorial index.

Java provides some special Compound Assignment Operators , also known as Shorthand Assignment Operators . It's called shorthand because it provides a short way to assign an expression to a variable.

This operator can be used to connect Arithmetic operator with an Assignment operator.

For example, you write a statement:

In Java, you can also write the above statement like this:

There are various compound assignment operators used in Java:

While writing a program, Shorthand Operators saves some time by changing the large forms into shorts; Also, these operators are implemented efficiently by Java runtime system compared to their equivalent large forms.

Programs to Show How Assignment Operators Works

Arithmetic Operators in Java [In-Depth Tutorial]

Introduction to arithmetic operators in java.

In the realm of Java programming, arithmetic operators are indispensable tools for performing basic mathematical operations. Whether you are developing a complex algorithm or simply performing straightforward calculations, understanding Java Arithmetic Operators is a fundamental skill.

Arithmetic operators in Java allow you to carry out operations like addition, subtraction, multiplication, and division. These operators form the building blocks for more complex mathematical logic embedded in real-world Java applications. From calculating the area of a shape to adjusting the values in data arrays, Basic Arithmetic in Java serves as the foundation upon which more complex code is built.

In this guide, we will delve into the various types of arithmetic operators available in Java, their syntax, and how they can be effectively used in your code. Stay tuned for practical examples, best practices, and much more as we explore the integral role that Java Arithmetic Operators play in shaping effective and efficient Java programs.

Types of Arithmetic Operators in Java

Java offers a set of arithmetic operators to perform basic mathematical operations. Below is a table listing these operators, their function, and examples demonstrating their use.

Example Code:

Each of these arithmetic operators has a specific role to play in mathematical calculations within Java programs.

Syntax and Usage

The syntax for using arithmetic operators in Java is straightforward. These operators are binary operators, which means they require two operands, one on each side of the operator.

  • result : The variable where the result of the operation will be stored.
  • operand1 and operand2 : The numbers you wish to perform the operation on.
  • operator : The arithmetic operator you want to use ( + , - , * , / , % ).

Basic Examples

Let's break down how each of these arithmetic operators works.

Addition ( + ) : Adds two numbers together.

Subtraction ( - ) : Subtracts the second operand from the first.

Multiplication ( * ) : Multiplies the operands.

Division ( / ) : Divides the first operand by the second. Note that the result is an integer if both operands are integers. For a floating-point result, at least one operand must be a floating-point number.

Modulus ( % ) : Provides the remainder of the division of the first operand by the second.

Here's a simple Java program that demonstrates the usage of these operators:

Operator Precedence in Java

Operator precedence determines the order in which operators are evaluated in an expression. This is crucial for obtaining the correct results in calculations. Java has a well-defined set of rules for operator precedence, which closely follow those in mathematical notation.

Rules of Precedence

Here are the rules governing arithmetic operators in Java, listed from highest to lowest precedence:

  • Parentheses () : Expressions within parentheses are evaluated first.
  • Unary Operators (+, -, ++, --) : Unary operators come next, such as negation or increment.
  • Multiplication * , Division / , and Modulus % : These operators are evaluated next and from left to right.
  • Addition + and Subtraction - : These operators are evaluated last and also from left to right.

Example 1: Mixing Multiplication and Addition

Let's consider a basic example:

Here, multiplication has higher precedence than addition, so 3 * 4 is evaluated first, giving 12 . Then 2 + 12 is evaluated, resulting in 14 .

Example 2: Using Parentheses

Parentheses can be used to change the natural precedence of operators.

In this example, (2 + 3) is evaluated first due to the parentheses, giving 5 . Then 5 * 4 is evaluated, resulting in 20 .

Example 3: Multiple Operators of Same Precedence

When multiple operators with the same level of precedence appear in an expression, they are evaluated from left to right.

Here, both / and * have the same level of precedence. The operation is carried out from left to right, so 10 / 2 is evaluated first to 5 , and then 5 * 3 is evaluated, giving 15 .

Example 4: Combining Everything

Here is a more complex example combining different levels of precedence and parentheses:

  • Parentheses are evaluated first: (2 + 3) gives 5 and (1 + 1) gives 2 .
  • Multiplication and division are next: 5 * 4 gives 20 and 2 * 2 gives 4 .
  • Addition and subtraction last: 20 - 4 gives 16 .

Using Parentheses to Override Operator Precedence in Java

In Java, you can use parentheses to explicitly specify the order in which operations should be performed, thereby overriding the default operator precedence rules. This can be essential for achieving the intended results, especially in more complex mathematical expressions.

Why Use Parentheses?

Using parentheses can make your code more readable and less prone to errors. It can also be necessary when the natural order of operator precedence doesn't align with the calculation you need to perform.

Basic Example Without Parentheses

Consider a simple expression that mixes addition and multiplication:

In this case, the multiplication operation ( 3 * 4 ) has higher precedence and is performed before the addition ( 2 + 12 ), leading to a result of 14.

Using Parentheses to Override Precedence

You can use parentheses to change this order:

Here, the parentheses force the addition operation ( 2 + 3 ) to be performed first, resulting in 5. This is then multiplied by 4 to get 20.

Here's a more complex example that combines multiple operators:

By default, the multiplications are done first, then the addition, and finally the subtraction. If we want to perform the addition operations first, we can use parentheses like this:

In this example, the operations within the parentheses are performed first, changing the entire outcome of the expression.

Integer Division vs Floating-Point Division in Java

In Java, the behavior of the division operator / varies depending on the types of operands involved. Specifically, the distinction between integer division and floating-point division is a critical one that new Java programmers should understand to avoid unexpected results.

Integer Division

When both operands are integers, Java performs integer division. This means that the result of the division will also be an integer, with any remainder discarded (i.e., the result is truncated towards zero).

In the example above, 10 / 3 would be 3.333... in real arithmetic. However, because both a and b are integers, Java performs integer division, and the result is 3 .

Floating-Point Division

When one or both operands are floating-point numbers ( float or double ), Java performs floating-point division, and the result is a floating-point number.

Here, 10.0 / 3.0 gives 3.333... , which is the expected result in real arithmetic.

Mixing Integer and Floating-Point Operands

If you mix integer and floating-point operands, Java automatically promotes the integer to a floating-point number before performing the division.

In this case, the integer a is promoted to a floating-point number before the division, so the result is 3.333... .

How to Convert Integer Division to Floating-Point

You can also cast one or both of the integer operands to a floating-point type if you want a floating-point result.

The Modulo Operator in Java

The modulo operator % in Java is a useful arithmetic operator that finds frequent use in various programming scenarios. This operator returns the remainder of the division of one number by another.

The syntax for the modulo operation is similar to other arithmetic operations. Here's a basic example:

In this case, 10 divided by 3 gives a quotient of 3 and a remainder of 1 . Therefore, a % b returns 1 .

The modulo operator is especially handy for the following tasks:

Checking Parity : You can use % to determine if a number is even or odd.

Cyclic Behavior : For rotating through a set of values in a circular manner, modulo is very useful. For example, in array manipulations or problems involving circular linked lists .

Converting Between Number Systems : When converting numbers to different bases, the modulo operator helps to find the remainder at each stage.

Clock Arithmetic : For tasks like scheduling or when working with time, the modulo operator can be used to wrap around the clock.

Unary Operators in Java: Understanding + and -

In Java, unary operators are operators that act on a single operand. Among these, the unary + and - are arithmetic operators commonly used for various purposes. Let's delve into their syntax, usage, and importance in Java programming.

The syntax for unary + and - is straightforward. You prefix the operator to a single operand like so:

Usage and Importance

Sign Reversal : The primary use of the unary - operator is to reverse the sign of a numeric expression.

Here, the value of b becomes -10 , which is the negation of a .

No Operation : The unary + operator doesn't actually perform any operations. It merely returns the value of the operand as is. However, it can be used for clarity in certain contexts.

Readability : While not required, you may choose to use the unary + operator to indicate explicitly that a number is positive, which could enhance code readability in some situations.

Type Promotion : Unary + and - operators can also trigger implicit type conversion if applied to smaller types like byte or short .

In the above example, the type of b becomes int because the unary - operator triggers type promotion.

Compound Assignment Operators in Java

In Java, compound assignment operators offer a more concise way to perform operations and assign the results back to the variable. They combine basic arithmetic operations with assignment. Common compound arithmetic assignment operators include += , -= , *= , /= , and %= .

The general syntax for these operators is:

This is a shorthand for:

Usage and Examples

Addition and Assignment ( += )

Subtraction and Assignment ( -= )

Multiplication and Assignment ( *= )

Division and Assignment ( /= )

Modulus and Assignment ( %= )

Type Conversion and Casting in Java

When you're working with arithmetic operations in Java, understanding type conversion and casting can be crucial. These aspects govern how different types of variables interact with each other during arithmetic operations. Let's explore both automatic type conversion and explicit casting in the context of Java arithmetic.

Automatic Type Conversion

Java performs automatic type conversion when you operate on variables of different types. This feature is also known as "type promotion." In type promotion, the smaller type is promoted to the larger type before the operation. For instance:

In this example, the int value i is automatically promoted to a double before the addition takes place. As a result, you get a double value in result .

Rules for Automatic Type Conversion

  • All byte and short values are promoted to int .
  • If one operand is a double , the whole expression is promoted to double .
  • Otherwise, if one operand is a float , the whole expression is promoted to float .
  • Otherwise, if one operand is a long , the whole expression is promoted to long .

Explicit Casting

Sometimes, automatic type conversion is not what you want, and you may need to control this behavior. That's when explicit casting comes into play.

In this example, the double value d is explicitly cast to an int . Note that this operation truncates the decimal part.

Best Practices for Using Arithmetic Operators in Java

Arithmetic operations are the cornerstone of most Java programs, and understanding how to use these operators effectively can make a difference in your code's performance, readability, and maintainability. Below are some best practices to keep in mind when dealing with arithmetic operators in Java.

Use Parentheses for Clarity

While Java has rules governing operator precedence, relying solely on them can make your code harder to read and understand. Use parentheses to make the order of operations explicit.

Be Mindful of Integer Division

Java performs integer division if both operands are integers. If you expect a floating-point result, make sure at least one operand is a floating-point number.

Use += and Other Compound Operators

Compound operators like += , -= , *= , etc., make your code more concise and can improve readability.

Avoid Magic Numbers

Instead of directly coding numerical values into your operations, use named constants for better readability and maintainability.

Use Modular Arithmetic Wisely

The % operator is not just for finding remainders; it can also be used to wrap-around counts, constrain values, etc. However, be cautious when using it with negative numbers, as the behavior may not be what you expect.

Check for Arithmetic Exceptions

Though Java handles most arithmetic issues gracefully, you should be aware of exceptions like division by zero, which leads to ArithmeticException .

Frequently Asked Questions

Arithmetic operations in Java can sometimes lead to questions, especially for beginners. Here are some of the most frequently asked questions related to Java's arithmetic operators, along with their answers.

1. Why is my division result always an integer?

In Java, when you divide two integers, the result will also be an integer, with the fractional part truncated. If you want a floating-point result, at least one operand should be a floating-point number.

2. What is the % operator used for?

The % operator is called the modulo or remainder operator. It returns the remainder when one number is divided by another. It's useful in a variety of contexts, including working with circular buffers, constraining values, or finding remainders.

3. What's the difference between x = x + 1 and x++ ?

Both x = x + 1 and x++ increment the value of x by 1. The difference is mainly syntactic sugar: x++ is a shorthand and can make the code more concise.

4. Can I perform arithmetic operations on char variables?

Yes, you can. A char in Java is essentially a 16-bit unsigned integer under the hood. When you perform arithmetic operations involving a char , it is promoted to an int .

5. What happens if an arithmetic operation causes an overflow?

Java does not provide automatic overflow checking for primitive types. The value will simply "wrap around." For example, adding 1 to the maximum value of an int will give you the minimum possible int value.

6. What is type casting and when should I use it?

Type casting is the process of converting one data type to another. Use it when you need to perform operations between different types of numbers, or when you need to store the result of an operation in a variable of a different type.

Arithmetic operators are fundamental building blocks in Java programming, allowing you to perform basic mathematical operations like addition, subtraction, multiplication, and division. These operators are invaluable for any kind of numerical computation, data manipulation, and logic building in Java applications. Understanding how to use them effectively, along with associated concepts like operator precedence, type conversion, and compound assignment, will significantly improve your Java coding skills. This article aims to provide a comprehensive guide to understanding and using arithmetic operators in Java for both beginners and those looking to refresh their knowledge.

Additional Resources

Official Java Documentation : The Java Language Specification provides an in-depth look at arithmetic operators. Java Operators Explained [Easy Examples] Stack Overflow : Often, real-world questions related to arithmetic operators are answered in this community . Operators More about Java Operators

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can reach out to him on his LinkedIn profile or join on Facebook page.

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

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

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

Buy GoLinuxCloud a Coffee

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

Thank You for your support!!

Leave a Comment Cancel reply

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

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

  • 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

  • Java history and features
  • Download and Install JDK
  • Environment setup & first program
  • Primitve Data types
  • Class Access Modifiers
  • Class Member Access Modifiers
  • Abstract Class
  • Final keyword in Java
  • Static keyword in Java
  • this keyword in Java
  • Encapsulation
  • Inheritance
  • Aggregation and composition
  • Polymorphism
  • Overloading
  • Constructors in Java
  • Coupling and cohesion
  • Stack and Heap in Java
  • Array in Java
  • 2-Dimensional Array in Java
  • Enums in Java
  • Return Types in Java
  • Var-args in Java
  • Garbage Collector
  • Method finalize()
  • Static Initialization Block
  • Instance Initialization Block
  • Static vs Instance Block
  • decision-making Statements
  • If Statement
  • If-Else Statement
  • Else-If Statement
  • Nested If Statement
  • Nested If-Else Statement
  • Switch Statement
  • Do-While Loop
  • Break Statement
  • Continue Statement
  • Labelled Break Statement
  • Labelled Continue Statement
  • Arithmetic Operator
  • Increment Operator
  • Decrement Operator
  • Compound Assignment Operators
  • Relational Operators
  • Logical Operators
  • Conditional Operator
  • instanceof operator
  • Character Wrapper Class
  • Boolean Wrapper Class
  • Byte Wrapper Class
  • Short Wrapper Class
  • Integer Wrapper Class
  • Long Wrapper Class
  • Float Wrapper Class
  • Double Wrapper Class
  • Autoboxing and Unboxing
  • Widening and Narrowing
  • What is Exception?
  • Checked Exception
  • Unchecked Exception
  • Exception Propagation
  • Try-Catch block
  • Multiple Catch Blocks
  • Finally block
  • Throw Keyword
  • Throws Keyword
  • User Defined Exception

Advertisement

+= operator

  • Add operation.
  • Assignment of the result of add operation.
  • Understanding += operator with a code -
  • Statement i+=2 is equal to i=i+2 , hence 2 will be added to the value of i, which gives us 4.
  • Finally, the result of addition, 4 is assigned back to i, updating its original value from 2 to 4.
  • A special case scenario for all the compound assigned operators
  • All compound assignment operators perform implicit casting.
  • Casting the char value ( smaller data type ) to an int value( larger data type ), so it could be added to an int value, 2.
  • Finally, the result of performing the addition resulted in an int value, which was casted to a char value before it could be assigned to a char variable, ch .

Example with += operator

-= operator.

  • Subtraction operation.
  • Assignment of the result of subtract operation.
  • Statement i-=2 is equal to i=i-2 , hence 2 will be subtracted from the value of i, which gives us 0.
  • Finally, the result of subtraction i.e. 0 is assigned back to i, updating its value to 0.

Example with -= operator

*= operator.

  • Multiplication operation.
  • Assignment of the result of multiplication operation.
  • Statement i*=2 is equal to i=i*2 , hence 2 will be multiplied with the value of i, which gives us 4.
  • Finally, the result of multiplication, 4 is assigned back to i, updating its value to 4.

Example with *= operator

/= operator.

  • Division operation.
  • Assignment of the result of division operation.
  • Statement i/=2 is equal to i=i/2 , hence 4 will be divided by the value of i, which gives us 2.
  • Finally, the result of division i.e. 2 is assigned back to i, updating its value from 4 to 2.

Example with /= operator

%= operator.

  • Modulus operation, which finds the remainder of a division operation.
  • Assignment of the result of modulus operation.
  • Statement i%=2 is equal to i=i%2 , hence 4 will be divided by the value of i and its remainder gives us 0.
  • Finally, the result of this modulus operation i.e. 0 is assigned back to i, updating its value from 4 to 0.

Example with %= operator

Please share this article -.

Facebook

Please Subscribe

Decodejava Facebook Page

Notifications

Please check our latest addition C#, PYTHON and DJANGO

© Copyright 2020 Decodejava.com. All Rights Reserved.

  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

Java operator

last modified January 27, 2024

In this article we show how to work with operators in Java.

An operator is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data. An operand is one of the inputs (arguments) of an operator.

Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands. The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators.

An operator usually has one or two operands. Those operators that work with only one operand are called unary operators . Those who work with two operands are called binary operators . There is also one ternary operator ?: which works with three operands.

Certain operators may be used in different contexts. For example the + operator. It can be used in different cases. It adds numbers, concatenates strings, or indicates the sign of a number. We say that the operator is overloaded .

Java sign operators

There are two sign operators: + and - . They are used to indicate or change the sign of a value.

The + and - signs indicate the sign of a value. The plus sign can be used to signal that we have a positive number. It can be omitted and it is mostly done so.

The minus sign changes the sign of a value.

Java assignment operator

The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In mathematics, the = operator has a different meaning. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.

Here we assign a number to the x variable.

This expression does not make sense in mathematics, but it is legal in programming. The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x.

This code line results in syntax error. We cannot assign a value to a literal.

Java concatenating strings

In Java the + operator is also used to concatenate strings.

We join three strings together.

Strings are joined with the + operator.

An alternative method for concatenating strings is the concat method.

Java increment and decrement operators

Incrementing or decrementing a value by one is a common task in programming. Java has two convenient operators for this: ++ and -- .

The above two pairs of expressions do the same.

In the above example, we demonstrate the usage of both operators.

We initiate the x variable to 6. Then we increment x two times. Now the variable equals to 8.

We use the decrement operator. Now the variable equals to 7.

And here is the output of the example.

Java arithmetic operators

The following is a table of arithmetic operators in Java.

The following example shows arithmetic operations.

In the preceding example, we use addition, subtraction, multiplication, division, and remainder operations. This is all familiar from the mathematics.

The % operator is called the remainder or the modulo operator. It finds the remainder of division of one number by another. For example, 9 % 4 , 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1.

Next we show the distinction between integer and floating point division.

In the preceding example, we divide two numbers.

In this code, we have done integer division. The returned value of the division operation is an integer. When we divide two integers the result is an integer.

If one of the values is a double or a float, we perform a floating point division. In our case, the second operand is a double so the result is a double.

We see the result of the program.

Java Boolean operators

In Java we have three logical operators. The boolean keyword is used to declare a Boolean value.

Boolean operators are also called logical.

Many expressions result in a boolean value. For instance, boolean values are used in conditional statements.

Relational operators always result in a boolean value. These two lines print false and true.

The body of the if statement is executed only if the condition inside the parentheses is met. The y > x returns true, so the message "y is greater than x" is printed to the terminal.

The true and false keywords represent boolean literals in Java.

The code example shows the logical and (&&) operator. It evaluates to true only if both operands are true.

Only one expression results in true .

The logical or ( || ) operator evaluates to true if either of the operands is true.

If one of the sides of the operator is true, the outcome of the operation is true.

Three of four expressions result in true .

The negation operator ! makes true false and false true.

The example shows the negation operator in action.

The || , and && operators are short circuit evaluated. Short circuit evaluation means that the second argument is only evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of the logical and evaluates to false, the overall value must be false; and when the first argument of logical or evaluates to true, the overall value must be true. Short circuit evaluation is used mainly to improve performance.

An example may clarify this a bit more.

We have two methods in the example. They are used as operands in boolean expressions. We will see if they are called.

The One method returns false. The short circuit && does not evaluate the second method. It is not necessary. Once an operand is false, the result of the logical conclusion is always false. Only "Inside one" is only printed to the console.

In the second case, we use the || operator and use the Two method as the first operand. In this case, "Inside two" and "Pass" strings are printed to the terminal. It is again not necessary to evaluate the second operand, since once the first operand evaluates to true, the logical or is always true.

Java relational operators

Relational operators are used to compare values. These operators always result in a boolean value.

Relational operators are also called comparison operators.

In the code example, we have four expressions. These expressions compare integer values. The result of each of the expressions is either true or false. In Java we use the == to compare numbers. (Some languages like Ada, Visual Basic, or Pascal use = for comparing numbers.)

Java bitwise operators

Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal, or hexadecimal symbols are only notations of a number. Bitwise operators work with bits of a binary number. Bitwise operators are seldom used in higher level languages like Java.

The bitwise negation operator changes each 1 to 0 and 0 to 1.

The operator reverts all bits of a number 7. One of the bits also determines whether the number is negative or not. If we negate all the bits one more time, we get number 7 again.

The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.

The first number is a binary notation of 6, the second is 3 and the result is 2.

The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if either of the corresponding bits in the operands is 1.

The result is 00110 or decimal 7.

The bitwise exclusive or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.

The result is 00101 or decimal 5.

Java compound assignment operators

Compound assignment operators are shorthand operators which consist of two operators.

The += compound operator is one of these shorthand operators. The above two expressions are equal. Value 3 is added to the a variable.

Other compound operators are:

The following example uses two compound operators.

We use the += and *= compound operators.

The a variable is initiated to one. Value 1 is added to the variable using the non-shorthand notation.

Using a += compound operator, we add 5 to the a variable. The statement is equal to a = a + 5; .

Using the *= operator, the a is multiplied by 3. The statement is equal to a = a * 3; .

Java instanceof operator

The instanceof operator compares an object to a specified type.

In the example, we have two classes: one base and one derived from the base.

This line checks if the variable d points to the class that is an instance of the Base class. Since the Derived class inherits from the Base class, it is also an instance of the Base class too. The line prints true.

The b object is not an instance of the Derived class. This line prints false.

Every class has Object as a superclass. Therefore, the d object is also an instance of the Object class.

Java lambda operator

Java 8 introduced the lambda operator ( -> ).

This is the basic syntax for a lambda expression in Java. Lambda expression allow to create more concise code in Java.

The declaration of the type of the parameter is optional; the compiler can infer the type from the value of the parameter. For a single parameter the parentheses are optional; for multiple parameters, they are required.

The curly braces are optional if there is only one statement in an expression body. Finally, the return keyword is optional if the body has a single expression to return a value; curly braces are required to indicate that the expression returns a value.

In the example, we define an array of strings. The array is sorted using the Arrays.sort method and a lambda expression.

Lambda expressions are used primarily to define an inline implementation of a functional interface, i.e., an interface with a single method only. Interfaces are abstract types that are used to enforce a contract.

In the example, we create a greeting service with the help of a lambda expression.

Interface GreetingService is created. All objects implementing this interface must implement the greet method.

We create an object that implements GreetingService with a lambda expression. The object has a method that prints a message to the console.

We call the object's greet method, which prints a give message to the console.

There are some common functional interfaces, such as Function , Consumer , or Supplier .

The example uses a lambda expression to compute squares of integers.

Function is a function that accepts one argument and produces a result. The operation of the lamda expression produces a square of the given integer.

Java double colon operator

The double colon operator (::) is used to create a reference to a method.

In the code example, we create a reference to a static method with the double colon operator.

We have a static method that prints a greeting to the console.

Consumer is a functional interface that represents an operation that accepts a single input argument and returns no result. With the double colon operator, we create a reference to the greet method.

We perform the functional operation with the accept method.

Java operator precedence

The operator precedence tells us which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions.

What is the outcome of the following expression, 28 or 40?

Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.

To change the order of evaluation, we can use parentheses. Expressions inside parentheses are always evaluated first. The result of the above expression is 40.

Java operators precedence list

The following table shows common Java operators ordered by precedence (highest precedence first):

Operators on the same row of the table have the same precedence. If we use operators with the same precedence, then the associativity rule is applied.

In this code example, we show a few expressions. The outcome of each expression is dependent on the precedence level.

This line prints 28. The multiplication operator has a higher precedence than addition. First, the product of 5*5 is calculated, then 3 is added.

In this case, the negation operator has a higher precedence than the bitwise OR. First, the initial true value is negated to false, then the | operator combines false and true, which gives true in the end.

Java associativity rule

Sometimes the precedence is not satisfactory to determine the outcome of an expression. There is another rule called associativity . The associativity of operators determines the order of evaluation of operators with the same precedence level.

What is the outcome of this expression, 9 or 1? The multiplication, deletion, and the modulo operator are left to right associated. So the expression is evaluated this way: (9 / 3) * 3 and the result is 9.

Arithmetic, boolean, relational, and bitwise operators are all left to right associated. The assignment operators, ternary operator, increment, decrement, unary plus and minus, negation, bitwise NOT, type cast, object creation operators are right to left associated.

In the example, we have two cases where the associativity rule determines the expression.

The assignment operator is right to left associated. If the associativity was left to right, the previous expression would not be possible.

The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and then the compound assignment operator is applied.

Java ternary operator

The ternary operator ?: is a conditional operator. It is a convenient operator for cases where we want to pick up one of two values, depending on the conditional expression.

If cond-exp is true, exp1 is evaluated and the result is returned. If the cond-exp is false, exp2 is evaluated and its result is returned.

In most countries the adulthood is based on the age. You are adult if you are older than a certain age. This is a situation for a ternary operator.

First the expression on the right side of the assignment operator is evaluated. The first phase of the ternary operator is the condition expression evaluation. So if the age is greater or equal to 18, the value following the ? character is returned. If not, the value following the : character is returned. The returned value is then assigned to the adult variable.

A 31 years old person is adult.

Calculating prime numbers

In the following example, we are going to calculate prime numbers.

In the above example, we deal with several operators. A prime number (or a prime) is a natural number that has exactly two distinct natural number divisors: 1 and itself. We pick up a number and divide it by numbers from 1 to the selected number. Actually, we do not have to try all smaller numbers; we can divide by numbers up to the square root of the chosen number. The formula will work. We use the remainder division operator.

We will calculate primes from these numbers.

Values 0 and 1 are not considered to be primes.

We skip the calculations for 2 and 3. They are primes. Note the usage of the equality and conditional or operators. The == has a higher precedence than the || operator. So we do not need to use parentheses.

We are OK if we only try numbers smaller than the square root of a number in question.

This is a while loop. The i is the calculated square root of the number. We use the decrement operator to decrease i by one each loop cycle. When i is smaller than 1, we terminate the loop. For example, we have number 9. The square root of 9 is 3. We will divide the 9 number by 3 and 2. This is sufficient for our calculation.

If the remainder division operator returns 0 for any of the i values, then the number in question is not a prime.

In this article we covered Java expressions. We mentioned various types of operators and described precedence and associativity rules in expressions.

Java operators - tutorial

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Java tutorials .

Java Compound Assignment Operators

In this chapter you will learn:

Description

Statements like the following

can be rewritten as

Both statements perform the same action: they increase the value of a by 4.

Any statement of the form

Here is a sample program that shows several op= operator assignments:

The output of this program is shown here:

Next chapter...

What you will learn in the next chapter:

Java Operators

Java arithmetic operators, java unary plus and minus, java increment and decrement, java number division by zero, java assignment operator, java compound assignment, java operator precedence, java relational operators, java logical operators, java conditional operator, java instanceof operator, java new operator, java modulus operator, java java bitwise operators, java bitwise logical operators, java left shift operator, java right shift operator, java unsigned right shift, java bitwise compound operators, java short-circuit operators, java java arithmetic operators example, java example, java arithmetic compound assignment operators.

A compound assignment operator is an operator that performs a calculation and an assignment at the same time.

All of Java's binary arithmetic operators (the ones that work on two operands) have equivalent compound assignment operators.

The statement

is equivalent to

Also, the statement

Thus, any statement of the form

can be rewritten as

To prevent confusion, use compound assignment expressions by themselves, not in combination with other expressions.

Consider these statements:

Is a set to 7 or 8?

In other words, is the third statement equivalent to

The assignment has the lowest precedence of all, and the multiplication here is performed as part of the assignment. As a result, the addition is performed before the multiplication - and the answer is 8.

Here is a sample program that shows several op= assignments in action:

The output of this program is shown here:

COMMENTS

  1. Compound assignment operators in Java

    Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. ... The following are all possible assignment operator in java: 1.

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

    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. ... You can also combine the arithmetic operators with the simple assignment operator to create compound assignments ...

  3. Java Compound Operators

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

  4. Java Compound Assignment Operators (With Examples)

    Compound assignment operators in Java are shorthand notations that combine an arithmetic or bitwise operation with an assignment. They allow you to perform an operation on a variable's value and then assign the result back to the same variable in a single step.

  5. Compound Assignment Operator in Java

    The compound assignment operator is the combination of more than one operator. It includes an assignment operator and arithmetic operator or bitwise operator. The specified operation is performed between the right operand and the left operand and the resultant assigned to the left operand. Generally, these operators are used to assign results ...

  6. Java Compound Assignment Operators

    This operator can be used to connect Arithmetic operator with an Assignment operator. For example, you write a statement: a = a+6; In Java, you can also write the above statement like this: a += 6; There are various compound assignment operators used in Java:

  7. Arithmetic Operators in Java [In-Depth Tutorial]

    In Java, compound assignment operators offer a more concise way to perform operations and assign the results back to the variable. They combine basic arithmetic operations with assignment. Common compound arithmetic assignment operators include +=, -=, *=, /=, and %=. The general syntax for these operators is:

  8. Java Operators

    We've learned arithmetic operators. We can combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, we can write "a = a + 5" in a compound way: "a += 5". Finally, let's walk through all supported compound assignments in Java through examples:

  9. Java Compound Assignment Operators (Arithmetic Examples)

    Boolean operators are used to perform logical comparisons, and always result in one of two values: true or false. Following are the most commonly used Boolean operators : AND: Compares two values and returns true if they are both true. OR: Compares two values and returns true if either of the values are true. Negation: Flips the state of a value.

  10. Java Compound Assignment Operators

    Learn about the Java Compound Assignment Operators. They are basically shorthand or shortcut operators for performing arithmetic and assigning a variable at ...

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

  12. Java Compound Operators

    Compound operators, also called combined assignment operators, are a shorthand way to update the value of a variableThey are+= (addition)-= (subtraction)*= (...

  13. Arithmetic and Assignment Operators Explained in Java

    Assignment Operators The assignment operator (=) assigns a value to a variable. y = y+7; The above expression adds 7 to y and then assigns the final result to y. If you're new to programming, this expression might seem a little weird. This shouldn't bother you as the compiler will understand what you're trying to do. Compound Assignment

  14. Arithmetic Compound Assignment Operators In Java

    Siva Nookala - 18 Feb 2019. Arithmetic Compound Assignment Operators In Java are used to combine an arithmetic operation with an assignment operation. e.g., marks += 5; instead of marks = marks + 5; Compound assignment operators provide a shorter syntax for assigning the result of an arithmetic operator. If the we want to multiply a variable ...

  15. Java Arithmetic Operators

    Similarly, the following program shows how to use the Java arithmetic operators on floating-point numbers: public class App { public static void main (String[] ... Compound assignment operators. To add a value to a variable, you use the + operator and assign the result back to the variable.

  16. Java

    In all the compound assignment operators, the expression on the right side of = is always calculated first and then the compound assignment operator will start its functioning. Hence in the last code, statement i+=2*2; is equal to i=i+ (2*2), which results in i=i+4, and finally it returns 6 to i. All compound assignment operators perform ...

  17. java

    4. For a += 4 javac can produce IIC instruction which does Increment local variable by constant. It is theoretically more efficient then IADD. IADD does Add int with popping up two values from stack then pushing back the result. IIC does nothing on stack but increments local variable. So if you may work on a very limited and primitive JVM like ...

  18. Performance of Arithmetic Compound Assignment Operators in Java

    I noticed in my benchmarks that arithmetic compound operators in Java always outperform the regular assignment: d0 *= d0; //faster //d0 = d0 * d0; //slower d0 += d0; //faster //d0 = d0 + d0; //slower Could someone please comment on the above observation and explain why it is the case.

  19. Java operator

    The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and then the compound assignment operator is applied. $ java Associativity.java 0 0 0 0 0 Java ternary operator

  20. Arithmetic Compound Assignment Operators

    Java Compound Assignment Operators. In this chapter you will learn: What are Arithmetic Compound Assignment Operators; Syntax for Arithmetic Compound Assignment Operators; Example - Arithmetic Compound Assignment Operators; Description. Statements like the following a = a + 4; can be rewritten as

  21. Java Arithmetic Compound Assignment Operators

    A compound assignment operator is an operator that performs a calculation and an assignment at the same time. All of Java's binary arithmetic operators (the ones that work on two operands) have equivalent compound assignment operators. The statement. is equivalent to. Also, the statement.