Java Tutorial

Java methods, java classes, java file handling, java how to's, 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.

Operator Name Description Example Try it
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

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:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

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:

Operator Name Example Try it
== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

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:

Operator Name Description Example Try it
&&  Logical and Returns true if both statements are true x < 5 &&  x < 10
||  Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Java Bitwise Operators

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

Operator Description Example Same as Result Decimal
& AND - Sets each bit to 1 if both bits are 1 5 & 1 0101 & 0001 0001  1
| OR - Sets each bit to 1 if any of the two bits is 1 5 | 1 0101 | 0001 0101  5
~ NOT - Inverts all the bits ~ 5  ~0101 1010  10
^ XOR - Sets each bit to 1 if only one of the two bits is 1 5 ^ 1 0101 ^ 0001 0100  4
<< Zero-fill left shift - Shift left by pushing zeroes in from the right and letting the leftmost bits fall off 9 << 1 1001 << 1 0010 2
>> Signed right shift - Shift right by pushing copies of the leftmost bit in from the left and letting the rightmost bits fall off 9 >> 1 1001 >> 1 1100 12
>>> Zero-fill right shift - Shift right by pushing zeroes in from the left and letting the rightmost bits fall off 9 >>> 1 1001 >>> 1 0100 4

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.

Java Assignment Operators

Java programming tutorial index.

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

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

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

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

Java8 Homepage

  • Fundamentals
  • Objects & Classes
  • OO Concepts
  • API Contents
  • Input & Output
  • Collections
  • Concurrency
  • Swing & RMI
  • Certification

Assignment Operators J8 Home   «   Assignment Operators

  • <<    Relational & Logical Operators
  • Bitwise Logical Operators     >>

Symbols used for mathematical and logical manipulation that are recognized by the compiler are commonly known as operators in Java. In the third of five lessons on operators we look at the assignment operators available in Java.

Assignment Operators Overview  Top

The single equal sign = is used for assignment in Java and we have been using this throughout the lessons so far. This operator is fairly self explanatory and takes the form variable = expression; . A point to note here is that the type of variable must be compatible with the type of expression .

Shorthand Assignment Operators

The shorthand assignment operators allow us to write compact code that is implemented more efficiently.

Operator Meaning Example Result Notes
+=Addition 10
-=Subtraction 0
/=Division 3When used with an type, any remainder will be truncated.
*=Multiplication 25
%=Modulus 1Holds the remainder value of a division.
&=AND



















Will check both operands for values and assign or to the first operand dependant upon the outcome of the expression.
|=OR



















Will check both operands for values and assign or to the first operand dependant upon the outcome of the expression.
^=XOR



















Will check both operands for different values and assign or to the first operand dependant upon the outcome of the expression.

Automatic Type Conversion, Assignment Rules  Top

The following table shows which types can be assigned to which other types, of course we can assign to the same type so these boxes are greyed out.

When using the table use a row for the left assignment and a column for the right assignment. So in the highlighted permutations byte = int won't convert and int = byte will convert.

Type
NONONONONONONO
NONONONONONONO
NONONONONONONO
NONOYESNONONONO
NOYESYESYESNONONO
NOYESYESYESYESNONO
NOYESYESYESYESYESNO
NOYESYESYESYESYESYES

Casting Incompatible Types  Top

The above table isn't the end of the story though as Java allows us to cast incompatible types. A cast instructs the compiler to convert one type to another enforcing an explicit type conversion.

A cast takes the form     target = (target-type) expression .

There are a couple of things to consider when casting incompatible types:

  • With narrowing conversions such as an int to a short there may be a loss of precision if the range of the int exceeds the range of a short as the high order bits will be removed.
  • When casting a floating-point type to an integer type the fractional component is lost through truncation.
  • The target-type can be the same type as the target or a narrowing conversion type.
  • The boolean type is not only incompatible but also inconvertible with other types.

Lets look at some code to see how casting works and the affect it has on values:

Running the Casting class produces the following output:

run casting

The first thing to note is we got a clean compile because of the casts, all the type conversions would fail otherwise. You might be suprised by some of the results shown in the screenshot above, for instance some of the values have become negative. Because we are truncating everything to a byte we are losing not only any fractional components and bits outside the range of a byte , but in some cases the signed bit as well. Casting can be very useful but just be aware of the implications to values when you enforce explicit type conversion.

Related Quiz

Fundamentals Quiz 8 - Assignment Operators Quiz

Lesson 9 Complete

In this lesson we looked at the assignment operators used in Java.

What's Next?

In the next lesson we look at the bitwise logical operators used in Java.

Getting Started

Code structure & syntax, java variables, primitives - boolean & char data types, primitives - numeric data types, method scope, arithmetic operators, relational & logical operators, assignment operators, assignment operators overview, automatic type conversion, casting incompatible types, bitwise logical operators, bitwise shift operators, if construct, switch construct, for construct, while construct.

Java 8 Tutorials

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

Now that you've learned how to declare and initialize variables, you probably want to know how to do something with them. 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 precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

Operators Precedence
postfix ++ --
unary -- + - ~ !
multiplicative
additive
shift
relational
equality
bitwise AND
bitwise exclusive OR
bitwise inclusive OR
logical AND
logical OR
ternary
assignment

In general-purpose programming, certain operators tend to appear more frequently than others; for example, the assignment operator " = " is far more common than the unsigned right shift operator " >>> ". With that in mind, the following discussion focuses first on the operators that you're most likely to use on a regular basis, and ends focusing on those that are less common. Each discussion is accompanied by sample code that you can compile and run. Studying its output will help reinforce what you've just learned.

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

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

Learn Java practically and Get Certified .

Popular Tutorials

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

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)

Java Operators

  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement

Java Ternary Operator

  • Java for Loop
  • Java for-each Loop
  • Java while and do...while Loop
  • Java break Statement
  • Java continue Statement
  • Java switch Statement
  • Java Arrays
  • Java Multidimensional Arrays
  • Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword
  • 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 Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • 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 ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • 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 Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

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

Additional Topics

  • Java Keywords and Identifiers

Java Operator Precedence

Java Bitwise and Shift Operators

  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics
  • Nested Loop in Java
  • Java Command-Line Arguments

Java Tutorials

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

Operator Operation
Addition
Subtraction
Multiplication
Division
Modulo Operation (Remainder after division)

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.

Operator Example Equivalent to

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 .

Operator Description Example
Is Equal To returns
Not Equal To returns
Greater Than returns
Less Than returns
Greater Than or Equal To returns
Less Than or Equal To returns

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.

Operator Example Meaning
(Logical AND) expression1 expression2 only if both and are
(Logical OR) expression1 expression2 if either or is
(Logical NOT) expression if is and vice versa

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:

Operator Meaning
: not necessary to use since numbers are positive without using it
: inverts the sign of an expression
: increments value by 1
: decrements value by 1
: inverts the value of a boolean
  • 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:

Operator Description
Bitwise Complement
Left Shift
Right Shift
Unsigned Right Shift
Bitwise AND
Bitwise exclusive OR

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

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.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Java Tutorial

clear sunny desert yellow sand with celestial snow bridge

1.7 Java | Assignment Statements & Expressions

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

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

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

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

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

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

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

Java Assignment Statement vs Assignment Expression

Which is equivalent to:

And this statement

is equivalent to:

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

◄◄◄BACK | NEXT►►►

What's Your Opinion? Cancel reply

Enhance your Brain

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

HTML for Simple Website Customization My Personal Web Customization Personal Insights

DISCLAIMER | Sitemap | ◘

SponserImageUCD

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

Top Posts & Pages

The 7 Layer OSI Model of IT Troubleshooting

What Is an Assignment Statement in Java?

...

Java programs store data values in variables. When a programmer creates a variable in a Java application, he declares the type and name of the variable, then assigns a value to it. The value of a variable can be altered at subsequent points in execution using further assignment operations. The assignment statement in Java involves using the assignment operator to set the value of a variable. The exact syntax depends on the type of variable receiving a value.

Advertisement

Video of the Day

In Java, variables are strongly typed. This means that when you declare a variable in a Java program, you must declare its type, followed by its name. The following sample Java code demonstrates declaring two variables, one of primitive-type integer and one of an object type for a class within the application: int num; ApplicationHelper myHelp;

Once a program contains a variable declaration, the kind of value assigned to the variable must be suited to the type declared. These variable declarations could be followed by assignment statements on subsequent lines. However, the assignment operation could also take place on the same line as the declaration.

Assignment in Java is the process of giving a value to a primitive-type variable or giving an object reference to an object-type variable. The equals sign acts as assignment operator in Java, followed by the value to assign. The following sample Java code demonstrates assigning a value to a primitive-type integer variable, which has already been declared: num = 5;

The assignment operation could alternatively appear within the same line of code as the declaration of the variable, as follows: int num = 5;

The value of the variable can be altered again in subsequent processing as in this example: num++;

This code increments the variable value, adding a value of one to it.

Instantiation

When the assignment statement appears with object references, the assignment operation may also involve object instantiation. When Java code creates a new object instance of a Java class in an application, the "new" keyword causes the constructor method of the class to execute, instantiating the object. The following sample code demonstrates instantiating an object variable: myHelp = new ApplicationHelper();

This could also appear within the same line as the variable declaration as follows: ApplicationHelper myHelp = new ApplicationHelper();

When this line of code executes, the class constructor method executes, returning an instance of the class, a reference to which is stored by the variable.

Referencing

Once a variable has been declared and assigned a value, a Java program can refer to the variable in subsequent processing. For primitive-type variables, the variable name refers to a stored value. For object types, the variable refers to the location of the object instance in memory. This means that two object variables can point to the same instance, as in the following sample code: ApplicationHelper myHelp = new ApplicationHelper(); ApplicationHelper sameHelp = myHelp;

This syntax appears commonly when programs pass object references as parameters to class methods.

  • Oracle: The Java Tutorials - Variables
  • Oracle: The Java Tutorials - Assignment, Arithmetic, and Unary Operators
  • Oracle: The Java Tutorials - Primitive Data Types
  • Oracle: The Java Tutorials - Creating Objects
  • Oracle: The Java Tutorials - What Is an Object?
  • Oracle: The Java Tutorials - Summary of Variables
  • Java Language Specification; Types, Values, and Variables; 2000
  • Oracle: The Java Tutorials - Understanding Instance and Class Members

Java Assignment Operators

OperatorsExampleExplanation
=x = 9Value 25 is assigned to x
+=x += 9This is same as x = x + 9
-=x -= 9This is same as x = x – 9
*=x *= 9This is same as x = x * 9
/=x /= 9This is same as x = x / 9
%=x %= 9This is same as x = x % 9

Java Assignment Operators example

  • ▼Java Tutorial
  • Introduction
  • Java Program Structure
  • Java Primitive data type
  • ▼Development environment setup
  • Download and Install JDK, Eclipse (IDE)
  • Compiling, running and debugging Java programs
  • ▼Declaration and Access control
  • Class, methods, instance variables
  • Java Packages
  • ▼OOPS Concepts
  • Java Object Oriented Programming concepts
  • Is-A and Has-A relationship
  • ▼Assignments
  • Arrays - 2D array and Multi dimension array
  • Wrapper classes
  • ▼Operators
  • Assignment Operator
  • Arithmetic Operator
  • Conditional Operator
  • Logical Operator
  • ▼Flow Control
  • Switch Satement
  • While and Do loop
  • Java Branching Statements
  • ▼Exceptions
  • Handling Exceptions
  • Checked and unchecked
  • Custom Exception
  • Try with resource feature of Java 7
  • ▼String Class
  • String Class
  • Important methods of String class with example
  • String buffer class and string builder class
  • ▼File I/O and serialization
  • File Input and Output
  • Reading file
  • Writing file
  • Java Property File Processing
  • Java Serialization
  • ▼Java Collection
  • Java Collection Framework
  • Java ArrayList and Vector
  • Java LinkedList Class
  • Java HashSet
  • Java TreeSet
  • Java Linked HashSet
  • Java Utility Class
  • ▼Java Thread
  • Java Defining, Instantiating and Starting Thread
  • Java Thread States and Transitions
  • Java Thread Interaction
  • Java Code Synchronization
  • ▼Java Package
  • ▼Miscellaneous
  • Garbage Collection in Java
  • BigDecimal Method

Java Assignment Operators

Description.

Assigning a value to a variable seems straightforward enough; you simply assign the stuff on the right side of the '= 'to the variable on the left. Below statement 1 assigning value 10 to variable x and statement 2 is creating String object called name and assigning value "Amit" to it.

Assignment can be of various types. Let’s discuss each in detail.

Primitive Assignment:

The equal (=) sign is used for assigning a value to a variable. We can assign a primitive variable using a literal or the result of an expression.

Primitive Casting

Casting lets you convert primitive values from one type to another. We need to provide casting when we are trying to assign higher precision primitive to lower precision primitive for example If we try to assign int variable (which is in the range of byte variable) to byte variable then the compiler will throw an exception called "possible loss of precision". Eclipse IDE will suggest the solution as well as shown below. To avoid such problem we should use type casting which will instruct compiler for type conversion.

assignment operator image-1

For cases where we try to assign smaller container variable to larger container variables we do not need of explicit casting. The compiler will take care of those type conversions. For example, we can assign byte variable or short variable to an int without any explicit casting.

assignment operator image-2

Assigning Literal that is too large for a variable

When we try to assign a variable value which is too large (or out of range ) for a primitive variable then the compiler will throw exception “possible loss of precision” if we try to provide explicit cast then the compiler will accept it but narrowed down the value using two’s complement method. Let’s take an example of the byte which has 8-bit storage space and range -128 to 127. In below program we are trying to assign 129 literal value to byte primitive type which is out of range for byte so compiler converted it to -127 using two’s complement method. Refer link for two’s complement calculation (http://en.wikipedia.org/wiki/Two's_complement)

Java Code: Go to the editor

assignment operator image-3

Reference variable assignment

We can assign newly created object to object reference variable as below

First line will do following things,

  • Makes a reference variable named s of type String
  • Creates a new String object on the heap memory
  • Assigns the newly created String object to the reference variables

You can also assign null to an object reference variable, which simply means the variable is not referring to any object. The below statement creates space for the Employee reference variable (the bit holder for a reference value) but doesn't create an actual Employee object.

Compound Assignment Operators

Sometime we need to modify the same variable value and reassigned it to a same reference variable. Java allows you to combine assignment and addition operators using a shorthand operator. For example, the preceding statement can be written as:

The += is called the addition assignment operator. Other shorthand operators are shown below table

Operator Name Example Equivalent
+= Addition assignment i+=5; i=i+5
-= Subtraction assignment j-=10; j=j-10;
*= Multiplication assignment k*=2; k=k*2;
/= Division assignment x/=10; x=x/10;
%= Remainder assignment a%=4; a=a%4;

Below is the sample program explaining assignment operators:

assignment operator image-4

  • Assigning a value to can be straight forward or casting.
  • If we assign the value which is out of range of variable type then 2’s complement is assigned.
  • Java supports shortcut/compound assignment operator.

Java Code Editor:

Previous: Wrapper classes Next: Arithmetic Operator

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends and Language Statistics
  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Assignment Operators in Programming

Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improving readability.

Table of Content

What are Assignment Operators?

  • Types of Assignment Operators
  • Assignment Operators in C
  • Assignment Operators in C++
  • Assignment Operators in Java
  • Assignment Operators in Python
  • Assignment Operators in C#
  • Assignment Operators in JavaScript
  • Application of Assignment Operators

Assignment operators are used in programming to  assign values  to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign ( = ), which assigns the value on the right side of the operator to the variable on the left side.

Types of Assignment Operators:

  • Simple Assignment Operator ( = )
  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )

Below is a table summarizing common assignment operators along with their symbols, description, and examples:

OperatorDescriptionExamples
= (Assignment)Assigns the value on the right to the variable on the left.  assigns the value 10 to the variable x.
+= (Addition Assignment)Adds the value on the right to the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
-= (Subtraction Assignment)Subtracts the value on the right from the current value of the variable on the left and assigns the result to the variable.  is equivalent to 
*= (Multiplication Assignment)Multiplies the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
/= (Division Assignment)Divides the current value of the variable on the left by the value on the right and assigns the result to the variable.  is equivalent to 
%= (Modulo Assignment)Calculates the modulo of the current value of the variable on the left and the value on the right, then assigns the result to the variable.  is equivalent to 

Assignment Operators in C:

Here are the implementation of Assignment Operator in C language:

Assignment Operators in C++:

Here are the implementation of Assignment Operator in C++ language:

Assignment Operators in Java:

Here are the implementation of Assignment Operator in java language:

Assignment Operators in Python:

Here are the implementation of Assignment Operator in python language:

Assignment Operators in C#:

Here are the implementation of Assignment Operator in C# language:

Assignment Operators in Javascript:

Here are the implementation of Assignment Operator in javascript language:

Application of Assignment Operators:

  • Variable Initialization : Setting initial values to variables during declaration.
  • Mathematical Operations : Combining arithmetic operations with assignment to update variable values.
  • Loop Control : Updating loop variables to control loop iterations.
  • Conditional Statements : Assigning different values based on conditions in conditional statements.
  • Function Return Values : Storing the return values of functions in variables.
  • Data Manipulation : Assigning values received from user input or retrieved from databases to variables.

Conclusion:

In conclusion, assignment operators in programming are essential tools for assigning values to variables and performing operations in a concise and efficient manner. They allow programmers to manipulate data and control the flow of their programs effectively. Understanding and using assignment operators correctly is fundamental to writing clear, efficient, and maintainable code in various programming languages.

Please Login to comment...

Similar reads.

  • Programming
  • How to Delete Discord Servers: Step by Step Guide
  • Google increases YouTube Premium price in India: Check our the latest plans
  • California Lawmakers Pass Bill to Limit AI Replicas
  • Best 10 IPTV Service Providers in Germany
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Javatpoint Logo

Java Tutorial

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

JavaTpoint

Every local variable and the final blank field will have an assigned value when any value is accessed. Access to the value will consist of the variable's name or an area that occurs in an expression, except in the left-hand operand of the assignment operator, "=".

To access a local variable or final blank field x, this "x" must be assigned definitely before accessing it or else a compile-time error will occur.

In the same way, every final blank variable will be assigned once and unassigned if an assignment to it occurs.

So, that kind of assignment is defined to occur only if the variable's name had happened on the left-hand side of an assignment operator.

When the assignment is done to a final blank variable, that variable should not get assigned previously before this assignment or else a compile-time error will arise.

The main idea behind this definite assignment is that the local variable assignment or final blank field will occur on each possible execution path for the access.

So that the analysis will take into account the structure of expressions and statements, and it will provide immediate treatment of the operators in an expression like &&, !, ||,? : and also boolean-valued constant expressions.

There is an exception for the treatment with conditional boolean operators like &&, ||, and ?: and also with boolean-valued constant expressions, and the values of the expressions are not considered in the flow analysis.

Let us discuss this with an example.

The Java compiler will decide that "k" is assigned before its access, like an argument with the method invocation in the code.

It is because the access will occur if the value of the expression is accurate. That value is valid only if the assignment to the "k" is executed and more adequately evaluated. The expression is given below:

And similarly, a Java compiler will recognize that in the above code, the variable "k" is definitely assigned to the while statement because the conditional expression "TRUE" will never have the value "FALSE". The break statement only will cause the while statement to compile as usual, and variable "k" is definitely assigned before the break statement.

And also, on the other hand,

The Java compiler will reject the above code because, in the above case, the while statement is not correct to execute its body only if we consider the rules of definite assignment.

The Java compiler will produce a compile-time error for the above code even though the "n" value is known at the compilation time. In the rule, it can be known at the time of compilation that the assignment to the value "k" always be executed and, more appropriately, it will execute.

The Java compiler must follow the rules we discussed above. The constant expressions only follow the rules, and in the above example, the constant expression, n > 2, is not a constant expression.

We will discuss another example of the Java compiler will accept the code:

As far as we consider the definite assignment of "k" because the rules are broken in the above, and we are allowed to say that "k" is assigned whether th value of the flag is true or false.

The rules will not accept the above variation, and the program will get the compile time error.

The Java compiler will accept the code until a definite unassignment of "k" is concerned, and the rules crossed in this will allow it to tell that "k" is assigned only once, like nothing matters if it is true or false.

The rules will not accept the variation, but when we compile the above program, it gets the compile-time error.

For specifying the steps of definite assignment, these rules will define many technical terms:

In the case of Boolean-valued expressions, the last two steps in the above are redirected into four points:

From the above, the true and false will refer to the value of the expression.

Let us take an example.

The local variable "k" is definitely assigned to a value after evaluating the expression above only if the above expression is true and not when the expression is false. If "a" is false, then the assignment for the "K" is not executed correctly or evaluated.

Let us consider the statement "V is definitely assigned after X", "V" is the local variable and "X" is the expression or statement. The statement says that "V" is definitely assigned after "X" if "X" completes its functioning usually. Suppose "X" has been completed in the wrong way, and the rules are defined for taking into consideration.

The different situation of the above expression is that "V is definitely assigned after the break," and it is always true because we know that the break statement will not usually be complete. It is true that "V" had not assigned the value of the break statement that usually completes them.

The abbreviation "iff" is used as "if and only if" to shorten the rules. We can also use another acronym, like if a rule may contain one or more occurrences of "unassigned", then it performs two rules:

Let us take an example.

The above statement is understood by two rules given below:

Above all are equivalent to saying that "V" is unassigned or assigned after "e" iff "V" is unassigned or assigned before "e".

It is because of the constant expression where the value is true and never had the value as false and the constant expression where the value is false and never had the value true, and the above two rules are satisfied.

Let us assume that b and c are boolean-valued expressions.

Let us assume that "e" is an expression of boolean type, not a logical complement expression, and not a boolean constant expression! a, not a conditional-and expression a&&b, not a conditional-or expression a||b, or not a conditional expression a ? b:c.

Let us consider an assignment expression a=b, a+=b, a%=b, a|=b, a^=b, a*=b, a-=b, a>>=b, a<<=b and many more.

As we include the disjunction, "a is V" will not affect the binary decision to ensure whether a program is acceptable or will result in a compile-time error. It will affect how many different points are in the code and is regarded as erroneous, so when practising, it will improve the quality of error reporting. So, a similar remark will apply to the inclusion of the conjunction "a is V" in rule one for definite unassignment, as stated above.

Let us assume that expression is not a boolean constant expression, and also not a pre-increment expression ++a, not a pre-decrement expression --a, not a post-increment a++, not a post decrement expression a--, not a logical complement expression ! a, not a conditional-and expression a&&b, not a conditional-or expression a||b, not a conditional expression a? b:c, not an assignment expression, or lambda expression, then we must follow the following rules:

If an expression has no sub-expressions, then "V" is unassigned or assigned after the expression if and only if "V" is unassigned or assigned before the expression.

In the above case, it will apply to literals, names, this (both qualified and unqualified), unqualified class instance creation expressions with no arguments, array creation expressions with initializers that will contain no expressions, superclass field access expressions, unqualified and type-qualified method invocation expressions with no arguments, superclass method invocation expressions with no arguments, and superclass and type-qualified method reference expressions.

If an expression has sub-expressions, "V" is unassigned or assigned after the expression if and only if "V" is unassigned or assigned after its rightmost immediate sub-expression.

There is a piece of subtle reasoning behind the assertion that a variable "V" can be known to be definitely unassigned after a method invocation expression. It will be taken by itself, at face value, and without qualification; such an assertion will not always true because the invoked method will perform assignments. It must remember that for the Java programming languages, the concept of the definite assignment will be applied only to final blank variables.

If "V" is a blank final local variable, then only the method to which its declaration belongs will perform assignments to "V". If "V" is a final blank field, then only a constructor or an initializer for the class containing the declaration for "V", and can perform assignments to "V". At last, explicit constructor invocations are handled specially, even though they are syntactically same to expressions that containing method invocations. They are not expression statements, and finally, the rules in this section do not apply to explicit constructor invocations.

Suppose an expression is a lambda expression, and the following rules will apply:

There are no rules that "V" is to be definitely unassigned before a lambda body. The variable that is definitely unassigned before the lambda body will be later assigned to it. So, we cannot examine whether the variables should be assigned when the body is executed.

For any immediate subexpression, "y" of an expression "x", where "x" is not a lambda expression, "V" is unassigned or assigned before "y" if and only if any one of the following is true.

There are some rules to apply for a statement if (e) S. They are:

There are some rules to apply for a statement if (e) S else T. They are:

There are some rules to apply to both a statement assert e1 and to the statement assert e1: e2.

There is a rule to apply for a statement asserting e1: e2. That is:

"V" will assign or unassign only after a switch statement if and only if all of the below statements are true:





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

logo

Object-Oriented Programming in Java – A Beginner‘s Guide

' data-src=

As a full-stack and Java developer, I often leverage object-oriented programming to build scalable, maintainable applications. OOP is fundamental for any intermediate or advanced Java programmer.

In this expanded 2600+ word guide for beginners, we‘ll dig deeper into:

  • Core OOP concepts like classes, objects, inheritance, encapsulation
  • How OOP contrasts with procedural programming
  • Benefits of object-oriented design and programming
  • Practical use cases and Java code examples
  • Trends and statistics on OOP adoption

We‘ll also address:

  • Common mistakes Java beginners make with OOP
  • Best practices from real-world OOP projects
  • How to put concepts into action

Let‘s start with the basics…

What is Object-Oriented Programming?

Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc. in programming. The main goal of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.

Some key benefits of OOP include:

  • Modularity: OOP allows developers to create modular programs and libraries that can be easily reused and expanded
  • Encapsulation: Objects can store data and implementation details privately, exposing only a public interface to users of the code
  • Maintainability: Code structured around objects and classes is easier to understand and maintain
  • Pluggability and debugging ease: Objects can be easily "plugged into" an application with minimal effort
  • Code reusability: Significant code reuse through inheritance and composition

OOP Usage Statistics

The immense benefits of OOP are clear based on usage alone. A Cloud Report survey in 2020 showed the following adoption rates:

Language% Using OOP
Java94%
C#81%
Python63%

As you can see, OOP dominates modern software development, especially in Java.

Now let‘s explore some of the key principles powering this paradigm.

Core OOP Concepts in Java

Some of the major Object Oriented Programming concepts in Java are:

Classes and Objects

Classes are user-defined data types that act as the blueprint for individual objects, attributes and methods. They are one of the main building blocks of Java OOP.

For example:

The Bicycle class above declares two fields ( gear , speed ) representing object state, along with methods modifying that state.

We can then instantiate individual objects, or instances , of this class like so:

Here we‘ve used the Bicycle class as a blueprint for bike1 .

The new keyword initializes the object. And we directly access fields and methods defined in its class.

As another example, we could model a bank account:

This allows us to represent real-world entities in code.

Inheritance

Inheritance allows classes to inherit properties and behaviors from parent classes. Inheriting classes are called subclasses , while parent classes are called superclasses .

Here Bicycle inherits from the parent Vehicle class, gaining access to behaviors like honkHorn() . It specializes the parent by defining its own ringBell() method.

This hierarchy allows related classes to reuse code and properties. Abstract classes can also define incomplete functionality for child classes to implement.

Benefits include:

  • Reduced duplication: Child classes acquire fields and methods of parent classes
  • Reusability: Common logic can be reused rather than redefined
  • Extensibility: Child classes can override, extend, and diversify functionality

This makes building hierarchies of related classes simple and practical.

Encapsulation

Encapsulation refers binding together data and behavior within a single unit, while hiding internal implementation details from users.

In Java, we control encapsulation using the following access modifiers:

  • public – accessible from everywhere
  • private – only accessible within class
  • protected – accessible within class and subclasses
  • (no modifier) package-private – accessible within package

Now code outside of BankAccount can‘t directly access its data. But it can indirectly interact using public methods.

This helps developers:

  • Control data validation and constraints
  • Prevent external state manipulation in unanticipated ways
  • Refactor code without impacting users

Appropriate encapsulation is key for building robust, modular software systems.

Abstraction

Abstraction focuses on essential qualities and behaviors, hiding the underlying implementation details from users. This helps reduce complexity and increase efficiency.

In Java, abstraction allows separation of what functionality subclasses should have from how they implement it.

  • Abstract classes – declare incomplete method signatures for child classes to implement
  • Interfaces – blueprint unrelated classes must follow

Any class implementing the Animal interface must contain the makeSound() method. This enforces a certain API structure across unique, unrelated classes.

Meanwhile abstract classes provide skeleton components for subclasses:

This defines common functionality child classes can inherit or override.

Appropriate abstraction helps developers:

  • Improve structural consistency across classes
  • Reduce duplication
  • Increase flexibility
  • Focus on essential class functionality

There are a couple other OOP principles like polymorphism worth covering, but these are the major concepts for grasping object-oriented programming in Java.

OOP vs Procedural Programming

Let‘s compare and contrast object-oriented programming with the older procedural style:

Procedural Programming

Procedural programming structures code into a series of procedures, subroutines, or functions.

For example :

Data and behaviors are decoupled. Code is segmented into procedures that transform input data into specific outputs.

Programs execute through a series of stateless function calls.

IssueProcedural ProgrammingObject-Oriented Programming
StructureProcedures and functionsObjects and classes
StateStatelessStateful objects
ExtensibilityLimited due to lack of polymorphismExcellent due to inheritance
Data PrivacyNo encapsulation mechanismStrict encapsulation

In summary – procedural programming scales poorly because code reuse requires explicit planning and up front design around functions. OOP provides tools like inheritance and polymorphism that empower implicit code reuse.

Combined with information hiding, OOP makes developing, maintaining and upgrading complex systems much simpler over longer application lifetimes.

No wonder object-oriented programming has largely superseded older procedural languages.

Why Use OOP Java?

We‘ve covered OOP theory and core concepts integral to learning Java. Now let‘s discuss practical use cases.

Java powers a tremendous variety of software applications thanks to OOP design principles and tools like:

1. Code Reuse

  • Inheritance facilitates reusable behaviors shared across class hierarchies
  • Interfaces and abstract classes encourage reusable architectural patterns

This dramatically cuts development time.

2. Real-World Modeling

  • Classes directly map to real-life objects
  • Relationships mimic tangible hierarchies
  • Application workflow mirrors actual business processes

Resulting in intuitive code and simpler visualizations.

3. Pluggability and Debugging

  • Loose class coupling enables simple integration
  • Bugs isolated to specific objects

Allowing complex programs to grow steadily.

4. Collaborative Development

  • Well-defined public APIs help teams coordinate
  • Encapsulation reduces software conflicts
  • Polymorphic code is extremely adaptive but also brittle when contracts between classes are broken

Enforcing discipline for large projects.

Let‘s look at a simple example demonstrating these advantages:

Without OOP

Procedural approach stores data globally. Function relies on external state.

Encapsulates data and couples it to behaviors operating on that data. Localized functionality promotes reuse while limiting external dependencies.

This OOP design is easier to extend, reuse, debug and manage.

Java was designed from the ground up as a pure OOP language to facilitate these benefits compared to hybrid languages like C++.

Common Mistakes

While Java provides excellent OOP support, misusing these tools can undermine your code.

Here are some common OOP anti-patterns Java beginners should avoid:

  • Inheritance abuse – Base classes shouldn‘t know specifics of child classes. Avoid tight coupling.
  • Excess abstraction – Don‘t abstract for the sake of abstraction. Let requirements dictate abstractions.
  • Incomplete encapsulation – Apply encapsulation universally and limit internal data leaks. Enforce invariants internally.
  • Broken modularity – Clearly define responsibilities between objects to maximize cohesion within classes and avoid god classes/objects
  • Overengineering – Don‘t misapply OOP principles without purpose. Let business needs determine optimal granularity.

Adhering to core OOP principles without overdoing things minimizes these issues.

Best Practices

When leveraging OOP for new Java projects, keep these best practices in mind:

  • Favor composition over inheritance – Has-a relationships are more flexible than is-a
  • Program to interfaces – Code against abstract interfaces for maximum interoperability
  • Follow Law of Demeter – Only talk to friends (immediate relationships), not strangers
  • Single Responsibility Principle – Classes should have one job
  • Open/Closed Principle – Open for extension but closed for modification
  • Don‘t Repeat Yourself Principle – Code duplication = bad

These guidelines help avoid tight coupling and technical debt accrual over long development cycles.

Adopting them leads naturally from sound OOP foundations.

Putting Concepts Into Action

We‘ve covered a lot of conceptual ground on core OOP principles. Let‘s tie it all together by outlining the typical process for applying object-oriented programming in Java:

1. Identify Objects

Analyze requirements/constraints and map nouns to potential objects with attributes and behaviors. This forms the basis for realizing use cases.

2. Define Relationships

Determine how mapped objects interact with one another. Structure logically related objects into clean inheritance hierarchies.

3. Establish Behaviors

Determine which behaviors are common across objects vs specific to child classes. Define public interfaces.

4. Assign Attributes

Map identified attributes to appropriate objects. Encapsulate them privately with getters/setters.

Once models are fleshed out, implementing everything codewise is straightforward:

  • Classes translate to code definitions
  • Objects become instantiations
  • Methods implement behaviors for data manipulation
  • Visibility controls access

By correctly applying OOP processes upfront, programming efforts flow naturally.

The key OOP takeaways are:

  • Object-oriented programming structures code around object data rather than functions
  • Major OOP concepts in Java: classes, objects, inheritance, encapsulation, abstraction
  • Mastering these core principles with languages like Java enables cleaner, modular software
  • Hierarchies, polymorphism and information hiding facilitate reuse and extendibility
  • Java was designed from the ground up around OOP

This guide explored the OOP paradigm in depth using targeted Java examples. We covered:

  • OOP basics and principles
  • Contrasts with older procedural programming
  • Real-life use cases
  • Common missteps to avoid
  • Best practices to follow
  • Converting concepts to code

I hope this expanded overview gives you a solid foundation for applying object-oriented programming techniques in Java. Let me know in the comments if you have any other topics you want covered or feedback on the post!

' data-src=

Dr. Alex Mitchell is a dedicated coding instructor with a deep passion for teaching and a wealth of experience in computer science education. As a university professor, Dr. Mitchell has played a pivotal role in shaping the coding skills of countless students, helping them navigate the intricate world of programming languages and software development.

Beyond the classroom, Dr. Mitchell is an active contributor to the freeCodeCamp community, where he regularly shares his expertise through tutorials, code examples, and practical insights. His teaching repertoire includes a wide range of languages and frameworks, such as Python, JavaScript, Next.js, and React, which he presents in an accessible and engaging manner.

Dr. Mitchell’s approach to teaching blends academic rigor with real-world applications, ensuring that his students not only understand the theory but also how to apply it effectively. His commitment to education and his ability to simplify complex topics have made him a respected figure in both the university and online learning communities.

Similar Posts

What is Container Orchestration? How to Manage your Containers with MicroK8s

What is Container Orchestration? How to Manage your Containers with MicroK8s

Container orchestration has become an essential part of managing containerized applications. As applications grow to use…

Windows vs MacOS vs Linux – Operating System Handbook

Windows vs MacOS vs Linux – Operating System Handbook

Operating systems form the core foundation of how we interact with computers. The "big three" OSs…

A poet‘s introduction to web development

A poet‘s introduction to web development

As a poet with an interest in technology‘s creative possibilities, I set out to pull back…

Learn NestJS by Building a CRUD API

Learn NestJS by Building a CRUD API

NestJS has quickly become one of the most popular frameworks for building scalable, production-ready Node.js applications….

Mastering LINQ: Unlock the Power of Advanced C# Data Manipulation

Mastering LINQ: Unlock the Power of Advanced C# Data Manipulation

LINQ (Language Integrated Query) is one of the most useful features for data manipulation introduced in…

How to Build Your Developer Résumé Without Job Experience

How to Build Your Developer Résumé Without Job Experience

Getting your first full-time developer job is widely recognized as one of the biggest hurdles for…

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Java Operators : |= bitwise OR and assign example [duplicate]

I just going through code someone has written and I saw |= usage, looking up on Java operators, it suggests bitwise or and assign operation, can anyone explain and give me an example of it?

Here is the code that read it:

  • bit-manipulation
  • variable-assignment

Chris Chambers's user avatar

  • Could you show us the code you read? –  talnicolas Commented Apr 13, 2012 at 13:49
  • @talnicolas: updated question with code . –  Rachel Commented Apr 13, 2012 at 13:50
  • What is the type of matches ? int or boolean ? –  adranale Commented Apr 13, 2012 at 13:51
  • see my answer, probably bitwise-or is not meant at all here! –  adranale Commented Apr 13, 2012 at 13:56

6 Answers 6

is the same as

It calculates the bitwise OR of the two operands, and assigns the result to the left operand.

To explain your example code:

I presume matches is a boolean ; this means that the bitwise operators behave the same as logical operators.

On each iteration of the loop, it OR s the current value of matches with whatever is returned from field.contains() . This has the effect of setting it to true if it was already true, or if field.contains() returns true.

So, it calculates if any of the calls to field.contains() , throughout the entire loop, has returned true .

Graham Borland's user avatar

  • can you put in some values for a and b? –  Rachel Commented Apr 13, 2012 at 13:51
  • oh ok, now it make some sense –  Rachel Commented Apr 13, 2012 at 13:57
  • "this means that the bitwise operators behave the same as logical operators". Actually, logical operators will short-circuit. Short circuiting is probably desired here. –  smp7d Commented Apr 13, 2012 at 14:13
  • 3 It should also be noted that if contains() has no side-effects, this is rather inefficient. Adding at least an if (matches) { break; } inside the loop would be so much nicer... (Although I suppose getValue() may be returning so few searches that it won't make a noticeable difference...) –  Izkata Commented Apr 13, 2012 at 18:03

a |= b is the same as a = (a | b)

Boolean Variables

In a boolean context, it means:

that is, if b is true then a will be true, otherwise a will be unmodified.

Bitwise Operations

In a bit wise context it means that every binary bit that's set in b will become set in a . Bits that are clear in b will be unmodified in a .

So if bit 0 is set in b , it'll also become set in a , per the example below:

This will set the bottom bit of an integer:

This will clear the bottom bit:

a &= ~0x01

This will toggle the bottom bit:

Alnitak's user avatar

  • can put in some number values for a and explain the detail ooperation. –  Rachel Commented Apr 13, 2012 at 13:52

is equivalent to this code:

Similarly, this code:

is equivalent to this one:

In the first example, a bit-wise OR is being performed. In the second example, a boolean OR is performed.

Óscar López's user avatar

a |= b is the same as a = a | b

a | b is a bitwise operator if both operands are integral types (int, short, etc...). If both operands are booleans, then its is a boolean or.

When both a and b are booleans, the difference between a | b and a || b is that in the first, both sides are always evaluated, in the later b is only evaluated if a is false. It is sort of a "shortcut" operator.

This is useful for situations like this:

On the other hand, || actually is implemented as another conditional jump in the bytecode/machine-code. In some cases, it may be faster to evaluate boolean conditions using the | operator to avoid the additional jump (and thus branch predition, etc...). Definitely something for low-level micro-benchmarking to figure out which is better (and usually not important in most applications).

When you do a |= b you are always evaluating both a and b . It doesn't really make sense to have an a ||= b operators, since the equivalent a = a || b would translate to:

...due to the conditional nature of || evaluation. In other words, b would not be evaluated if a was already true.

ɲeuroburɳ's user avatar

Could it be possible that the code has a bug and it was meant

matches = matches || field.contains(search);

so that matches should be true if at least one field contains the search variable?

adranale's user avatar

  • 2 your code is not functionally the same - if matches is already true then the short circuit operator will prevent evaluation of field.contains(search) . AFAIK the |= operator won't do that. –  Alnitak Commented Apr 13, 2012 at 14:05
  • Which means my code is optimization of the original code –  adranale Commented Apr 13, 2012 at 14:06
  • 1 only if it's truly intended that .contains() is not called in those circumstances. –  Alnitak Commented Apr 13, 2012 at 14:07
  • 1 you mean if the .contains() method does not have side-effects –  adranale Commented Apr 13, 2012 at 14:14
  • 1 yeah, mostly - in this case it probably doesn't matter, but it's worth knowing that for boolean variables a |= func() is the same as a = a | func() which is not functionally the same as a = a || func() , even though the end result on a is the same. –  Alnitak Commented Apr 13, 2012 at 16:26

That code snippet is a poor example of when to use that operator. Honestly I can't think of a great example of when to use this operator, but here's my best attempt:

Note: You need 3 ifs because otherwise you could just do somethingIsTrue | testSomethingElseTrue() for the second if.

In case you were wondering why you shouldn't use the operator in the first example, here's why:

From a performance standpoint, it is poor because it does a compare and an assign for each loop instead of just a compare. Also, it continues iterating even when future iterations will have no effect (once matches gets set to true it will not change, and String.contains has no side effects).

It is also poor from a readability standpoint, based solely on the existence of this question ;)

Thus, in place of that snippet I'd go for:

On a side note, it seems to me like the original coder might have been playing a bit too much code-golf when (s)he wrote this :)

Community's user avatar

  • There are many good use cases for this operator. Imagine methods like addAll or removeAll in a set, provided that you iterate over the collection in parameter. You add or remove in a loop, and you want to return true if you actually added or removed at least one entry. –  Vlasec Commented Nov 24, 2019 at 21:45

Not the answer you're looking for? Browse other questions tagged java operators bit-manipulation variable-assignment or ask your own question .

  • The Overflow Blog
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Is this a 'standard' elliptic integral?
  • How to vertically displace a word in a sentence?
  • Reference request: locally erasable delta-functor is universal
  • Why is there an "unnamed volcano" in Syria?
  • Why is GParted distributed as an ISO image? Is it to accommodate Linux needs as well as Windows needs?
  • How much easier/harder would it be to colonize space if humans found a method of giving ourselves bodies that could survive in almost anything?
  • Is it a date format of YYMMDD, MMDDYY, and/or DDMMYY?
  • Libreoffice printing is always in landscape format
  • What rules of legal ethics apply to information a lawyer learns during a consultation?
  • Is a company liable for "potential" harms?
  • Can it be acceptable to take over CTRL + F shortcut in web app
  • Compactly supported wave packet in Schrödinger's evolution
  • A classic problem about matrix
  • How do I define the solution to an inequality?
  • What is happening when a TV satellite stops broadcasting during an "eclipse"?
  • Why does my passive IR occupancy sensor switch react to a nearby WiFi access point?
  • Self-descriptive
  • Not a cross, not a word (number crossword)
  • decode the pipe
  • Does an airplane fly less or more efficiently after an mid-flight engine failure?
  • Is consciousness a prerequisite for knowledge?
  • Replace a string in a script without modifying the file, and then to execute it
  • Can we idiomatically say "Jack is an ordered person" to mean he is an organized person?
  • What did Wittgenstein mean by ”contradiction is the outer limit of propositions”?

java assignment definition

IMAGES

  1. Java Assignment Operators

    java assignment definition

  2. Java Assignment Operators with Examples

    java assignment definition

  3. VARIOUS TOPICS IN JAVA. Firstly, the definition of java

    java assignment definition

  4. Assignment Operators in Java

    java assignment definition

  5. Java 1

    java assignment definition

  6. Java Assignment Operators

    java assignment definition

VIDEO

  1. JAVA Assignment Operators

  2. Java Practice Assignment 5

  3. #20. Assignment Operators in Java

  4. Core

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

  6. Java Assignment Operator in Arabic || عامل التعيين في الجافا

COMMENTS

  1. Java Assignment Operators with Examples

    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.

  2. Java: define terms initialization, declaration and assignment

    assignment: throwing away the old value of a variable and replacing it with a new one. initialization: it's a special kind of assignment: the first.Before initialization objects have null value and primitive types have default values such as 0 or false.Can be done in conjunction with declaration. declaration: a declaration states the type of a variable, along with its name.

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

    This beginner Java tutorial describes fundamentals of programming in the Java programming language ... 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: ...

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

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

  6. Types of Assignment Operators in Java

    To assign a value to a variable, use the basic assignment operator (=). It is the most fundamental assignment operator in Java. It assigns the value on the right side of the operator to the variable on the left side. Example: int x = 10; int x = 10; In the above example, the variable x is assigned the value 10.

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

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

  10. Java 8

    Assignment Operators Overview Top. The single equal sign = is used for assignment in Java and we have been using this throughout the lessons so far. This operator is fairly self explanatory and takes the form variable = expression; . A point to note here is that the type of variable must be compatible with the type of expression.

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

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

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

  13. 1.7 Java

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

  14. What Is an Assignment Statement in Java?

    Assignment. Assignment in Java is the process of giving a value to a primitive-type variable or giving an object reference to an object-type variable. The equals sign acts as assignment operator in Java, followed by the value to assign. The following sample Java code demonstrates assigning a value to a primitive-type integer variable, which has ...

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

  16. Operators in Java

    The general format of the assignment operator is: variable = value;. In many cases, the assignment operator can be combined with other operators to build a shorter version of the statement called a Compound Statement.For example, instead of a = a+5, we can write a += 5. +=, for adding the left operand with the right operand and then assigning it to the variable on the left.

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

  18. Java: Assignment Operators

    This lesson will define the Java assignment operators and provide code examples of the operators in action. Create an account Table of Contents. Assignment Operators; General Assignment: Addition ...

  19. Assignment Operators in Programming

    Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...

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

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

  21. Definite Assignment in Java

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

  22. Object-Oriented Programming in Java

    Classes and Objects. Classes are user-defined data types that act as the blueprint for individual objects, attributes and methods. They are one of the main building blocks of Java OOP. For example: public class Bicycle { //fields private int gear; private int speed; //methods public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } }

  23. Java Operators : |= bitwise OR and assign example

    a |= b; is the same as. a = (a | b); It calculates the bitwise OR of the two operands, and assigns the result to the left operand. To explain your example code: for (String search : textSearch.getValue()) matches |= field.contains(search); I presume matches is a boolean; this means that the bitwise operators behave the same as logical operators.