• 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
  • How to Organize Your Digital Files with Cloud Storage and Automation
  • 10 Best Blender Alternatives for 3D Modeling in 2024
  • How to Transfer Photos From iPhone to iPhone
  • What are Tiktok AI Avatars?
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Java Tutorial

Java methods, java classes, java file handling, java how to, java reference, java examples, java operators.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Try it Yourself »

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

Java divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Advertisement

Java Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Java Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either true or false . These values are known as Boolean values , and you will learn more about them in the Booleans and If..Else chapter.

In the following example, we use the greater than operator ( > ) to find out if 5 is greater than 3:

Java Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values:

Java Bitwise Operators

Bitwise operators are used to perform binary logic with the bits of an integer or long integer.

Note: The Bitwise examples above use 4-bit unsigned examples, but Java uses 32-bit signed integers and 64-bit signed long integers. Because of this, in Java, ~5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010

In Java, 9 >> 1 will not return 12. It will return 4. 00000000000000000000000000001001 >> 1 will return 00000000000000000000000000000100

Test Yourself With Exercises

Multiply 10 with 5 , and print the result.

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Java Hello World
  • Java JVM, JRE and JDK
  • Java Variables and Literals
  • Java Data Types

Java Operators

  • Java Input and Output
  • Java Expressions & Blocks
  • Java Comment

Java Flow Control

  • Java if...else
  • Java switch Statement
  • Java for Loop
  • Java for-each Loop
  • Java while Loop
  • Java break Statement
  • Java continue Statement
  • Java Arrays
  • Multidimensional Array
  • Java Copy Array

Java OOP (I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructor
  • Java Strings
  • Java Access Modifiers
  • Java this keyword
  • Java final keyword
  • Java Recursion

Java instanceof Operator

Java OOP (II)

  • Java Inheritance
  • Java Method Overriding
  • Java super Keyword
  • Abstract Class & Method
  • Java Interfaces
  • Java Polymorphism
  • Java Encapsulation

Java OOP (III)

  • Nested & Inner Class
  • Java Static Class
  • Java Anonymous Class
  • Java Singleton
  • Java enum Class
  • Java enum Constructor
  • Java enum String
  • Java Reflection
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java List Interface
  • Java ArrayList
  • Java Vector
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue Interface
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet
  • Java EnumSet
  • Java LinkedhashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator
  • Java ListIterator
  • Java I/O Streams
  • Java InputStream
  • Java OutputStream
  • Java FileInputStream
  • Java FileOutputStream
  • Java ByteArrayInputStream
  • Java ByteArrayOutputStream
  • Java ObjectInputStream
  • Java ObjectOutputStream
  • Java BufferedInputStream
  • Java BufferedOutputStream
  • Java PrintStream

Java Reader/Writer

  • Java Reader
  • Java Writer
  • Java InputStreamReader
  • Java OutputStreamWriter
  • Java FileReader
  • Java FileWriter
  • Java BufferedReader
  • Java BufferedWriter
  • Java StringReader
  • Java StringWriter
  • Java PrintWriter

Additional Topics

  • Java Scanner Class
  • Java Type Casting
  • Java autoboxing and unboxing
  • Java Lambda Expression
  • Java Generics
  • Java File Class
  • Java Wrapper Class
  • Java Command Line Arguments

Java Tutorials

Java Operator Precedence

Java Ternary Operator

Java Bitwise and Shift Operators

  • Java if...else Statement
  • Java Math IEEEremainder()

Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while * is also an operator used for multiplication.

Operators in Java can be classified into 5 types:

  • Arithmetic Operators
  • Assignment Operators
  • Relational Operators
  • Logical Operators
  • Unary Operators
  • Bitwise Operators

1. Java Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables and data. For example,

Here, the + operator is used to add two variables a and b . Similarly, there are various other arithmetic operators in Java.

Example 1: Arithmetic Operators

In the above example, we have used + , - , and * operators to compute addition, subtraction, and multiplication operations.

/ Division Operator

Note the operation, a / b in our program. The / operator is the division operator.

If we use the division operator with two integers, then the resulting quotient will also be an integer. And, if one of the operands is a floating-point number, we will get the result will also be in floating-point.

% Modulo Operator

The modulo operator % computes the remainder. When a = 7 is divided by b = 4 , the remainder is 3 .

Note : The % operator is mainly used with integers.

2. Java Assignment Operators

Assignment operators are used in Java to assign values to variables. For example,

Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is assigned to the variable age .

Let's see some more assignment operators available in Java.

Example 2: Assignment Operators

3. java relational operators.

Relational operators are used to check the relationship between two operands. For example,

Here, < operator is the relational operator. It checks if a is less than b or not.

It returns either true or false .

Example 3: Relational Operators

Note : Relational operators are used in decision making and loops.

4. Java Logical Operators

Logical operators are used to check whether an expression is true or false . They are used in decision making.

Example 4: Logical Operators

Working of Program

  • (5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true .
  • (5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false .
  • (5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true .
  • (5 > 3) || (8 < 5) returns true because the expression (5 > 3) is true .
  • (5 < 3) || (8 < 5) returns false because both (5 < 3) and (8 < 5) are false .
  • !(5 == 3) returns true because 5 == 3 is false .
  • !(5 > 3) returns false because 5 > 3 is true .

5. Java Unary Operators

Unary operators are used with only one operand. For example, ++ is a unary operator that increases the value of a variable by 1 . That is, ++5 will return 6 .

Different types of unary operators are:

  • Increment and Decrement Operators

Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the value of the operand by 1 , while -- decrease it by 1 . For example,

Here, the value of num gets increased to 6 from its initial value of 5 .

Example 5: Increment and Decrement Operators

In the above program, we have used the ++ and -- operator as prefixes (++a, --b) . We can also use these operators as postfix (a++, b++) .

There is a slight difference when these operators are used as prefix versus when they are used as a postfix.

To learn more about these operators, visit increment and decrement operators .

6. Java Bitwise Operators

Bitwise operators in Java are used to perform operations on individual bits. For example,

Here, ~ is a bitwise operator. It inverts the value of each bit ( 0 to 1 and 1 to 0 ).

The various bitwise operators present in Java are:

These operators are not generally used in Java. To learn more, visit Java Bitwise and Bit Shift Operators .

Other operators

Besides these operators, there are other additional operators in Java.

The instanceof operator checks whether an object is an instanceof a particular class. For example,

Here, str is an instance of the String class. Hence, the instanceof operator returns true . To learn more, visit Java instanceof .

The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example,

Here's how it works.

  • If the Expression is true , expression1 is assigned to the variable .
  • If the Expression is false , expression2 is assigned to the variable .

Let's see an example of a ternary operator.

In the above example, we have used the ternary operator to check if the year is a leap year or not. To learn more, visit the Java ternary operator .

Now that you know about Java operators, it's time to know about the order in which operators are evaluated. To learn more, visit Java Operator Precedence .

Table of Contents

  • Introduction
  • Java Arithmetic Operators
  • Java Assignment Operators
  • Java Relational Operators
  • Java Logical Operators
  • Java Unary Operators
  • Java Bitwise Operators

Sorry about that.

Related Tutorials

Java Tutorial

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

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
  • 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
  • What are Copy Constructors In Java? Explore Types,Examples & Use
  • What is a Bitwise Operator in Java? Type, Example and More
  • Constructor Overloading in Java
  • Ternary Operator in Java
  • For Loop in Java: Its Types and Examples
  • 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
  • What is Class in Java? - Objects and Classes in Java {Explained}
  • Access Modifiers in Java: Default, Private, Public, Protected
  • Constructors in Java: Types of Constructors with Examples
  • Polymorphism in Java: Compile time and Runtime Polymorphism
  • Abstract Class 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 Tutorial

  • Java - Home
  • Java - Overview
  • Java - History
  • Java - Features
  • Java 8 - New Features
  • Java vs C++
  • Java Virtual Machine(JVM)
  • Java - JDK vs JRE vs JVM
  • Java - Hello World Program
  • Java - Environment Setup
  • Java - Basic Syntax
  • Java - Variable Types
  • Java - Data Types
  • Java - Type Casting
  • Java - Unicode System
  • Java - Basic Operators
  • Java - Comments
  • Java - Streams
  • Java - Datetime Api
  • Java - User Input
  • Java - Loop Control
  • Java - Decision Making
  • Java - If-else
  • Java - Switch
  • Java - For Loops
  • Java - For-Each Loops
  • Java - While Loops
  • Java - do-while Loops
  • Java - Break
  • Java - Continue
  • Java - OOPs Concepts
  • Java - Object & Classes
  • Java - Class Attributes
  • Java - Class Methods
  • Java - Methods
  • Java - Variables Scope
  • Java - Constructors
  • Java - Access Modifiers
  • Java - Inheritance
  • Java - Aggregation
  • Java - Polymorphism
  • Java - Overriding
  • Java - Method Overloading
  • Java - Dynamic Binding
  • Java - Static Binding
  • Java - Instance Initializer Block
  • Java - Abstraction
  • Java - Encapsulation
  • Java - Interfaces
  • Java - Packages
  • Java - Inner Classes
  • Java - Static Class
  • Java - Anonymous Class
  • Java - Singleton Class
  • Java - Wrapper Classes
  • Java - Enums
  • Java - Enum Constructor
  • Java - Enum Strings
  • Java - Reflection
  • Java - Number
  • Java - Boolean
  • Java - Characters
  • Java - Strings
  • Java - Arrays
  • Java - Date & Time
  • Java - Math Class
  • Java - Files
  • Java - Create a File
  • Java - Write to File
  • Java - Read Files
  • Java - Delete Files
  • Java - Directories
  • Java - I/O Streams
  • Java - Exceptions
  • Java - try-catch Block
  • Java - try-with-resources
  • Java - Multi-catch Block
  • Java - Nested try Block
  • Java - Finally Block
  • Java - throw Exception
  • Java - Exception Propagation
  • Java - Built-in Exceptions
  • Java - Custom Exception
  • Java - Annotations
  • Java - Logging
  • Java - Assertions
  • Java - Multithreading
  • Java - Thread Life Cycle
  • Java - Creating a Thread
  • Java - Starting a Thread
  • Java - Joining Threads
  • Java - Naming Thread
  • Java - Thread Scheduler
  • Java - Thread Pools
  • Java - Main Thread
  • Java - Thread Priority
  • Java - Daemon Threads
  • Java - Thread Group
  • Java - Shutdown Hook
  • Java - Synchronization
  • Java - Block Synchronization
  • Java - Static Synchronization
  • Java - Inter-thread Communication
  • Java - Thread Deadlock
  • Java - Interrupting a Thread
  • Java - Thread Control
  • Java - Reentrant Monitor
  • Java - Networking
  • Java - Socket Programming
  • Java - URL Processing
  • Java - URL Class
  • Java - URLConnection Class
  • Java - HttpURLConnection Class
  • Java - Socket Class
  • Java - ServerSocket Class
  • Java - InetAddress Class
  • Java - Generics
  • Java - Collections
  • Java - Collection Interface
  • Java - List Interface
  • Java - ArrayList
  • Java - Vector Class
  • Java - Stack Class
  • Java - Queue Interface
  • Java - PriorityQueue
  • Java - Deque Interface
  • Java - LinkedList
  • Java - ArrayDeque
  • Java - Map Interface
  • Java - HashMap
  • Java - LinkedHashMap
  • Java - WeakHashMap
  • Java - EnumMap
  • Java - SortedMap Interface
  • Java - TreeMap
  • Java - The IdentityHashMap Class
  • Java - Set Interface
  • Java - HashSet
  • Java - EnumSet
  • Java - LinkedHashSet
  • Java - SortedSet Interface
  • Java - TreeSet
  • Java - Data Structures
  • Java - Enumeration
  • Java - BitSet Class
  • Java - Dictionary
  • Java - Hashtable
  • Java - Properties
  • Java - Collections Algorithms
  • Java - Iterators
  • Java - Comparators
  • Java - Comparable Interface in Java
  • Java - Recursion
  • Java - Regular Expressions
  • Java - Serialization
  • Java - Maths Methods
  • Java - Array Methods
  • Java - Keywords Reference
  • Java - Command-Line Arguments
  • Java - Lambda Expressions
  • Java - Sending Email
  • Java - Applet Basics
  • Java - Javadoc Comments
  • Java - Autoboxing and Unboxing
  • Java - File Mismatch Method
  • Java - REPL (JShell)
  • Java - Multi-Release Jar Files
  • Java - Private Interface Methods
  • Java - Inner Class Diamond Operator
  • Java - Multiresolution Image API
  • Java - Collection Factory Methods
  • Java - Module System
  • Java - Nashorn JavaScript
  • Java - Optional Class
  • Java - Method References
  • Java - Functional Interfaces
  • Java - Default Methods
  • Java - Base64 Encode Decode
  • Java - Switch Expressions
  • Java - Teeing Collectors
  • Java - Microbenchmark
  • Java - Text Blocks
  • Java - Dynamic CDS archive
  • Java - Z Garbage Collector (ZGC)
  • Java - Null Pointer Exception
  • Java - Packaging Tools
  • Java - NUMA Aware G1
  • Java - Sealed Classes
  • Java - Record Classes
  • Java - Hidden Classes
  • Java - Pattern Matching
  • Java - Compact Number Formatting
  • Java - Programming Examples
  • JDBC Tutorial
  • SWING Tutorial
  • AWT Tutorial
  • Servlets Tutorial
  • JSP Tutorial
  • Java Compiler
  • Java - Questions and Answers
  • Java 8 - Questions and Answers
  • Java - Quick Guide
  • Java - Useful Resources
  • Java - Discussion
  • Java - Examples
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Java - Assignment Operators with Examples

Java assignment operators.

Following are the assignment operators supported by Java language −

The following programs are simple examples which demonstrate the assignment operators. Copy and paste the following Java programs as Test.java file, and compile and run the programs −

In this example, we're creating three variables a,b and c and using assignment operators . We've performed simple assignment, addition AND assignment, subtraction AND assignment and multiplication AND assignment operations and printed the results.

In this example, we're creating two variables a and c and using assignment operators . We've performed Divide AND assignment, Multiply AND assignment, Modulus AND assignment, bitwise exclusive OR AND assignment, OR AND assignment operations and printed the results.

In this example, we're creating two variables a and c and using assignment operators . We've performed Left shift AND assignment, Right shift AND assignment, operations and printed the results.

Exploring Operators in Java 101: A Comprehensive Guide to Mastering Java’s Fundamental Building Blocks

You are currently viewing Exploring Operators in Java 101: A Comprehensive Guide to Mastering Java’s Fundamental Building Blocks

  • Post author: Piyush
  • Post published: 31 August 2023
  • Post category: Java
  • Post comments: 0 Comments

I. Introduction to Operators in Java

Operators in java are essential components in programming languages. They serve as the building blocks of various operations and calculations. In Java, operators are crucial for performing tasks such as arithmetic operations, comparison of values, logical evaluations, and bit manipulations. By understanding and mastering operators, Java developers can write efficient and powerful code.

Contents of Operators in Java

Ii. arithmetic operators.

Arithmetic operators in Java allow for basic mathematical operations. These operators include addition (+), subtraction (-), multiplication (*), and division (/). Understanding the order of execution and precedence is crucial to accurately perform calculations involving multiple operators. Java also provides the modulus operator (%) which calculates the remainder of a division operation. Additionally, the increment (++) and decrement (–) operators are used to increase or decrease values by one. It is important to comprehend operator precedence and associativity to ensure correct execution of mathematical expressions involving multiple operators.

III. Relational Operators

Relational operators in Java are used to compare values ​​and determine relationships between values. Equality and inequality operators, represented by == and != respectively, allow for the comparison of equality or inequality between two operands. Comparison operators such as <, >, <=, and >= enable the evaluation of greater than, less than, greater than or equal, and less than or equal relationships respectively. Relational operators return boolean results, which are commonly used in conditional statements to determine the flow of the program. Furthermore, these operators can also be used for string comparisons, providing flexibility for string handling in Java.

IV. Logical Operators

Logical operators in Java are fundamental in decision-making and logical evaluations. The logical (&&) AND operator returns true only if both operands are true. Similarly, the logical OR operator (||) returns true if at least one of the operands is true. The logical (!) NOT operator negates the value of its operand. These operators are commonly used to combine multiple conditions and control program flow based on the outcomes. Java’s logical operators also support short-circuit evaluation, which allows for efficient execution by evaluating operands only when necessary.

V. Bitwise Operators

Bitwise operators in Java manipulate individual bits within binary representations of data. These operators include bitwise (&) AND, bitwise (|) OR, bitwise (^) XOR, and bitwise (~) NOT. They are useful in low-level programming, dealing with hardware interactions, and efficient data manipulation. Understanding the bitwise operators and their practical applications are essential for programmers working on tasks that involve bit-level calculations or data compression techniques.

VI. Assignment Operators

Assignment operators in Java are used to assign values to variables. The basic assignment operator (=) assigns the value on the right-hand side to the variable on the left-hand side. In addition to the basic operator, Java provides compound assignment operators such as +=, -=, *=, /=, and %= which combine arithmetic operations and assignment in a concise manner. These shortcut operators enhance code readability and reduce the need for repetitive code blocks when performing multiple calculations on the same variable.

VII. Conditional Operator (Ternary Operator)

The conditional operator (also known as the ternary operator) in Java provides a concise alternative to if-else statements. Its syntax is in the form of condition ? expression1 : expression2. The condition is evaluated, and if it is true, expression1 is executed; otherwise, expression2 is executed. Proper usage of the conditional operator can result in more concise and readable code, especially when dealing with simple conditional assignments or calculations.

VIII. Instanceof Operator

In Java, instanceof operator is used to check the type of an object at runtime. It returns true if the given object is an instance of the specified type or any of its subclasses. This operator is particularly useful when working with polymorphism and class hierarchies. It helps ensure type compatibility, enabling developers to effectively handle type conversions and implement appropriate logic based on the object’s actual type.

IX. Bit Shift Operators

Bit shift operators in Java are used to shift the bits of a value either to the left or to the right. The left shift operator (<<) moves the bits to the left, effectively multiplying the value by 2 for each shift. The right shift operator (>>) moves the bits to the right, effectively dividing the value by 2 for each shift. Java also provides the logical right shift operator (>>>), which fills the leftmost bits with zeroes. Bit shifting is commonly used in tasks involving binary data manipulation, creating efficient algorithms, and implementing encryption techniques.

what are the assignment operators in java

X. Operator Precedence and Associativity

In Java, operator precedence and associativity determine the order in which operators are evaluated. It is crucial to understand these concepts to avoid unexpected behaviors and to write code that accurately reflects the intended logic. Java follows specific rules for operator precedence and associativity, which developers should be familiar with. Additionally, having a quick-reference table of operator precedence can be immensely helpful during code development and debugging processes.

XI. Operator Overloading

Operator overloading is a feature in some programming languages that allows operators to behave differently based on the types of operands. However, this feature is not supported in Java. Unlike languages such as C++, Java does not allow developers to define new meanings for operators or extend their behavior beyond their predefined functionality. This constraint encourages developers to rely on established conventions and alternative design patterns for achieving the desired functionality.

XII. Operator Conventions and Best Practices

Adhering to established conventions and best practices in writing Java code helps improve readability and maintainability. When using operators, it is essential to follow established conventions such as proper indentation, consistent spacing, and the use of parentheses to clarify the order of operations. Code should be written in a way that promotes clarity and avoids unnecessary complexity or side effects. By maintaining a consistent and readable coding style, collaboration and further development become easier tasks.

XIII. Common Operator Pitfalls and Errors

Working with operators in Java can sometimes lead to pitfalls and errors if not handled carefully. Understanding and anticipating common mistakes can help developers avoid these issues. Some common pitfalls include operator precedence mistakes, incorrectly using logical operators, or misunderstanding the behavior of specific operators. When encountering operator-related errors, developers should leverage debugging techniques and use error handling strategies to identify and resolve issues effectively.

XIV: Performance Considerations and Optimizations

The choice of operators in Java can have performance implications. Understanding the performance characteristics of different operators is vital for writing efficient code. By analyzing how specific operators interact with the underlying hardware and optimizing code accordingly, developers can significantly improve program performance. However, it is crucial to strike a balance between code readability and performance trade-offs. Careful consideration should be given to optimizing critical sections of the code while maintaining overall code quality.

XV. Advanced Operator Techniques

As developers gain mastery over operators, they can explore advanced techniques that combine operators intelligently to perform complex operations. By creatively leveraging bitwise operators, for example, developers can achieve specific needs such as implementing custom data structures, optimizing memory usage, and creating efficient algorithms. Advanced examples showcasing the versatility of operators provide valuable insights into harnessing the full potential of operators in Java.

XVI. Summary and Key Takeaways

In summary, operators are fundamental building blocks in Java programming. They serve various purposes, including arithmetic calculations, comparison of values, logical evaluations, and bit manipulations. Understanding and mastering operators is crucial for efficient development and accurate execution of code. By applying the knowledge gained from this comprehensive guide, developers can confidently work with operators and leverage their power for writing high-quality Java code.

  • Operators in Java are symbols that represent actions or computations. They can perform functions such as arithmetic calculations, value comparisons, logical evaluations, and bit manipulations.
  • Java has various types of operators, including arithmetic operators, relational operators, logical operators, bitwise operators, assignment operators, the conditional operator, the instanceof operator, and the bit shift operators.
  • Operators in Java have different levels of precedence, which determine the order in which they are evaluated. Parentheses can be used to override the default precedence and control the order of execution.
  • No, you cannot overload operators in Java. Unlike some programming languages, Java does not allow developers to redefine the behavior of operators or create new operator meanings.
  • Common pitfalls when using operators in Java include incorrect operator precedence, misuse of logical operators, and misunderstanding specific operator behaviors. These issues can be avoided through careful understanding and following established best practices.

XVIII. Conclusion

Operators play a vital role in Java programming, serving as the fundamental building blocks for various operations and calculations. Through this comprehensive guide, readers have gained insights into different types of operators, their functionalities, and best practices for utilizing them effectively. Mastering operators empowers Java developers to write efficient and powerful code, paving the way for efficient development and successful software projects. It is essential to continue exploring operators, experimenting with different techniques, and practicing their usage to continually enhance programming skills and deliver high-quality Java applications.

Please Share This Share this content

  • Opens in a new window

You Might Also Like

Read more about the article Leap Year Program in Java 101: A Comprehensive Tutorial

Leap Year Program in Java 101: A Comprehensive Tutorial

Read more about the article Mastering Java Constructors: A Comprehensive Guide 2208

Mastering Java Constructors: A Comprehensive Guide 2208

Read more about the article Java Break and Continue: Unlocking the Power of Flow Control 2208

Java Break and Continue: Unlocking the Power of Flow Control 2208

Leave a reply cancel reply.

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

refresh java logo

  • 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

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

We Love Servers.

  • WHY IOFLOOD?
  • BARE METAL CLOUD
  • DEDICATED SERVERS

Understanding the Java += (Addition Assignment) Operator

java_additional_assignment_operator_symbols

Stumped by the ‘+=’ operator in Java? You’re not alone. Many developers find this operator a bit puzzling, but it’s actually a handy tool that can simplify your code and make your programming tasks easier.

Think of the ‘+=’ operator in Java as a mathematical shortcut – a bridge that connects your variables and values in a more efficient way. It’s a powerful tool that can streamline your code, making it more readable and maintainable.

In this guide, we’ll walk you through the process of understanding and using the ‘+=’ operator in Java , from the basics to more advanced techniques. We’ll cover everything from simple assignments and calculations to its use with strings and arrays, and even discuss alternative approaches.

So, let’s dive in and start mastering the ‘+=’ operator in Java!

TL;DR: What Does ‘+=’ Mean in Java?

In Java, the ‘+=’ represents the additional assignment operator and is used to add the right operand to the left operand and assign the result back to the left operand, with the syntax, operandA += operandB . It’s a shorthand for a common operation that can make your code more concise and easier to read.

Here’s a simple example:

In this example, we declare an integer a and assign it a value of 5. Then, we use the ‘+=’ operator to add 3 to a and assign the result back to a . When we print out a , the output is 8.

This is just a basic use of the ‘+=’ operator in Java, but there’s much more to learn about this operator and how it can simplify your code. Continue reading for more detailed information and advanced usage scenarios.

Table of Contents

The Basics of ‘+=’ in Java

Advanced uses of ‘+=’ in java, exploring alternatives to ‘+=’ in java, troubleshooting java ‘+=’ operator issues, digging into java operators, applying ‘+=’ operator in larger java projects, wrapping up: additional assignment ‘+=’ operator.

The ‘+=’ operator in Java is a compound assignment operator. It’s a shorthand that combines the addition and assignment operations into a single operation. This operator adds the right operand to the left operand and then assigns the result back to the left operand.

Let’s look at a simple example:

In this example, we declare an integer b and assign it a value of 10. Then, we use the ‘+=’ operator to add 5 to b and assign the result back to b . When we print out b , the output is 15.

Advantages of Using ‘+=’

One of the main advantages of using the ‘+=’ operator is that it can make your code more concise and easier to read. Instead of writing b = b + 5; , you can simply write b += 5; .

Pitfalls to Avoid

While the ‘+=’ operator can simplify your code, it’s important to be aware of potential pitfalls. For example, if you use the ‘+=’ operator with a null value, you’ll get a NullPointerException. It’s also important to remember that the ‘+=’ operator performs an implicit cast, which can lead to unexpected results if you’re not careful.

Here’s an example:

In this example, the ‘+=’ operator performs an implicit cast from int (the type of the right operand) to byte (the type of the left operand). The result is -116, which might not be what you expected.

While the ‘+=’ operator is commonly used with numeric types, it can also be used with other types in Java, such as strings and arrays. This versatility can lead to more complex and interesting use cases.

‘+=’ with Strings

In Java, the ‘+=’ operator can be used to concatenate strings. Here’s an example:

In this example, we declare a string s and assign it a value of “Java”. Then, we use the ‘+=’ operator to append ” programming” to s . When we print out s , the output is “Java programming”.

‘+=’ with Arrays

The ‘+=’ operator can also be used with arrays in Java. However, it’s important to note that this usage is not as straightforward as with numeric types or strings. Here’s an example:

In this example, we declare an array and use a for loop to iterate through each element. We use the ‘+=’ operator to add 5 to each element in the array. When we print out the elements of the array, the output is 6, 7, 8.

These advanced uses of the ‘+=’ operator can help you write more efficient and concise code in Java, especially when working with strings and arrays.

While the ‘+=’ operator is a powerful tool in Java, there are other related operators that you can use depending on the specific needs of your code. Understanding these alternatives can give you more flexibility and control over your code.

The ‘+’ Operator

The ‘+’ operator in Java is the most basic form of addition. It adds the right operand to the left operand.

In this example, we’re doing the same thing as c += 3; , but we’re writing it out in a longer form. The ‘+’ operator is straightforward and easy to understand, but it can make your code more verbose.

The ‘++’ Operator

The ‘++’ operator in Java is an increment operator. It increases the value of the variable by 1.

In this example, we’re increasing the value of d by 1. The ‘++’ operator is a concise way to increment a variable, but it’s limited to increasing the value by 1.

Decision-Making Considerations

When deciding which operator to use, consider the needs of your code and the readability of your code. The ‘+=’ operator can make your code more concise, but it might be less clear to someone who isn’t familiar with this operator. The ‘+’ and ‘++’ operators are more explicit, but they can make your code more verbose.

Understanding these alternatives to the ‘+=’ operator can help you write more efficient and readable code in Java.

While the ‘+=’ operator in Java is a powerful tool, it’s not without its potential pitfalls. Understanding these common issues and how to address them can save you time and frustration.

Dealing with Null Values

One common issue is attempting to use the ‘+=’ operator with a null value. This will result in a NullPointerException.

In this example, we attempt to use the ‘+=’ operator to append ” programming” to a null string. This results in a NullPointerException. To avoid this, always ensure that your variables are initialized before using them with the ‘+=’ operator.

Implicit Casting

Another common issue is the implicit casting that occurs when using the ‘+=’ operator. This can lead to unexpected results.

In this example, the ‘+=’ operator performs an implicit cast from int (the type of the right operand) to byte (the type of the left operand), resulting in an unexpected value. To avoid this, be mindful of the types of your variables and the potential for implicit casting.

Optimization Tips

While the ‘+=’ operator can make your code more concise, it’s not always the most efficient choice. For example, if you’re performing a large number of additions, it might be more efficient to use a StringBuilder when working with strings, or to use a loop or a built-in method when working with arrays.

Understanding these common issues and best practices can help you use the ‘+=’ operator more effectively in Java.

Operators in Java are special symbols that perform specific operations on one, two, or three operands, and then return a result. They are the building blocks of any Java program, allowing us to perform calculations, manipulate bits, compare values, and more.

The Role of Operators in Java

Operators play a pivotal role in Java programming. They allow us to perform basic mathematical operations like addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). They also let us compare values and determine logic ( == , != , > , < , && , || ), manipulate bits ( <> , & , | ), and more.

The Importance of ‘+=’ Operator

Among these operators, ‘+=’ holds a special place due to its dual functionality. It’s a compound assignment operator that performs both addition and assignment in a single step. This not only makes our code more concise but also can lead to performance improvements in certain situations.

In this example, we use the ‘+=’ operator to add 5 to x and assign the result back to x in a single step. This is more efficient than performing the addition and assignment in two separate steps.

The ‘+=’ Operator in the Broader Context of Java

The ‘+=’ operator is part of a family of compound assignment operators in Java, which also includes ‘-=’, ‘*=’, ‘/=’, and more. These operators all combine an arithmetic operation with an assignment, making our code more concise and potentially more efficient.

Understanding the ‘+=’ operator and its role in Java programming is key to mastering Java and writing efficient, readable code.

The ‘+=’ operator is not just for small programs or quick scripts. It can be a valuable tool in larger Java projects, where code efficiency and readability become critical.

In large codebases, the ‘+=’ operator can help simplify complex calculations and assignments, making the code easier to understand and maintain. It can also reduce the chance of errors, as it reduces the need to repeat variable names.

Related Topics to Explore

The ‘+=’ operator often accompanies several related topics in typical use cases. Understanding these related concepts can provide a more holistic view of Java programming. These include other compound assignment operators like ‘-=’, ‘*=’, ‘/=’, and ‘%=’, as well as the broader topic of operator precedence in Java.

Further Resources for Mastering Java Operators

To further your understanding of the ‘+=’ operator and related concepts, here are some resources that offer more in-depth information:

  • Java Operator Tutorial: Getting Started – Discover Java’s bitwise operators for manipulating binary data.

.equals Method in Java – Learn to compare the contents of objects for equality with the “.equals()” method in Java.

Exploring ! Operator Usage – Understand how the “!” operator performs logical negation, flipping true to false and vice versa.

Java Operators: Oracle Docs provides a comprehensive overview of all operators in Java, including the ‘+=’ operator.

Java Compound Assignment Operators discusses the usage of compound assignment operators in Java.

Java Operator Precedence explains operator precedence in Java, which determines how expressions involving the ‘+=’ operator are evaluated.

In this comprehensive guide, we’ve demystified the ‘+=’ operator in Java, a handy tool that can simplify your code and streamline your programming tasks.

We began with the basics, examining how the ‘+=’ operator functions as a mathematical shortcut in Java. We then delved into more advanced usage scenarios, such as using the ‘+=’ operator with strings and arrays. We also explored alternative approaches and related operators in Java, giving you a broader understanding of the Java operator landscape.

Throughout our exploration, we tackled common issues and pitfalls associated with the ‘+=’ operator, such as dealing with null values and understanding implicit casting. We provided solutions and best practices to help you overcome these challenges.

Here’s a quick comparison of the methods we’ve discussed:

Whether you’re a beginner just starting out with Java or an experienced developer looking to brush up on your skills, we hope this guide has shed light on the ‘+=’ operator in Java and its usage.

The ‘+=’ operator is a powerful tool in your Java toolkit, offering a combination of simplicity, efficiency, and versatility. Now, you’re well equipped to use it in your Java projects. Happy coding!

About Author

Gabriel Ramuglia

Gabriel Ramuglia

Gabriel is the owner and founder of IOFLOOD.com , an unmanaged dedicated server hosting company operating since 2010.Gabriel loves all things servers, bandwidth, and computer programming and enjoys sharing his experience on these topics with readers of the IOFLOOD blog.

Related Posts

Bash script for substring extraction featuring text cropping icons and selection markers emphasizing precision and text analysis

  • TutorialKart
  • SAP Tutorials
  • Salesforce Admin
  • Salesforce Developer
  • Visualforce
  • Informatica
  • Kafka Tutorial
  • Spark Tutorial
  • Tomcat Tutorial
  • Python Tkinter

Programming

  • Bash Script
  • Julia Tutorial
  • CouchDB Tutorial
  • MongoDB Tutorial
  • PostgreSQL Tutorial
  • Android Compose
  • Flutter Tutorial
  • Kotlin Android

Web & Server

  • Selenium Java
  • Java Basics
  • Java Tutorial
  • Java HelloWorld Program
  • Java Program Structure
  • Java Datatypes
  • Java Variable Types
  • Java Access Modifiers
  • Java Operators
  • Java Decision Making
  • Print array
  • Initialize array
  • Array of integers
  • Array of strings
  • Array of objects
  • Array of arrays
  • Iterate over array
  • Array For loop
  • Array while loop
  • Append element to array
  • Check if array is empty
  • Array average
  • Check if array contains
  • Array ForEach
  • Array - Find Index of Item
  • Concatenate arrays
  • Find smallest number in array
  • Find largest number in array
  • Array reverse
  • Classes and Objects
  • Inheritance
  • Polymorphism
  • Method Overloading
  • Method Overriding/
  • Abstraction
  • Abstract methods and classes
  • Encapsulation
  • Print string
  • Read string from console
  • Create string from Char array
  • Create string from Byte array
  • Concatenate two strings
  • Get index of the first Occurrence of substring
  • Get index of nth occurrence of substring
  • Check if two strings are equal
  • Check if string ends with specific suffix
  • Check if string starts with specific prefix
  • Check if string is blank
  • Check if string is empty
  • Check if string contains search substring
  • Validate if string is a Phone Number
  • Character Level
  • Get character at specific index in string
  • Get first character in string
  • Get last character from string
  • Transformations
  • Replace first occurrence of string
  • Replace all occurrences of a string
  • Join strings
  • Join strings in string array
  • Join strings in ArrayList
  • Reverse a string
  • Trim string
  • Split string
  • Remove whitespaces in string
  • Replace multiple spaces with single space
  • Comparisons
  • Compare strings lexicographically
  • Compare String and CharSequence
  • Compare String and StringBuffer
  • Java Exception Handling StringIndexOutOfBoundsException
  • Convert string to int
  • Convert string to float
  • Convert string to double
  • Convert string to long
  • Convert string to boolean
  • Convert int to string
  • Convert int to float
  • Convert int to double
  • Convert int to long
  • Convert int to char
  • Convert float to string
  • Convert float to int
  • Convert float to double
  • Convert float to long
  • Convert long to string
  • Convert long to float
  • Convert long to double
  • Convert long to int
  • Convert double to string
  • Convert double to float
  • Convert double to int
  • Convert double to long
  • Convert char to int
  • Convert boolean to string
  • Create a file
  • Read file as string
  • Write string to file
  • Delete File
  • Rename File
  • Download File from URL
  • Replace a String in File
  • Filter list of files or directories
  • Check if file is readable
  • Check if file is writable
  • Check if file is executable
  • Read contents of a file line by line using BufferedReader
  • Read contents of a File line by line using Stream
  • Check if n is positive or negative
  • Read integer from console
  • Add two integers
  • Count digits in number
  • Largest of three numbers
  • Smallest of three numbers
  • Even numbers
  • Odd numbers
  • Reverse a number
  • Prime Number
  • Print All Prime Numbers
  • Factors of a Number
  • Check Palindrome number
  • Check Palindrome string
  • Swap two numbers
  • Even or Odd number
  • Java Classes
  • ArrayList add()
  • ArrayList addAll()
  • ArrayList clear()
  • ArrayList clone()
  • ArrayList contains()
  • ArrayList ensureCapacity()
  • ArrayList forEach()
  • ArrayList get()
  • ArrayList indexOf()
  • ArrayList isEmpty()
  • ArrayList iterator()
  • ArrayList lastIndexOf()
  • ArrayList listIterator()
  • ArrayList remove()
  • ArrayList removeAll()
  • ArrayList removeIf()
  • ArrayList removeRange()
  • ArrayList retainAll()
  • ArrayList set()
  • ArrayList size()
  • ArrayList spliterator()
  • ArrayList subList()
  • ArrayList toArray()
  • ArrayList trimToSize()
  • HashMap clear()
  • HashMap clone()
  • HashMap compute()
  • HashMap computeIfAbsent()
  • HashMap computeIfPresent()
  • HashMap containsKey()
  • HashMap containsValue()
  • HashMap entrySet()
  • HashMap get()
  • HashMap isEmpty()
  • HashMap keySet()
  • HashMap merge()
  • HashMap put()
  • HashMap putAll()
  • HashMap remove()
  • HashMap size()
  • HashMap values()
  • HashSet add()
  • HashSet clear()
  • HashSet clone()
  • HashSet contains()
  • HashSet isEmpty()
  • HashSet iterator()
  • HashSet remove()
  • HashSet size()
  • HashSet spliterator()
  • Integer bitCount()
  • Integer byteValue()
  • Integer compare()
  • Integer compareTo()
  • Integer compareUnsigned()
  • Integer decode()
  • Integer divideUnsigned()
  • Integer doubleValue()
  • Integer equals()
  • Integer floatValue()
  • Integer getInteger()
  • Integer hashCode()
  • Integer highestOneBit()
  • Integer intValue()
  • Integer longValue()
  • Integer lowestOneBit()
  • Integer max()
  • Integer min()
  • Integer numberOfLeadingZeros()
  • Integer numberOfTrailingZeros()
  • Integer parseInt()
  • Integer parseUnsignedInt()
  • Integer remainderUnsigned()
  • Integer reverse()
  • Integer reverseBytes()
  • Integer rotateLeft()
  • Integer rotateRight()
  • Integer shortValue()
  • Integer signum()
  • Integer sum()
  • Integer toBinaryString()
  • Integer toHexString()
  • Integer toOctalString()
  • Integer toString()
  • Integer toUnsignedLong()
  • Integer toUnsignedString()
  • Integer valueOf()
  • StringBuilder append()
  • StringBuilder appendCodePoint()
  • StringBuilder capacity()
  • StringBuilder charAt()
  • StringBuilder chars()
  • StringBuilder codePointAt()
  • StringBuilder codePointBefore()
  • StringBuilder codePointCount()
  • StringBuilder codePoints()
  • StringBuilder delete()
  • StringBuilder deleteCharAt()
  • StringBuilder ensureCapacity()
  • StringBuilder getChars()
  • StringBuilder indexOf()
  • StringBuilder insert()
  • StringBuilder lastIndexOf()
  • StringBuilder length()
  • StringBuilder offsetByCodePoints()
  • StringBuilder replace()
  • StringBuilder reverse()
  • StringBuilder setCharAt()
  • StringBuilder setLength()
  • StringBuilder subSequence()
  • StringBuilder substring()
  • StringBuilder toString()
  • StringBuilder trimToSize()
  • Arrays.asList()
  • Arrays.binarySearch()
  • Arrays.copyOf()
  • Arrays.copyOfRange()
  • Arrays.deepEquals()
  • Arrays.deepToString()
  • Arrays.equals()
  • Arrays.fill()
  • Arrays.hashCode()
  • Arrays.sort()
  • Arrays.toString()
  • Random doubles()
  • Random ints()
  • Random longs()
  • Random next()
  • Random nextBoolean()
  • Random nextBytes()
  • Random nextDouble()
  • Random nextFloat()
  • Random nextGaussian()
  • Random nextInt()
  • Random nextLong()
  • Random setSeed()
  • Math random
  • Math signum
  • Math toDegrees
  • Math toRadians
  • Java Date & Time
  • ❯ Java Tutorial

Java Bitwise AND Assignment (&=) Operator

Java bitwise and assignment.

In Java, Bitwise AND Assignment Operator is used to compute the Bitwise AND operation of left and right operands, and assign the result back to left operand. In this tutorial, we will learn how to use Bitwise AND Assignment operator in Java, with examples.

The syntax to compute bitwise AND a value of 2 and value in variable x , and assign the result back to x using Bitwise AND Assignment Operator is

In the following example, we take a variable x with an initial value of 9 , add bitwise AND it with value of 2 , and assign the result to x , using Bitwise AND Assignment Operator.

In this Java Tutorial , we learned about Bitwise AND Assignment Operator in Java, with examples.

Popular Courses by TutorialKart

App developement, web development, online tools.

TecAdmin

Java Operators MCQs (Multiple Choice Questions)

Java, one of the most widely used programming languages, offers a rich set of operators to perform various operations, from basic arithmetic to complex logical evaluations. Understanding these operators and their precedence is crucial for anyone looking to master Java programming. To aid in this journey, we have compiled a meticulously curated set of multiple-choice questions (MCQs) focusing on Java Operators. This collection spans from the foundational arithmetic and relational operators to the more nuanced conditional and bitwise operators. Whether you’re a novice programmer aiming to solidify your Java fundamentals or an experienced developer looking to brush up on the intricacies of Java operators, this guide is tailored to enhance your knowledge and test your skills.

Q1 Which operator is used to compare two values for equality in Java?

A = B == C === D <>

Q2 What is the output of the expression ’10 % 3′?

A 3 B 1 C 0 D 10

Q3 Which operator is used for string concatenation in Java?

A + B & C && D .

Q4 What does the ‘++’ operator do to a variable?

A Decreases its value by 1 B Increases its value by 1 C Doubles its value D Squares its value

Q5 Which of the following is the correct way to use the ternary operator?

A var result = (condition) ? valueIfTrue : valueIfFalse; B var result = (condition, valueIfTrue, valueIfFalse); C var result = ?(condition) valueIfTrue : valueIfFalse; D var result = if(condition) ? valueIfTrue : valueIfFalse;

Q6 What is the result of the expression ‘5 == 5’?

A true B false C 1 D 0

Q7 Which operator checks if two variables refer to the same object instance?

A == B === C equals() D instanceof

Q8 What is the result of the expression ‘!true’?

Q9 What is the precedence order of the operators: *, +, and ()?

A +, *, () B *, +, () C (), *, + D (), +, *

Q10 Which operator is used to invert the value of a boolean variable?

A ~ B ! C – D ^

Q11 Which of the following operators has the highest precedence in Java?

A && B + C / D ++

Q12 What does the expression ‘x &= y’ do?

A Sets x to the result of x AND y B Sets x to the result of x OR y C Sets x to the result of x XOR y D Compares x and y for equality

Q13 Which of the following is true about the ‘instanceof’ operator?

A It is used to compare numerical values B It is used for arithmetic operations C It checks if an object is an instance of a specific class or interface D It concatenates strings

Q14 Which of the following is a unary operator in Java?

A + B – C / D *

Q15 What is the output of ‘1 << 2'?

A 1 B 2 C 3 D 4

Q16 What is the output of the following code snippet?

A 15 B 16 C 17 D 18

Q17 How do you perform a bitwise OR operation between two integers x and y?

A x || y B x | y C x OR y D x + y

Q18 Which operator is used for type casting in Java?

A cast B instanceof C () D typeof

Q19 What is the result of the expression ‘null instanceof Object’?

A true B false C NullPointerException D Compilation error

Q20 What does the expression ‘var a = 20; var b = a << 2;' set 'b' to?

A 5 B 40 C 80 D 100

Q21 Which of the following is NOT a relational operator in Java?

A B >= C == D =>

Q22 What is the use of the operator ‘?:’ in Java?

A To perform logical operations B To perform exponential calculations C To assign a value based on a condition D To concatenate strings

Q23 What does the ‘>>>=’ assignment operator do?

A Performs a right shift and assigns the result B Performs a left shift and assigns the result C Performs an unsigned right shift and assigns the result D Performs an unsigned left shift and assigns the result

Q24 Which operator is used to determine if an object is of a certain type (class) at runtime?

A == B != C instanceof D getClass()

Q25 What does the expression ‘true || false’ evaluate to in Java?

A true B false C 0 D 1

Q26 Which of the following is the correct use of the bitwise XOR operator in Java?

A int result = x ~ y; B int result = x ^ y; C int result = x | y; D int result = x && y;

Q27 What is the result of the following operation: ‘4 | 3’?

A 0 B 7 C 1 D 12

Q28 In Java, what does the ‘>>>=’ operator do?

A Performs a right arithmetic shift and assigns the result B Performs a left arithmetic shift and assigns the result C Performs an unsigned right shift and assigns the result D Performs an unsigned left shift and assigns the result

Navigating through the realm of Java operators is a fundamental step towards mastering Java programming. The provided MCQs offer a panoramic view of Java’s operator capabilities, from manipulating numbers and strings to making complex decisions based on various conditions. Engaging with these questions not only reinforces theoretical concepts but also sharpens practical problem-solving skills. As you progress, remember that the understanding of operators extends beyond their individual functionality; it’s about recognizing their role in the broader context of Java programming paradigms. We encourage learners to delve deeper into each topic, experiment with code examples, and continuously challenge their understanding. This exploration is not just about passing a test; it’s about laying a solid foundation for your Java programming journey.

Related Posts

Python coding challenge 001: character frequency counter, step-by-step guide to installing java on ubuntu 24.04.

Mastering Linux-challenge 001

Mastering Linux Challenge 001 – Is the execution time of crontab correct?

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

Type above and press Enter to search. Press Esc to cancel.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

JavaScript ( JS ) is a lightweight interpreted (or just-in-time compiled) programming language with first-class functions . While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js , Apache CouchDB and Adobe Acrobat . JavaScript is a prototype-based , multi-paradigm, single-threaded , dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.

JavaScript's dynamic capabilities include runtime object construction, variable parameter lists, function variables, dynamic script creation (via eval ), object introspection (via for...in and Object utilities ), and source-code recovery (JavaScript functions store their source text and can be retrieved through toString() ).

This section is dedicated to the JavaScript language itself, and not the parts that are specific to Web pages or other host environments. For information about APIs that are specific to Web pages, please see Web APIs and DOM .

The standards for JavaScript are the ECMAScript Language Specification (ECMA-262) and the ECMAScript Internationalization API specification (ECMA-402). As soon as one browser implements a feature, we try to document it. This means that cases where some proposals for new ECMAScript features have already been implemented in browsers, documentation and examples in MDN articles may use some of those new features. Most of the time, this happens between the stages 3 and 4, and is usually before the spec is officially published.

Do not confuse JavaScript with the Java programming language — JavaScript is not "Interpreted Java" . Both "Java" and "JavaScript" are trademarks or registered trademarks of Oracle in the U.S. and other countries. However, the two programming languages have very different syntax, semantics, and use.

JavaScript documentation of core language features (pure ECMAScript , for the most part) includes the following:

  • The JavaScript guide
  • The JavaScript reference

For more information about JavaScript specifications and related technologies, see JavaScript technologies overview .

Learn how to program in JavaScript with guides and tutorials.

For complete beginners

Head over to our Learning Area JavaScript topic if you want to learn JavaScript but have no previous experience with JavaScript or programming. The complete modules available there are as follows:

Answers some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", along with discussing key JavaScript features such as variables, strings, numbers, and arrays.

Continues our coverage of JavaScript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events.

The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you.

Discusses asynchronous JavaScript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.

Explores what APIs are, and how to use some of the most common APIs you'll come across often in your development work.

JavaScript guide

A much more detailed guide to the JavaScript language, aimed at those with previous programming experience either in JavaScript or another language.

Intermediate

JavaScript frameworks are an essential part of modern front-end web development, providing developers with proven tools for building scalable, interactive web applications. This module gives you some fundamental background knowledge about how client-side frameworks work and how they fit into your toolset, before moving on to a series of tutorials covering some of today's most popular ones.

An overview of the basic syntax and semantics of JavaScript for those coming from other programming languages to get up to speed.

Overview of available data structures in JavaScript.

JavaScript provides three different value comparison operations: strict equality using === , loose equality using == , and the Object.is() method.

How different methods that visit a group of object properties one-by-one handle the enumerability and ownership of properties.

A closure is the combination of a function and the lexical environment within which that function was declared.

Explanation of the widely misunderstood and underestimated prototype-based inheritance.

Memory life cycle and garbage collection in JavaScript.

JavaScript has a runtime model based on an "event loop".

Browse the complete JavaScript reference documentation.

Get to know standard built-in objects Array , Boolean , Date , Error , Function , JSON , Math , Number , Object , RegExp , String , Map , Set , WeakMap , WeakSet , and others.

Learn more about the behavior of JavaScript's operators instanceof , typeof , new , this , the operator precedence , and more.

Learn how do-while , for-in , for-of , try-catch , let , var , const , if-else , switch , and more JavaScript statements and keywords work.

Learn how to work with JavaScript's functions to develop your applications.

JavaScript classes are the most appropriate way to do object-oriented programming.

IMAGES

  1. Java operators with examples

    what are the assignment operators in java

  2. Java operators with examples

    what are the assignment operators in java

  3. Assignment Operators in Java with Examples

    what are the assignment operators in java

  4. The Assignment Operator in Java

    what are the assignment operators in java

  5. Operators in Java and its Types

    what are the assignment operators in java

  6. Types of Java Operators

    what are the assignment operators in java

VIDEO

  1. Assignment operators in java

  2. #6

  3. Core

  4. #20. Assignment Operators in Java

  5. #06 Java Operators

  6. Operators, Types of Operators in Java

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. Assignment, Arithmetic, and Unary Operators (The Java™ Tutorials

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

  3. Java Operators

    Java Assignment Operators. Assignment operators are used to assign values to variables. In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x: Example int x = 10;

  4. Java Operators: Arithmetic, Relational, Logical and more

    Java Assignment Operators. Assignment operators are used in Java to assign values to variables. For example, int age; age = 5; Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5 is assigned to the variable age.

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

  6. All Java Assignment Operators (Explained With Examples)

    There are mainly two types of assignment operators in Java, which are as follows: Simple Assignment Operator ; We use the simple assignment operator with the "=" sign, where the left side consists of an operand and the right side is a value. The value of the operand on the right side must be of the same data type defined on the left side.

  7. Java Assignment Operators

    Java Assignment Operators. The Java Assignment Operators are used when you want to assign a value to the expression. The assignment operator denoted by the single equal sign =. In a Java assignment statement, any expression can be on the right side and the left side must be a variable name. For example, this does not mean that "a" is equal to ...

  8. Operators (The Java™ Tutorials > Learning the Java Language

    Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest ...

  9. Java Operators

    The simple assignment operator (=) is a straightforward but important operator in Java. Actually, we've used it many times in previous examples. It assigns the value on its right to the operand on its left: int seven = 7; 9.2. Compound Assignments

  10. Java Assignment operators

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

  11. Types of Assignment Operators in Java

    Types of Assignment Operators in Java. Java is a popular programming language that software developers use to construct a wide range of applications. It is a simple, robust, and platform-independent object-oriented language. There are various types of assignment operators in Java, each with its own function.

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

  13. Java

    Example. =. Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign value of A + B into C. +=. Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand. C += A is equivalent to C = C + A.

  14. Java Assignment Operators

    Compound Assignment Operators. Sometime we need to modify the same variable value and reassigned it to a same reference variable. Java allows you to combine assignment and addition operators using a shorthand operator. For example, the preceding statement can be written as: i +=8; //This is same as i = i+8; The += is called the addition ...

  15. Exploring Operators in Java 101: A Comprehensive Guide to Mastering

    Assignment Operators. Assignment operators in Java are used to assign values to variables. The basic assignment operator (=) assigns the value on the right-hand side to the variable on the left-hand side. In addition to the basic operator, Java provides compound assignment operators such as +=, -=, *=, /=, and %= which combine arithmetic ...

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

  17. operators, expressions, precedence, associativity in Java

    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. What is += Addition Assignment Operator in Java?

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

  19. Understanding the Java += (Addition Assignment) Operator

    The '+=' operator in Java is a compound assignment operator. It's a shorthand that combines the addition and assignment operations into a single operation. This operator adds the right operand to the left operand and then assigns the result back to the left operand. Let's look at a simple example:

  20. Java Bitwise AND Assignment (&=) Operator

    In Java, Bitwise AND Assignment Operator is used to compute the Bitwise AND operation of left and right operands, and assign the result back to left operand. In this tutorial, we will learn how to use Bitwise AND Assignment operator in Java, with examples. The syntax to compute bitwise AND a value of 2 and value in variable x, and assign the ...

  21. Java Operators MCQs (Multiple Choice Questions)

    Java, one of the most widely used programming languages, offers a rich set of operators to perform various operations, from basic arithmetic to complex logical evaluations. Understanding these operators and their precedence is crucial for anyone looking to master Java programming. To aid in this journey, we have compiled a meticulously curated set of multiple-choice

  22. JavaScript

    JavaScript (JS) is a lightweight interpreted (or just-in-time compiled) programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat. JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented ...

  23. C++ Assignment Operator overloading unexpected behavior

    That is the returned temporary object created within your assignment operator is used to initialize the newly defined object C by means of the default copy constructor. Again the object B will be unchanged as pointed out above. One more the above code snippet is equivalent to. Point C = B.operator =( A );