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

Overview of Java

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

Basics of Java

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

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

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

Flow Control in Java

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

Java Assignment Operators with Examples

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

OOPS in Java

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

Access Modifiers in Java

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

Inheritance in Java

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

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

Constructors in Java

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

Methods in Java

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

Keywords in Java

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

Memory Allocation in Java

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

Classes of Java

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

Packages in Java

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

Exception Handling in Java

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

File Handling in Java

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

JDBC - Java Database Connectivity

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

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

Types of Operators: 

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

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

Assignment Operators

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

Types of Assignment Operators in Java

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

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

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

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

1. (=) operator: 

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

Syntax:  

Example:  

2. (+=) operator: 

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

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

Reason for the Above Calculation

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

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

3. (-=) operator: 

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

4. (*=) operator:

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

5. (/=) operator: 

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

6. (%=) operator: 

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

Please Login to comment...

Similar reads.

  • Java-Operators
  • 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?

clear sunny desert yellow sand with celestial snow bridge

1.7 Java | Assignment Statements & Expressions

An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java.

After a variable is declared, you can assign a value to it by using an assignment statement . In Java, the equal sign = is used as the assignment operator . The syntax for assignment statements is as follows:

An expression represents a computation involving values, variables, and operators that, when taking them together, evaluates to a value. For example, consider the following code:

You can use a variable in an expression. A variable can also be used on both sides of the =  operator. For example:

In the above assignment statement, the result of x + 1  is assigned to the variable x . Let’s say that x is 1 before the statement is executed, and so becomes 2 after the statement execution.

To assign a value to a variable, you must place the variable name to the left of the assignment operator. Thus the following statement is wrong:

Note that the math equation  x = 2 * x + 1  ≠ the Java expression x = 2 * x + 1

Java Assignment Statement vs Assignment Expression

Which is equivalent to:

And this statement

is equivalent to:

Note: The data type of a variable on the left must be compatible with the data type of a value on the right. For example, int x = 1.0 would be illegal, because the data type of x is int (integer) and does not accept the double value 1.0 without Type Casting .

◄◄◄BACK | NEXT►►►

What's Your Opinion? Cancel reply

Enhance your Brain

Subscribe to Receive Free Bio Hacking, Nootropic, and Health Information

HTML for Simple Website Customization My Personal Web Customization Personal Insights

DISCLAIMER | Sitemap | ◘

SponserImageUCD

HTML for Simple Website Customization My Personal Web Customization Personal Insights SEO Checklist Publishing Checklist My Tools

Top Posts & Pages

1. VbScript | Message Box

assignment expression in 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.3. Variables and Data Types" data-toggle="tooltip">
  • 1.5. Compound Assignment Operators' data-toggle="tooltip" >

1.4. Expressions and Assignment Statements ¶

In this lesson, you will learn about assignment statements and expressions that contain math operators and variables.

1.4.1. Assignment Statements ¶

Remember that a variable holds a value that can change or vary. Assignment statements initialize or change the value stored in a variable using the assignment operator = . An assignment statement always has a single variable on the left hand side of the = sign. The value of the expression on the right hand side of the = sign (which can contain math operators and other variables) is copied into the memory location of the variable on the left hand side.

Assignment statement

Figure 1: Assignment Statement (variable = expression) ¶

Instead of saying equals for the = operator in an assignment statement, say “gets” or “is assigned” to remember that the variable on the left hand side gets or is assigned the value on the right. In the figure above, score is assigned the value of 10 times points (which is another variable) plus 5.

The following video by Dr. Colleen Lewis shows how variables can change values in memory using assignment statements.

As we saw in the video, we can set one variable to a copy of the value of another variable like y = x;. This won’t change the value of the variable that you are copying from.

coding exercise

Click on the Show CodeLens button to step through the code and see how the values of the variables change.

The program is supposed to figure out the total money value given the number of dimes, quarters and nickels. There is an error in the calculation of the total. Fix the error to compute the correct amount.

Calculate and print the total pay given the weekly salary and the number of weeks worked. Use string concatenation with the totalPay variable to produce the output Total Pay = $3000 . Don’t hardcode the number 3000 in your print statement.

exercise

Assume you have a package with a given height 3 inches and width 5 inches. If the package is rotated 90 degrees, you should swap the values for the height and width. The code below makes an attempt to swap the values stored in two variables h and w, which represent height and width. Variable h should end up with w’s initial value of 5 and w should get h’s initial value of 3. Unfortunately this code has an error and does not work. Use the CodeLens to step through the code to understand why it fails to swap the values in h and w.

1-4-7: Explain in your own words why the ErrorSwap program code does not swap the values stored in h and w.

Swapping two variables requires a third variable. Before assigning h = w , you need to store the original value of h in the temporary variable. In the mixed up programs below, drag the blocks to the right to put them in the right order.

The following has the correct code that uses a third variable named “temp” to swap the values in h and w.

The code is mixed up and contains one extra block which is not needed in a correct solution. Drag the needed blocks from the left into the correct order on the right, then check your solution. You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks.

After three incorrect attempts you will be able to use the Help Me button to make the problem easier.

Fix the code below to perform a correct swap of h and w. You need to add a new variable named temp to use for the swap.

1.4.2. Incrementing the value of a variable ¶

If you use a variable to keep score you would probably increment it (add one to the current value) whenever score should go up. You can do this by setting the variable to the current value of the variable plus one (score = score + 1) as shown below. The formula looks a little crazy in math class, but it makes sense in coding because the variable on the left is set to the value of the arithmetic expression on the right. So, the score variable is set to the previous value of score + 1.

Click on the Show CodeLens button to step through the code and see how the score value changes.

1-4-11: What is the value of b after the following code executes?

  • It sets the value for the variable on the left to the value from evaluating the right side. What is 5 * 2?
  • Correct. 5 * 2 is 10.

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

  • x = 0, y = 1, z = 2
  • These are the initial values in the variable, but the values are changed.
  • x = 1, y = 2, z = 3
  • x changes to y's initial value, y's value is doubled, and z is set to 3
  • x = 2, y = 2, z = 3
  • Remember that the equal sign doesn't mean that the two sides are equal. It sets the value for the variable on the left to the value from evaluating the right side.
  • x = 1, y = 0, z = 3

1.4.3. Operators ¶

Java uses the standard mathematical operators for addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). Arithmetic expressions can be of type int or double. An arithmetic operation that uses two int values will evaluate to an int value. An arithmetic operation that uses at least one double value will evaluate to a double value. (You may have noticed that + was also used to put text together in the input program above – more on this when we talk about strings.)

Java uses the operator == to test if the value on the left is equal to the value on the right and != to test if two items are not equal. Don’t get one equal sign = confused with two equal signs == ! They mean different things in Java. One equal sign is used to assign a value to a variable. Two equal signs are used to test a variable to see if it is a certain value and that returns true or false as you’ll see below. Use == and != only with int values and not doubles because double values are an approximation and 3.3333 will not equal 3.3334 even though they are very close.

Run the code below to see all the operators in action. Do all of those operators do what you expected? What about 2 / 3 ? Isn’t surprising that it prints 0 ? See the note below.

When Java sees you doing integer division (or any operation with integers) it assumes you want an integer result so it throws away anything after the decimal point in the answer, essentially rounding down the answer to a whole number. If you need a double answer, you should make at least one of the values in the expression a double like 2.0.

With division, another thing to watch out for is dividing by 0. An attempt to divide an integer by zero will result in an ArithmeticException error message. Try it in one of the active code windows above.

Operators can be used to create compound expressions with more than one operator. You can either use a literal value which is a fixed value like 2, or variables in them. When compound expressions are evaluated, operator precedence rules are used, so that *, /, and % are done before + and -. However, anything in parentheses is done first. It doesn’t hurt to put in extra parentheses if you are unsure as to what will be done first.

In the example below, try to guess what it will print out and then run it to see if you are right. Remember to consider operator precedence .

1-4-15: Consider the following code segment. Be careful about integer division.

What is printed when the code segment is executed?

  • 0.666666666666667
  • Don't forget that division and multiplication will be done first due to operator precedence.
  • Yes, this is equivalent to (5 + ((a/b)*c) - 1).
  • Don't forget that division and multiplication will be done first due to operator precedence, and that an int/int gives an int result where it is rounded down to the nearest int.

1-4-16: Consider the following code segment.

What is the value of the expression?

  • Dividing an integer by an integer results in an integer
  • Correct. Dividing an integer by an integer results in an integer
  • The value 5.5 will be rounded down to 5

1-4-17: Consider the following code segment.

  • Correct. Dividing a double by an integer results in a double
  • Dividing a double by an integer results in a double

1-4-18: Consider the following code segment.

  • Correct. Dividing an integer by an double results in a double
  • Dividing an integer by an double results in a double

1.4.4. The Modulo Operator ¶

The percent sign operator ( % ) is the mod (modulo) or remainder operator. The mod operator ( x % y ) returns the remainder after you divide x (first number) by y (second number) so 5 % 2 will return 1 since 2 goes into 5 two times with a remainder of 1. Remember long division when you had to specify how many times one number went into another evenly and the remainder? That remainder is what is returned by the modulo operator.

../_images/mod-py.png

Figure 2: Long division showing the whole number result and the remainder ¶

In the example below, try to guess what it will print out and then run it to see if you are right.

The result of x % y when x is smaller than y is always x . The value y can’t go into x at all (goes in 0 times), since x is smaller than y , so the result is just x . So if you see 2 % 3 the result is 2 .

1-4-21: What is the result of 158 % 10?

  • This would be the result of 158 divided by 10. modulo gives you the remainder.
  • modulo gives you the remainder after the division.
  • When you divide 158 by 10 you get a remainder of 8.

1-4-22: What is the result of 3 % 8?

  • 8 goes into 3 no times so the remainder is 3. The remainder of a smaller number divided by a larger number is always the smaller number!
  • This would be the remainder if the question was 8 % 3 but here we are asking for the reminder after we divide 3 by 8.
  • What is the remainder after you divide 3 by 8?

1.4.5. FlowCharting ¶

Assume you have 16 pieces of pizza and 5 people. If everyone gets the same number of slices, how many slices does each person get? Are there any leftover pieces?

In industry, a flowchart is used to describe a process through symbols and text. A flowchart usually does not show variable declarations, but it can show assignment statements (drawn as rectangle) and output statements (drawn as rhomboid).

The flowchart in figure 3 shows a process to compute the fair distribution of pizza slices among a number of people. The process relies on integer division to determine slices per person, and the mod operator to determine remaining slices.

Flow Chart

Figure 3: Example Flow Chart ¶

A flowchart shows pseudo-code, which is like Java but not exactly the same. Syntactic details like semi-colons are omitted, and input and output is described in abstract terms.

Complete the program based on the process shown in the Figure 3 flowchart. Note the first line of code declares all 4 variables as type int. Add assignment statements and print statements to compute and print the slices per person and leftover slices. Use System.out.println for output.

1.4.6. Storing User Input in Variables ¶

Variables are a powerful abstraction in programming because the same algorithm can be used with different input values saved in variables.

Program input and output

Figure 4: Program input and output ¶

A Java program can ask the user to type in one or more values. The Java class Scanner is used to read from the keyboard input stream, which is referenced by System.in . Normally the keyboard input is typed into a console window, but since this is running in a browser you will type in a small textbox window displayed below the code. The code below shows an example of prompting the user to enter a name and then printing a greeting. The code String name = scan.nextLine() gets the string value you enter as program input and then stores the value in a variable.

Run the program a few times, typing in a different name. The code works for any name: behold, the power of variables!

Run this program to read in a name from the input stream. You can type a different name in the input window shown below the code.

Try stepping through the code with the CodeLens tool to see how the name variable is assigned to the value read by the scanner. You will have to click “Hide CodeLens” and then “Show in CodeLens” to enter a different name for input.

The Scanner class has several useful methods for reading user input. A token is a sequence of characters separated by white space.

Run this program to read in an integer from the input stream. You can type a different integer value in the input window shown below the code.

A rhomboid (slanted rectangle) is used in a flowchart to depict data flowing into and out of a program. The previous flowchart in Figure 3 used a rhomboid to indicate program output. A rhomboid is also used to denote reading a value from the input stream.

Flow Chart

Figure 5: Flow Chart Reading User Input ¶

Figure 5 contains an updated version of the pizza calculator process. The first two steps have been altered to initialize the pizzaSlices and numPeople variables by reading two values from the input stream. In Java this will be done using a Scanner object and reading from System.in.

Complete the program based on the process shown in the Figure 5 flowchart. The program should scan two integer values to initialize pizzaSlices and numPeople. Run the program a few times to experiment with different values for input. What happens if you enter 0 for the number of people? The program will bomb due to division by zero! We will see how to prevent this in a later lesson.

The program below reads two integer values from the input stream and attempts to print the sum. Unfortunately there is a problem with the last line of code that prints the sum.

Run the program and look at the result. When the input is 5 and 7 , the output is Sum is 57 . Both of the + operators in the print statement are performing string concatenation. While the first + operator should perform string concatenation, the second + operator should perform addition. You can force the second + operator to perform addition by putting the arithmetic expression in parentheses ( num1 + num2 ) .

More information on using the Scanner class can be found here https://www.w3schools.com/java/java_user_input.asp

1.4.7. Programming Challenge : Dog Years ¶

In this programming challenge, you will calculate your age, and your pet’s age from your birthdates, and your pet’s age in dog years. In the code below, type in the current year, the year you were born, the year your dog or cat was born (if you don’t have one, make one up!) in the variables below. Then write formulas in assignment statements to calculate how old you are, how old your dog or cat is, and how old they are in dog years which is 7 times a human year. Finally, print it all out.

Calculate your age and your pet’s age from the birthdates, and then your pet’s age in dog years. If you want an extra challenge, try reading the values using a Scanner.

1.4.8. Summary ¶

Arithmetic expressions include expressions of type int and double.

The arithmetic operators consist of +, -, * , /, and % (modulo for the remainder in division).

An arithmetic operation that uses two int values will evaluate to an int value. With integer division, any decimal part in the result will be thrown away, essentially rounding down the answer to a whole number.

An arithmetic operation that uses at least one double value will evaluate to a double value.

Operators can be used to construct compound expressions.

During evaluation, operands are associated with operators according to operator precedence to determine how they are grouped. (*, /, % have precedence over + and -, unless parentheses are used to group those.)

An attempt to divide an integer by zero will result in an ArithmeticException to occur.

The assignment operator (=) allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left.

During execution, expressions are evaluated to produce a single value.

The value of an expression has a type based on the evaluation of the expression.

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.

Expressions, Statements, and Blocks

Now that you understand variables and operators, it's time to learn about expressions , statements , and blocks . Operators may be used in building expressions, which compute values; expressions are the core components of statements; statements may be grouped into blocks.

Expressions

An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. You've already seen examples of expressions, illustrated in bold below:

The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is an int . As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String .

The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here's an example of a compound expression:

In this particular example, the order in which the expression is evaluated is unimportant because the result of multiplication is independent of order; the outcome is always the same, no matter in which order you apply the multiplications. However, this is not true of all expressions. For example, the following expression gives different results, depending on whether you perform the addition or the division operation first:

You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ). For example, to make the previous expression unambiguous, you could write the following:

If you don't explicitly indicate the order for the operations to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators that have a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Therefore, the following two statements are equivalent:

When writing compound expressions, be explicit and indicate with parentheses which operators should be evaluated first. This practice makes code easier to read and to maintain.

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon ( ; ).

  • Assignment expressions
  • Any use of ++ or --
  • Method invocations
  • Object creation expressions

Such statements are called expression statements . Here are some examples of expression statements.

In addition to expression statements, there are two other kinds of statements: declaration statements and control flow statements . A declaration statement declares a variable. You've seen many examples of declaration statements already:

Finally, control flow statements regulate the order in which statements get executed. You'll learn about control flow statements in the next section, Control Flow Statements

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example, BlockDemo , illustrates the use of blocks:

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

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

Live Training, Prepare for Interviews, and Get Hired

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.

Java Assignment Operators

Java programming tutorial index.

The Java Assignment Operators are used when you want to assign a value to the expression. The assignment operator denoted by the single equal sign = .

In a Java assignment statement, any expression can be on the right side and the left side must be a variable name. For example, this does not mean that "a" is equal to "b", instead, it means assigning the value of 'b' to 'a'. It is as follows:

Java also has the facility of chain assignment operators, where we can specify a single value for multiple variables.

  • 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

  • Basics of Java
  • ➤ Java Introduction
  • ➤ History of Java
  • ➤ Getting started with Java
  • ➤ What is Path and Classpath
  • ➤ Checking Java installation and Version
  • ➤ Syntax in Java
  • ➤ My First Java Program
  • ➤ Basic terms in Java Program
  • ➤ Runtime and Compile time
  • ➤ What is Bytecode
  • ➤ Features of Java
  • ➤ What is JDK JRE and JVM
  • ➤ Basic Program Examples
  • Variables and Data Types
  • ➤ What is Variable
  • ➤ Types of Java Variables
  • ➤ Naming conventions for Identifiers
  • ➤ Data Type in Java
  • ➤ Mathematical operators in Java
  • ➤ Assignment operator in Java
  • ➤ Arithmetic operators in Java
  • ➤ Unary operators in Java
  • ➤ Conditional and Relational Operators
  • ➤ Bitwise and Bit Shift Operators
  • ➤ Operator Precedence
  • ➤ Overflow Underflow Widening Narrowing
  • ➤ Variable and Data Type Programs
  • Control flow Statements
  • ➤ Java if and if else Statement
  • ➤ else if and nested if else Statement
  • ➤ Java for Loop
  • ➤ Java while and do-while Loop
  • ➤ Nested loops
  • ➤ Java break Statement
  • ➤ Java continue and return Statement
  • ➤ Java switch Statement
  • ➤ Control Flow Program Examples
  • Array and String in Java
  • ➤ Array in Java
  • ➤ Multi-Dimensional Arrays
  • ➤ for-each loop in java
  • ➤ Java String
  • ➤ Useful Methods of String Class
  • ➤ StringBuffer and StringBuilder
  • ➤ Array and String Program Examples
  • Classes and Objects
  • ➤ Classes in Java
  • ➤ Objects in Java
  • ➤ Methods in Java
  • ➤ Constructors in Java
  • ➤ static keyword in Java
  • ➤ Call By Value
  • ➤ Inner/nested classes in Java
  • ➤ Wrapper Classes
  • ➤ Enum in Java
  • ➤ Initializer blocks
  • ➤ Method Chaining and Recursion
  • Packages and Interfaces
  • ➤ What is package
  • ➤ Sub packages in java
  • ➤ built-in packages in java
  • ➤ Import packages
  • ➤ Access modifiers
  • ➤ Interfaces in Java
  • ➤ Key points about Interfaces
  • ➤ New features in Interfaces
  • ➤ Nested Interfaces
  • ➤ Structure of Java Program
  • OOPS Concepts
  • ➤ What is OOPS
  • ➤ Inheritance in Java
  • ➤ Inheritance types in Java
  • ➤ Abstraction in Java
  • ➤ Encapsulation in Java
  • ➤ Polymorphism in Java
  • ➤ Runtime and Compile-time Polymorphism
  • ➤ Method Overloading
  • ➤ Method Overriding
  • ➤ Overloading and Overriding Differences
  • ➤ Overriding using Covariant Return Type
  • ➤ this keyword in Java
  • ➤ super keyword in Java
  • ➤ final keyword in Java

Assignment Operator in Java with Example

Assignment operator is one of the simplest and most used operator in java programming language. As the name itself suggests, the assignment operator is used to assign value inside a variable. In java we can divide assignment operator in two types :

  • Assignment operator or simple assignment operator
  • Compound assignment operators

What is assignment operator in java

The = operator in java is known as assignment or simple assignment operator. It assigns the value on its right side to the operand(variable) on its left side. For example :

The left-hand side of an assignment operator must be a variable while the right side of it should be a value which can be in the form of a constant value, a variable name, an expression, a method call returning a compatible value or a combination of these.

The value at right side of assignment operator must be compatible with the data type of left side variable, otherwise compiler will throw compilation error. Following are incorrect assignment :

Another important thing about assignment operator is that, it is evaluated from right to left . If there is an expression at right side of assignment operator, it is evaluated first then the resulted value is assigned in left side variable.

Here in statement int x = a + b + c; the expression a + b + c is evaluated first, then the resulted value( 60 ) is assigned into x . Similarly in statement a = b = c , first the value of c which is 30 is assigned into b and then the value of b which is now 30 is assigned into a .

The variable at left side of an assignment operator can also be a non-primitive variable. For example if we have a class MyFirstProgram , we can assign object of MyFirstProgram class using = operator in MyFirstProgram type variable.

Is == an assignment operator ?

No , it's not an assignment operator, it's a relational operator used to compare two values.

Is assignment operator a binary operator

Yes , as it requires two operands.

Assignment operator program in Java

a = 2 b = 2 c = 4 d = 4 e = false

Java compound assignment operators

The assignment operator can be mixed or compound with other operators like addition, subtraction, multiplication etc. We call such assignment operators as compound assignment operator. For example :

Here the statement a += 10; is the short version of a = a + 10; the operator += is basically addition compound assignment operator. Similarly b *= 5; is short version of b = b * 5; the operator *= is multiplication compound assignment operator. The compound assignment can be in more complex form as well, like below :

List of all assignment operators in Java

The table below shows the list of all possible assignment(simple and compound) operators in java. Consider a is an integer variable for this table.

How many assignment operators are there in Java ?

Including simple and compound assignment we have total 12 assignment operators in java as given in above table.

What is shorthand operator in Java ?

Shorthand operators are nothing new they are just a shorter way to write something that is already available in java language. For example the code a += 5 is shorter way to write a = a + 5 , so += is a shorthand operator. In java all the compound assignment operator(given above) and the increment/decrement operators are basically shorthand operators.

Compound assignment operator program in Java

a = 20 b = 80 c = 30 s = 64 s2 = 110 b2 = 15

What is the difference between += and =+ in Java?

An expression a += 1 will result as a = a + 1 while the expression a =+ 1 will result as a = +1 . The correct compound statement is += , not =+ , so do not use the later one.

facebook page

  • Watch & Listen
  • Oracle University

Previous in the Series: Summary of Operators

Next in the Series: Control Flow Statements

Expressions, Statements and Blocks

Expressions.

An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. You have already seen examples of expressions, illustrated in code below:

The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is an int . As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String .

The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here is an example of a compound expression:

In this particular example, the order in which the expression is evaluated is unimportant because the result of multiplication is independent of order; the outcome is always the same, no matter in which order you apply the multiplications. However, this is not true of all expressions. For example, the following expression gives different results, depending on whether you perform the addition or the division operation first:

You can specify exactly how an expression will be evaluated using balanced parenthesis: ( and ) . For example, to make the previous expression unambiguous, you could write the following:

If you don't explicitly indicate the order for the operations to be performed, the order is determined by the precedence assigned to the operators in use within the expression. Operators that have a higher precedence get evaluated first. For example, the division operator has a higher precedence than does the addition operator. Therefore, the following two statements are equivalent:

When writing compound expressions, be explicit and indicate with parentheses which operators should be evaluated first. This practice makes code easier to read and to maintain.

Floating Point Arithmetic

Floating point arithmetic is a special world in which common operations may behave unexpectedly. Consider the following code.

You would probably expect that it prints true . Due to the way floating point addition is conducted and rounded, it prints false .

Presenting how floating point arithmetic is implemented in Java is beyond the scope of this tutorial. If you need to learn more on this topic, you may watch the following vide.

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon ( ; ).

  • Assignment expressions
  • Any use of ++ or --
  • Method invocations
  • Object creation expressions
  • Such statements are called expression statements. Here are some examples of expression statements.

In addition to expression statements, there are two other kinds of statements: declaration statements and control flow statements. A declaration statement declares a variable. You have seen many examples of declaration statements already:

Finally, control flow statements regulate the order in which statements get executed. You will learn about control flow statements in the next section, Control Flow Statements.

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following example, BlockDemo , illustrates the use of blocks:

In this tutorial

Last update: September 22, 2021

  • All Articles List
  • 10 April 2023

Java Expressions: An Introduction with Examples

What is expression in java, types of expressions in java.

  • Arithmetic expressions : These expressions involve arithmetic operations such as addition, subtraction, multiplication, and division. For example, 2+3 is an arithmetic expression that evaluates to 5.
  • Relational expressions : These expressions involve comparing two values using relational operators such as "greater than," "less than," "equal to," and "not equal to." For example, 4<5 is a relational expression that evaluates to true.
  • Logical expressions : These expressions involve logical operations such as "AND," "OR," and "NOT." For example, (2<3)&&(3<4) is a logical expression that evaluates to true.
  • Conditional expressions : These expressions involve using the ternary operator "?:" to assign a value based on a condition. For example, int x = (5<6)?2:3; assigns the value 2 to x since 5 is less than 6.
  • Assignment expressions : These expressions involve assigning a value to a variable. For example, int x = 5; assigns the value 5 to the variable x.

Example of Expression Statement

Examples of java expressions, arithmetic expression:, relational expression:, logical expression:, conditional expression:, assignment expression:.

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

Javatpoint Logo

Java Tutorial

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

JavaTpoint

  • 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

IMAGES

  1. The Assignment Operator in Java

    assignment expression in java

  2. Java Assignment Operators

    assignment expression in java

  3. Assignment Operators in Java

    assignment expression in java

  4. 1.4. Expressions and Assignment Statements

    assignment expression in java

  5. Assignment operator in Java

    assignment expression in java

  6. Assignment operator in Java

    assignment expression in java

VIDEO

  1. Operators and Expressions

  2. #20. Assignment Operators in Java

  3. Core

  4. Python 的指派運算式 #pydoing #python #assignment_expression

  5. Functionalities of Lambda Expression| Java developer| SDET java

  6. Java tutorial in Hindi for beginners #15 Assignment Operators

COMMENTS

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

  2. 1.7 Java

    An assignment statement designates a value for a variable. An assignment statement can be used as an expression in Java. After a variable is declared, you can assign a value to it by using an assignment statement. In Java, the equal sign = is used as the assignment operator. The syntax for assignment statements is as follows: variable ...

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

    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:

  4. 1.4. Expressions and Assignment Statements

    In this lesson, you will learn about assignment statements and expressions that contain math operators and variables. 1.4.1. Assignment Statements ¶. Remember that a variable holds a value that can change or vary. Assignment statements initialize or change the value stored in a variable using the assignment operator =.

  5. What does an assignment expression evaluate to in Java?

    The assignment operator in Java evaluates to the assigned value (like it does in, e.g., c ). So here, readLine() will be executed, and its return value stored in line. That stored value is then checked against null, and if it's null then the loop will terminate. edited Jun 3, 2021 at 14:55. Michael. 43.1k 11 89 137. answered Jul 2, 2016 at 19:56.

  6. Expressions, Statements, and Blocks (The Java™ Tutorials

    The data type of the value returned by an expression depends on the elements used in the expression. The expression cadence = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, cadence is an int.As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String.

  7. All Java Assignment Operators (Explained With Examples)

    The assignment operator (=) is used to assign the value of the expression on the right-hand side to the variable on the left-hand side. Types of Assignment Operators in Java There are mainly two types of assignment operators in Java, which are as follows:

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

  9. Java Assignment Operators

    The Java Assignment Operators are used when you want to assign a value to the expression. ... In a Java assignment statement, any expression can be on the right side and the left side must be a variable name. For example, this does not mean that "a" is equal to "b", instead, it means assigning the value of 'b' to 'a'. ...

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

  11. Assignment Operator in Java with Example

    The = operator in java is known as assignment or simple assignment operator. It assigns the value on its right side to the operand (variable) on its left side. For example : int a = 10; // value 10 is assigned in variable a double d = 20.25; // value 20.25 is assigned in variable d char c = 'A'; // Character A is assigned in variable c. a = 20 ...

  12. Java Operators

    However, the expression ... Next, let's see which assignment operators we can use in Java. 9.1. The Simple Assignment Operator. The simple assignment operator (=) is a straightforward but important operator in Java. Actually, we've used it many times in previous examples. It assigns the value on its right to the operand on its left:

  13. Expressions, Statements and Blocks

    The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. Here is an example of a compound expression: ... Assignment expressions; Any use of ++ or --Method invocations;

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

  15. Java Expressions: Types, Evaluation of Expression, Examples

    Learn about Java expressions, types, evaluations, and examples in this tutorial. Understand how to work with expressions in Java. ... Assignment expressions are used to assign values to variables. Example: int x = 10; Explanation: This example is a simple assignment expression that assigns the value 10 to the variable x. 5. Method Call Expressions

  16. Java Expressions: An Introduction with Examples

    In Java, an expression is a combination of values, variables, operators, and method invocations that are evaluated to produce a single value. An expression can be a single value or a combination of values that produce a result. Expressions can be used in various contexts, such as in assignments, conditional statements, and loops.

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

  18. Definite Assignment in Java

    The definite assignment will consider the structure of expressions and statements. The Java compiler will decide that "k" is assigned before its access, like an argument with the method invocation in the code. It is because the access will occur if the value of the expression is accurate.

  19. java

    This is an expression, but not a statement; hence the complaint. If you want to examine the contents of nums , you can do something like: System.out.println(Arrays.toString(nums));

  20. java

    @Peter, try googling for insert assignment operator expression to complete expression I always remove all punctuation characters to be sure it's no "special" search. Google will favour results in which the words come close to each other anyway. I also, Remove Capitalization Etc... I've read (a long time ago) that if you use mixed case, google assumes you know for sure how the case should be.