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

Static Final Variables in Java

Last updated: March 17, 2024

assignment to itself java

  • Java Keyword

announcement - icon

It's finally here:

>> The Road to Membership and Baeldung Pro .

Going into ads, no-ads reading , and bit about how Baeldung works if you're curious :)

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page .

You can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Java applications have a notoriously slow startup and a long warmup time. The CRaC (Coordinated Restore at Checkpoint) project from OpenJDK can help improve these issues by creating a checkpoint with an application's peak performance and restoring an instance of the JVM to that point.

To take full advantage of this feature, BellSoft provides containers that are highly optimized for Java applications. These package Alpaquita Linux (a full-featured OS optimized for Java and cloud environment) and Liberica JDK (an open-source Java runtime based on OpenJDK).

These ready-to-use images allow us to easily integrate CRaC in a Spring Boot application:

Improve Java application performance with CRaC support

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page .

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page .

Whether you're just starting out or have years of experience, Spring Boot is obviously a great choice for building a web application.

Jmix builds on this highly powerful and mature Boot stack, allowing devs to build and deliver full-stack web applications without having to code the frontend. Quite flexibly as well, from simple web GUI CRUD applications to complex enterprise solutions.

Concretely, The Jmix Platform includes a framework built on top of Spring Boot, JPA, and Vaadin , and comes with Jmix Studio, an IntelliJ IDEA plugin equipped with a suite of developer productivity tools.

The platform comes with interconnected out-of-the-box add-ons for report generation, BPM, maps, instant web app generation from a DB, and quite a bit more:

>> Become an efficient full-stack developer with Jmix

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

Download the E-book

Do JSON right with Jackson

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Working on getting your persistence layer right with Spring?

Explore the eBook

Building a REST API with Spring?

Get started with Spring and Spring Boot, through the Learn Spring course:

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

1. Overview

Simply put, static final variables, also called constants , are key features in Java to create a class variable that won’t change after initialization . However, in the case of a static final object reference, the state of the object may change.

In this tutorial, we’ll learn how to declare and initialize constant variables. Also, we’ll discuss their usefulness.

2. static final Variables

The static keyword associates a variable to a class itself, not to instances of the class.

Furthermore, the final keyword makes a variable immutable. Its value can’t change after initialization.

The combination of the two keywords helps create a constant. They are mostly named using uppercase and underscores to separate words .

2.1. Initializing static final Variables

Here’s an example of how to declare a static final field and assign a value:

Here, we create a class named Bike  with a constant class variable named TIRE and initialize it to two.

Alternatively, we can initialize the variable via a static initializer block:

This will compile without an error:

Here are some key rules for constant variables:

  • We must initialize upon declaration or in a static initializer block
  • We can’t reassign it after initialization

Attempting to initialize it outside the initialization scope will cause an exception.

Also, we can’t initialize it via the constructor because constructors are invoked when we create an instance of a class. Static variables belong to the class itself and not to individual instances .

2.2. static   final  Objects

We can also create static final object references:

Since the PART reference is constant, it can’t be reassigned:

The code above throws an exception because we assign a new reference to an immutable variable.

However, we can modify the state of the object:

Here, we can change the value of the seat  despite setting it to one initially. We mutate the contents of PART  despite being a constant reference. Only the reference itself is immutable.

Notably, the final  keyword only makes primitive types, String , and other immutable types constant. In the case of an object, it only makes the reference constant, but the state of the object can be altered .

3. Why Constants Are Useful

Using static final variables has several advantages. It provides better performance since its values are inlined at compile time instead of a runtime value lookup .

Moreover, declaring reusable values as constant avoids duplicating literals. Constant can be reused anywhere in the code, depending on the access modifier . A constant with a private access modifier will only be usable within the class.

Additionally, a static final variable of primitive or String type is thread-safe. Its value remains unchanged when shared among multiple threads.

Finally, giving semantic names to constant values increases code readability. Also, it makes code self-documenting. For example, the  java.math package provides constants like PI :

The  Math.PI  encapsulates the mathematical constant value in a reusable way.

4. Conclusion

In this article, we learned how to declare and initialize a constant variable. Also, we highlighted some of its use cases.

A final static variable defines a class-level constant. However, a  static final object may still be mutable, even if the reference can’t change.

As always, the complete source code for the examples is available over on GitHub .

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode , for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

RWS Course Banner

Javatpoint Logo

Java Tutorial

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

JavaTpoint

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.

In this section, we will look at Java's many types of assignment operators, how they function, and how they are utilized.

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.

In the above example, the variable x is assigned the value 10.

To add a value to a variable and subsequently assign the new value to the same variable, use the addition assignment operator (+=). It takes the value on the right side of the operator, adds it to the variable's existing value on the left side, and then assigns the new value to the variable.

To subtract one numeric number from another, use the subtraction operator. All numeric data types, including integers and floating-point values, can be utilised with it. Here's an illustration:

In this example, we create two integer variables, a and b, subtract b from a, and then assign the result to the variable c.

To combine two numerical numbers, use the multiplication operator. All numeric data types, including integers and floating-point values, can be utilised with it. Here's an illustration:

In this example, we declare two integer variables, a and b, multiply their values using the multiplication operator, and then assign the outcome to the third variable, c.

To divide one numerical number by another, use the division operator. All numeric data types, including integers and floating-point values, can be utilised with it. Here's an illustration:

In this example, we declare two integer variables, a and b, divide them by one another using the division operator, and then assign the outcome to the variable c.

It's vital to remember that when two numbers are divided, the outcome will also be an integer, and any residual will be thrown away. For instance:

The modulus assignment operator (%=) computes the remainder of a variable divided by a value and then assigns the resulting value to the same variable. It takes the value on the right side of the operator, divides it by the current value of the variable on the left side, and then assigns the new value to the variable on the left side.





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

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

Assignment, Arithmetic, and Unary Operators

The simple assignment operator.

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

This operator can also be used on objects to assign object references , as discussed in Creating Objects .

The Arithmetic Operators

The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is " % ", which divides one operand by another and returns the remainder as its result.

Operator Description
Additive operator (also used for String concatenation)
Subtraction operator
Multiplication operator
Division operator
Remainder operator

The following program, ArithmeticDemo , tests the arithmetic operators.

This program prints the following:

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

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

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

The Unary Operators

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

Operator Description
Unary plus operator; indicates positive value (numbers are positive without this, however)
Unary minus operator; negates an expression
Increment operator; increments a value by 1
Decrement operator; decrements a value by 1
Logical complement operator; inverts the value of a boolean

The following program, UnaryDemo , tests the unary operators:

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

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

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

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

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.

Operator Example Same As
= a = 10 a = 10
+= a += 5 a = a + 5
-= a -= 3 a = a - 3
*= a *= 6 a = a * 6
/= a /= 5 a = a / 5
%= a %= 7 a = a % 7
&= a &= 3 a = a & 3
|= a |= 3 a = a | 3
^= a ^= 2 a = a ^ 2
>>= a >>= 3 a = a >> 3
>>>= a >>>= 3 a = a >>> 3
<<= a <<= 2 a = a << 2

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

  • C Programming
  • Java Programming
  • Data Structures
  • Web Development
  • Tech Interview

Java's Basic and Shorthand Assignment Operators

Reference assignment, primitive assignment, primitive casting, shorthand assignment operators, basic assignment operator.

Java's basic assignment operator is a single equals-to (=) sign that assigns the right-hand side value to the left-hand side operand. On left side of the assignment operator there must be a variable that can hold the value assigned to it. Assignment operator operates on both primitive and reference types. It has the following syntax: var = expression; Note that the type of var must be compatible with the type of expression .

Chaining of assignment operator is also possible where we can create a chain of assignments in order to assign a single value to multiple variables. For example,

The above piece of code sets the variables x, y, and z to 100 using a single statement. This works because the = is an operator that yields the value of the right-hand expression. Thus, the value of z = 100 is 100, which is then assigned to y , which in turn is assigned to x . Using a "chain of assignment" is an easy way to set a group of variables to a common value.

A variable referring to an object is a reference variable not an object. We can assign a newly created object to an object reference variable as follows:

The above line of code performs three tasks

  • Creates a reference variable named st1 , of type Student .
  • Creates a new Student object on the heap.
  • Assigns the newly created Student object to the reference variable st1

We can also assign null to an object reference variable, which simply means the variable is not referring to any object:

Above line of code creates space for the Student reference variable st2 but doesn't create an actual Student object.

Note that, we can also use a reference variable to refer to any object that is a subclass of the declared reference variable type.

Primitive variables can be assigned either by using a literal or the result of an expression. For example,

The most important point that we should keep in mind, while assigning primitive types is if we are going to assign a bigger value to a smaller type, we have to typecast it properly. In Above piece of code the literal integer 130 is implicitly an int but it is acceptable here because the variable x is of type int . It gets weird if you try 130 to assign to a byte variable. For example, The below piece of code will not compile because literal 130 is implicitly an integer and it does not fit into a smaller type byte x . Likewise, byte c = a + b will also not compile because the result of an expression involving anything int-sized or smaller is always an int .

Casting lets us convert primitive values from one type to another (specially from bigger to smaller types). Casts can be implicit or explicit. An implicit cast means we don't have to write code for the cast; the conversion happens automatically. Typically, an implicit cast happens when we do a widening conversion. In other words, putting a smaller thing (say, a byte ) into a bigger container (like an int ). Remember those "possible loss of precision" compiler errors we saw during assignments. Those happened when we tried to put a larger thing (say, an int ) into a smaller container (like a byte ). The large-value-into-small-container conversion is referred to as narrowing and requires an explicit cast, where we tell the compiler that we are aware of the danger and accept full responsibility.

As a final note on casting, it is very important to note that the shorthand assignment operators let us perform addition, subtraction, multiplication or division without putting in an explicit cast. In fact, +=, -=, *=, and /= will all put in an implicit cast. Below is an example:

In addition to the basic assignment operator, Java also defines 12 shorthand assignment operators that combine assignment with the 5 arithmetic operators ( += , -= , *= , /= , %= ) and the 6 bitwise and shift operators ( &= , |= , ^= , <<= , >>= , >>>= ). For example, the += operator reads the value of the left variable, adds the value of the right operand to it, stores the sum back into the left variable as a side effect, and returns the sum as the value of the expression. Thus, the expression x += 2 is almost the same x = x + 2 .

The difference between these two expressions is that when we use the += operator, the left operand is evaluated only once. This makes a difference when that operand has a side effect. Consider the following two expressions a[i++] += 2; and a[i++] = a[i++] + 2; , which are not equivalent:

In this tutorial we discussed basic and shorthand (compound) assignment operators of Java. Hope you have enjoyed reading this tutorial. Please do write us if you have any suggestion/comment or come across any error on this page. Thanks for reading!

  • Core Java Volume I - Fundamentals
  • Java: The Complete Reference, Seventh Edition
  • Operators: Sun tutorial
  • Bit Twiddling Hacks
  • C Programming Tutorials
  • Java Programming Tutorials
  • Data Structures Tutorials
  • All Tech Interview Questions
  • C Interview Question Answers
  • Java Interview Question Answers
  • DSA Interview Question Answers

Get Free Tutorials by Email

About the Author

Author Photo

Krishan Kumar is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.

Today's Tech News

  • Write For Us

CAST Highlight

Avoid self-assigned variables

Why you should care.

There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead.

How we detect

This Code Insight counts one occurrence each time a variable is re-assigned to itself.

5362

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.

assignment to itself java

Download Interview guide PDF

Java 8 interview questions, download pdf.

Java, originally evolved from the Oak language, was born in early 1996 with its major version as Java 1 or JDK 1.0. Java was initially designed and developed by Sir James Gosling at Sun Microsystems. Java 8 or JDK 8.0 is one of the major releases of the Java programming language in 2014. It is also known by the codename Spider. Java is an open-source project and is currently managed by Oracle Corporation.

This article would walk you through the Java 8 interview questions for freshers and experienced, scope, and opportunities.

Java 8 Interview Questions for Freshers

1. what is the lambda expression in java and how does a lambda expression relate to a functional interface.

Lambda expression is a type of function without a name. It may or may not have results and parameters. It is known as an anonymous function as it does not have type information by itself. It is executed on-demand. It is beneficial in iterating, filtering, and extracting data from a collection.

As lambda expressions are similar to anonymous functions, they can only be applied to the single abstract method of Functional Interface. It will infer the return type, type, and several arguments from the signature of the abstract method of functional interface.

2. What are the various categories of pre-defined function interfaces?

Function: To transform arguments in returnable value.

Predicate: To perform a test and return a Boolean value.

Consumer: Accept arguments but do not return any values.

Supplier: Do not accept any arguments but return a value. 

Operator: Perform a reduction type operation that accepts the same input types.

3. What are some standard Java pre-defined functional interfaces?

Some of the famous pre-defined functional interfaces from previous Java versions are Runnable, Callable, Comparator, and Comparable. While Java 8 introduces functional interfaces like Supplier, Consumer, Predicate, etc. Please refer to the java.util.function doc for other predefined functional interfaces and its description introduced in Java 8.

Runnable: use to execute the instances of a class over another thread with no arguments and no return value. 

Callable: use to execute the instances of a class over another thread with no arguments and it either returns a value or throws an exception.

Comparator: use to sort different objects in a user-defined order

Comparable: use to sort objects in the natural sort order

4. What are static methods in Interfaces?

Static methods, which contains method implementation is owned by the interface and is invoked using the name of the interface, it is suitable for defining the utility methods and cannot be overridden.

5. What is the default method, and why is it required?

A method in the interface that has a predefined body is known as the default method. It uses the keyword default. default methods were introduced in Java 8 to have 'Backward Compatibility in case JDK modifies any interfaces. In case a new abstract method is added to the interface, all classes implementing the interface will break and will have to implement the new method. With default methods, there will not be any impact on the interface implementing classes. default methods can be overridden if needed in the implementation. Also, it does not qualify as synchronized or final.

  • Software Dev
  • Data Science

6. Can a functional interface extend/inherit another interface?

A functional interface cannot extend another interface with abstract methods as it will void the rule of one abstract method per functional interface. E.g:

It can extend other interfaces which do not have any abstract method and only have the default, static, another class is overridden, and normal methods. For eg:

7. What are functional or SAM interfaces?

Functional Interfaces are an interface with only one abstract method. Due to which it is also known as the Single Abstract Method (SAM) interface. It is known as a functional interface because it wraps a function as an interface or in other words a function is represented by a single abstract method of the interface.

Functional interfaces can have any number of default, static, and overridden methods. For declaring Functional Interfaces @FunctionalInterface annotation is optional to use. If this annotation is used for interfaces with more than one abstract method, it will generate a compiler error.

8. What is MetaSpace? How does it differ from PermGen?

assignment to itself java

PremGen: MetaData information of classes was stored in PremGen (Permanent-Generation) memory type before Java 8. PremGen is fixed in size and cannot be dynamically resized. It was a contiguous Java Heap Memory.

MetaSpace: Java 8 stores the MetaData of classes in native memory called 'MetaSpace'. It is not a contiguous Heap Memory and hence can be grown dynamically which helps to overcome the size constraints. This improves the garbage collection, auto-tuning, and de-allocation of metadata.

9. What are the significant advantages of Java 8?

  • Compact, readable, and reusable code.
  • Less boilerplate code.
  • Parallel operations and execution.
  • Can be ported across operating systems.
  • High stability.
  • Stable environment.
  • Adequate support

10. In which programming paradigm Java 8 falls?

  • Object-oriented programming language.
  • Functional programming language.
  • Procedural programming language.
  • Logic programming language

11. Describe the newly added features in Java 8?

Here are the newly added features of Java 8:

Feature Name Description
Lambda expression A function that can be shared or referred to as an object.
Functional Interfaces Single abstract method interface.
Method References Uses function as a parameter to invoke a method.
Default method It provides an implementation of methods within interfaces enabling 'Interface evolution' facilities.
Stream API Abstract layer that provides pipeline processing of the data.
Date Time API New improved joda-time inspired APIs to overcome the drawbacks in previous versions
Optional Wrapper class to check the null values and helps in further processing based on the value.
Nashorn, JavaScript Engine An improvised version of JavaScript Engine that enables JavaScript executions in Java, to replace Rhino.

Java 8 Interview Questions for Experienced

1. what is the basic structure/syntax of a lambda expression.

Lambda expression can be divided into three distinct parts as below:

1. List of Arguments/Params:

(String name) 

A list of params is passed in () round brackets. It can have zero or more params. Declaring the type of parameter is optional and can be inferred for the context. 

2. Arrow Token:

->  Arrow token is known as the lambda arrow operator. It is used to separate the parameters from the body, or it points the list of arguments to the body. 3. Expression/Body:

A body can have expressions or statements. {} curly braces are only required when there is more than one line. In one statement, the return type is the same as the return type of the statement. In other cases, the return type is either inferred by the return keyword or void if nothing is returned.

2. What are the features of a lambda expression?

Below are the two significant features of the methods that are defined as the lambda expressions: 

  • Lambda expressions can be passed as a parameter to another method. 
  • Lambda expressions can be standalone without belonging to any class.

3. What is a type interface?

Type interface is available even in earlier versions of Java. It is used to infer the type of argument by the compiler at the compile time by looking at method invocation and corresponding declaration.

4. What are the types and common ways to use lambda expressions?

A lambda expression does not have any specific type by itself. A lambda expression receives type once it is assigned to a functional interface. That same lambda expression can be assigned to different functional interface types and can have a different type.

For eg consider expression s -> s.isEmpty() :

Predicate<String> stringPredicate = s -> s.isEmpty();   Predicate<List> listPredicate = s -> s.isEmpty(); Function<String, Boolean> func = s -> s.isEmpty(); Consumer<String> stringConsumer = s -> s.isEmpty();

Common ways to use the expression

Assignment to a functional Interface —> Predicate<String> stringPredicate = s -> s.isEmpty(); Can be passed as a parameter that has a functional type —> stream.filter(s -> s.isEmpty()) Returning it from a function —> return s -> s.isEmpty() Casting it to a functional type —> (Predicate<String>) s -> s.isEmpty()

5. In Java 8, what is Method Reference?

Method reference is a compact way of referring to a method of functional interface. It is used to refer to a method without invoking it. :: (double colon) is used for describing the method reference. The syntax is class::methodName

Integer::parseInt(str) \\ method reference

str -> Integer.ParseInt(str); \\ equivalent lambda

6. What does the String::ValueOf expression mean?

It is a static method reference to method Valueof() of class String. It will return the string representation of the argument passed.

7. What is an Optional class?

Optional is a container type which may or may not contain value i.e. zero(null) or one(not-null) value. It is part of java.util package. There are pre-defined methods like isPresent(), which returns true if the value is present or else false and the method get(), which will return the value if it is present.

assignment to itself java

8. What are the advantages of using the Optional class?

Below are the main advantage of using the Optional class: 

It encapsulates optional values, i.e., null or not-null values, which helps in avoiding null checks, which results in better, readable, and robust code It acts as a wrapper around the object and returns an object instead of a value, which can be used to avoid run-time NullPointerExceptions.

9. What are Java 8 streams?

A stream is an abstraction to express data processing queries in a declarative way. 

A Stream, which represents a sequence of data objects & series of operations on that data is a data pipeline that is not related to Java I/O Streams does not hold any data permanently. The key interface is java.util.stream.Stream<T> . It accepts Functional Interfaces so that lambdas can be passed. Streams support a fluent interface or chaining. Below is the basic stream timeline marble diagram:

assignment to itself java

10. What are the main components of a Stream?

Components of the stream are:

  • A data source
  • Set of Intermediate Operations to process the data source
  • Single Terminal Operation that produces the result

assignment to itself java

11. What are the sources of data objects a Stream can process?

A Stream can process the following data:

  • A collection of an Array.
  • An I/O channel or an input device.
  • A reactive source (e.g., comments in social media or tweets/re-tweets) 
  • A stream generator function or a static factory.

12. What are Intermediate and Terminal operations?

Intermediate Operations:

  • Process the stream elements.
  • Typically transforms a stream into another stream.
  • Are lazy, i.e., not executed till a terminal operation is invoked.
  • Does internal iteration of all source elements.
  • Any number of operations can be chained in the processing pipeline.
  • Operations are applied as per the defined order.
  • Intermediate operations are mostly lambda functions.

Terminal Operations:

  • Kick-starts the Stream pipeline.
  • used to collect the processed Stream data.

13. What are the most commonly used Intermediate operations?

Filter(Predicate<T>) - Allows selective processing of Stream elements. It returns elements that are satisfying the supplied condition by the predicate.

map(Funtion<T, R>) - Returns a new Stream, transforming each of the elements by applying the supplied mapper function.= sorted() - Sorts the input elements and then passes them to the next stage.

distinct() - Only pass on elements to the next stage, not passed yet.

limit(long maxsize) - Limit the stream size to maxsize.

skip(long start) - Skip the initial elements till the start.

peek(Consumer) - Apply a consumer without modification to the stream.

flatMap(mapper) - Transform each element to a stream of its constituent elements and flatten all the streams into a single stream.

14. What is the stateful intermediate operation? Give some examples of stateful intermediate operations.

To complete some of the intermediate operations, some state is to be maintained, and such intermediate operations are called stateful intermediate operations. Parallel execution of these types of operations is complex.

For Eg: sorted() , distinct() , limit() , skip() etc. 

Sending data elements to further steps in the pipeline stops till all the data is sorted for sorted() and stream data elements are stored in temporary data structures.

15. What is the most common type of Terminal operations?

  • collect() - Collects single result from all elements of the stream sequence.
  • count() - Returns the number of elements on the stream.
  • min() - Returns the min element from the stream.
  • max() - Returns the max element from the stream.
  • anyMatch() , noneMatch() , allMatch() , ... - Short-circuiting operations.
  • Takes a Predicate as input for the match condition.
  • Stream processing will be stopped, as and when the result can be determined.
  • forEach() - Useful to do something with each of the Stream elements. It accepts a consumer.
  • forEachOrdered() - It is helpful to maintain order in parallel streams.

16. What is the difference between findFirst() and findAny()?

findFirst() findAny()
Returns the first element in the Stream Return any element from the Stream
Deterministic in nature Non-deterministic in nature

17. How are Collections different from Stream?

Collections are the source for the Stream. Java 8 collection API is enhanced with the default methods returning Stream<T> from the collections.

Collections Streams
Data structure holds all the data elements No data is stored. Have the capacity to process an infinite number of elements on demand
External Iteration Internal Iteration
Can be processed any number of times Traversed only once
Elements are easy to access No direct way of accessing specific elements
Is a data store Is an API to process the data

18. What is the feature of the new Date and Time API in Java 8?

  • Immutable classes and Thread-safe 
  • Timezone support
  • Fluent methods for object creation and arithmetic
  • Addresses I18N issue for earlier APIs
  • Influenced by popular joda-time package
  • All packages are based on the ISO-8601 calendar system

19. What are the important packages for the new Data and Time API?

  • time-zones 
  • Java.time.format
  • Java.time.temporal
  • java.time.zone

20. Explain with example, LocalDate, LocalTime, and LocalDateTime APIs.

  • Date with no time component
  • Default format - yyyy-MM-dd (2020-02-20)
  • LocalDate today = LocalDate.now();  // gives today’s date
  • LocalDate aDate = LocalDate.of(2011, 12, 30); //(year, month, date)
  • Time with no date with nanosecond precision
  • Default format - hh:mm:ss:zzz (12:06:03.015) nanosecond is optional
  • LocalTime now = LocalTime.now();  // gives time now
  • LocalTime aTime2 = LocalTime.of(18, 20, 30); // (hours, min, sec)

LocalDateTime

  • Holds both Date and Time
  • Default format - yyyy-MM-dd-HH-mm-ss.zzz (2020-02-20T12:06:03.015)
  • LocalDateTime timestamp = LocalDateTime.now(); // gives timestamp now
  • //(year, month, date, hours, min, sec)
  • LocalDateTime dt1 = LocalDateTime.of(2011, 12, 30, 18, 20, 30);

21. Define Nashorn in Java 8

Nashorn is a JavaScript processing engine that is bundled with Java 8. It provides better compliance with ECMA (European Computer Manufacturers Association) normalized JavaScript specifications and better performance at run-time than older versions.

22. What is the use of JJS in Java 8?

As part of Java 8, JJS is a command-line tool that helps to execute the JavaScript code in the console. Below is the example of CLI commands:

JAVA>jjs jjs> print("Hello, Java 8 - I am the new JJS!") Hello, Java 8 - I am the new JJS! jjs> quit() >>

All in all, Java is a prevalent programming language securing the second rank in popularity in both TIOBE and PYPL programming language ranking. The world's leading tech giants like Twitter, LinkedIn, Amazon, PayPal, etc., use Java to build their web apps and backend web systems. Java is also one of the primary languages used to develop Android apps; an operating system backed and promoted by Google.

As of today, there are 1,751,661 questions around Java on StackOverflow and 123,776 Java public repositories on GitHub and continuously increasing. Considering Java 8 to be one of the most stable versions, there are immense career opportunities and scope in the same. Just understand the concepts, implement them and get ready for the interviews!

Additional Resources

  • Practice Coding
  • Java Tutorials
  • Spring Boot Interview Questions
  • Hibernate Interview Questions
  • How To Become A Java Developer
  • Online Java Compiler
  • Features of Java
  • Java 9 Features
  • Java Frameworks
  • Highest Paying Jobs In India (IT Sector)
  • Java Developer Salary

Coding Problems

Java 8 mcqs.

What would be the output of the following code

Using Optional<T> type eliminates NullPointerException?

What is true about a Terminal Operation?

Methods of Optional<T> class

Identify the valid lambda expression

(s) -> System.out.println("Welcome to Java 8, Hello !!! "+s); is an implementation of type

partitioningBy() collector returns a Map<Boolean, List<>>

A lambda expression has a scope of its own

Which is not the type of Lambda Expression?

Lambdas vs. Anonymous Inner classes - what is false?

  • Privacy Policy

instagram-icon

  • Practice Questions
  • Programming
  • System Design
  • Fast Track Courses
  • Online Interviewbit Compilers
  • Online C Compiler
  • Online C++ Compiler
  • Online Javascript Compiler
  • Online Python Compiler
  • Interview Preparation
  • Java Interview Questions
  • Sql Interview Questions
  • Python Interview Questions
  • Javascript Interview Questions
  • Angular Interview Questions
  • Networking Interview Questions
  • Selenium Interview Questions
  • Data Structure Interview Questions
  • Data Science Interview Questions
  • System Design Interview Questions
  • Hr Interview Questions
  • Html Interview Questions
  • C Interview Questions
  • Amazon Interview Questions
  • Facebook Interview Questions
  • Google Interview Questions
  • Tcs Interview Questions
  • Accenture Interview Questions
  • Infosys Interview Questions
  • Capgemini Interview Questions
  • Wipro Interview Questions
  • Cognizant Interview Questions
  • Deloitte Interview Questions
  • Zoho Interview Questions
  • Hcl Interview Questions
  • Highest Paying Jobs In India
  • Exciting C Projects Ideas With Source Code
  • Top Java 8 Features
  • Angular Vs React
  • 10 Best Data Structures And Algorithms Books
  • Best Full Stack Developer Courses
  • Best Data Science Courses
  • Python Commands List
  • Data Scientist Salary
  • Maximum Subarray Sum Kadane’s Algorithm
  • Python Cheat Sheet
  • C++ Cheat Sheet
  • Javascript Cheat Sheet
  • Git Cheat Sheet
  • Java Cheat Sheet
  • Data Structure Mcq
  • C Programming Mcq
  • Javascript Mcq

1 Million +

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

Self assignment check in assignment operator

In C++, assignment operator should be overloaded with self assignment check.

For example, consider the following class Array and overloaded assignment operator function without self assignment check.

       

If we have an object say a1 of type Array and if we have a line like a1 = a1 somewhere, the program results in unpredictable behavior because there is no self assignment check in the above code. To avoid the above issue, self assignment check must be there while overloading assignment operator. For example, following code does self assignment check.

     

References: http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html

Please Login to comment...

Similar reads.

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

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

Multiple assignment at once in java

In python you can do this:

Is there an equivalent in java?

qed's user avatar

4 Answers 4

tl;dr: No, there isn't such a thing in Java.

You can assign initial values to variables like this:

But if your want (1, 2, 3) to be the result of a method call, this is not possible in Java. Java does not allow returning multiple values.

Python allows this:

The main point, why this does not work in Java is, that the left hand side (LHS) of the assignment must be one variable:

You can not assign to a tuple on the LHS as you can in Python.

  • 1 python is not a big bad guy - it returning one value, in case of OP example - tuple. But it supporting unboxing a tuple to variables. java not support such thing. –  Reishin Commented Nov 5, 2019 at 12:21

If you want (1,2,3) to be the result of a method call, you can use an array:

Eran's user avatar

  • 1 What about the type of this array? What if is more complex than int[] ? –  user1907906 Commented Nov 16, 2014 at 13:21
  • @user1907906 See the generics in Java. –  f1nch Commented Apr 20, 2022 at 7:56

I realize this is an old post, but I could point out a way that comes somewhat close to this.

Using the OP's example (This could obviously use multiple types instead of three ints, but I'm going with the original example),

Now at this point I realize you haven't actually ASSIGNED this to three local variables (or member variables) as you would have liked, however you do have a local variable you can use as though you had... like:

The advantages here are that this is quite terse, hardly more work than the python example and safer/clearer/easier to read; as is I'd be really happy with this!

Perhaps more important though is that as you go on you will realize that this mini-class should have been a real class all along since the values are going to be somewhat associated since they are from the same function!

You can change what you have to a real class with simple editor refactors--replace member access with getter/setter, make members private, extract the class into it's own file and you have a full class!

Chances are that you'll eventually figure out that your original function f() should have been a member (or constructor) of this class in the first place!

By the way, the disadvantage is that this will fully trigger some Java programmers that don't understand that rules were meant to be broken--if you have old coders who are insistent on stuff that seems pedantic (rule-obsessed) it's best not to try this because it'll make their head explode (all over you, most likely).

Bill K's user avatar

As I noted in this other question , if your goal is specifically to return multiple values from a function, in Java 16+ you can accomplish something similar to this using a record type:

This will let you return any set of types, with named fields, at the expense of having to add a line to declare the record. This won't really help with assignments like (i, j) = (j, i) however.

Chiara Coetzee's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java assign 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

  • Doesn't counting hole and electron current lead to double-counting of actual current?
  • What story starts off with the character waking up in a battlefield with wolves and vultures and snow?
  • Functor composition rule necessary?
  • What does "if you ever get up this way" mean?
  • Solenoid driver circuit with peak hold
  • Do eternal ordinances such as the festival of unleavened bread pose a biblical contradiction?
  • How do I define the solution to an inequality?
  • Can it be acceptable to take over CTRL + F shortcut in web app
  • Driveway electric run using existing service poles
  • How can I retain only the lines in code fences?
  • Can an international student email a professor at a foreign university for an internship opportunity?
  • Explain how π – 1 + 50 + ⅔ × 1000 is PLONK
  • Why does my shifter say the wrong gear?
  • Are there probabilistic facts of the matter about the universe?
  • What should be the affiliation of PhD student who submitted thesis but yet to defend, in a conference talk slides?
  • Who owns code contributed to a license-free repository?
  • Reference to formal approach to homotopy analysis method
  • World Building Knowledgebase - How to write good Military World Building
  • Did Gandalf know he was a Maia?
  • How many ways can you make change?
  • Reference request: regularity of non-divergence form elliptic operators with Neumann boundary conditions
  • If you have two probabilities, how do you describe how much more likely one is than the other?
  • Driving relay without a control Fet: Back EMF consideration when control side is Grounded
  • Is it a date format of YYMMDD, MMDDYY, and/or DDMMYY?

assignment to itself java

IMAGES

  1. Java Assignment Operators

    assignment to itself java

  2. Assignment Operators in Java

    assignment to itself java

  3. The Assignment Operator in Java

    assignment to itself java

  4. Beginner Java Tutorial #11: Shorthand Assignment Operators

    assignment to itself java

  5. Java Assignment operators

    assignment to itself java

  6. Assignment Operators in Java

    assignment to itself java

VIDEO

  1. JAVA Assignment Operators

  2. part-16|While Loop |Simple Exaplain|Java Tutorial For Beginners|Basic To Advance Level|In Tamil

  3. NPTEL Programming in Java Week-1 Assignment Solution #nptelcourseanswers

  4. Run Java Program in CMD itself

  5. Java ReentrantLock

  6. Can a method call itself in Java (Core Java Interview Question #337)

COMMENTS

  1. In Java why would you assign a variable to itself

    6. You are not assigning the variable to itself, this.VAR and VAR are different variables. When using a class in Java, you can refer to your attributes by using the this prefix. In many methods the this prefix is optional because there is not any method parameter with the same name.

  2. A Guide to the Static Keyword in Java

    2. The Anatomy of the static Keyword. In the Java programming language, the keyword static means that the particular member belongs to a type itself, rather than to an instance of that type. This means we'll create only one instance of that static member that's shared across all instances of the class.

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

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

  5. Passing and Returning Objects in Java

    When we assign an integer value to an Integer object, the value is autoboxed into an Integer object. For example the statement "Integer x = 10" creates an object 'x' with value 10. Following are some interesting output questions based on comparison of Autoboxed Integer objects. Predict the output of following Java Program // file name: Main.java pu

  6. Java Constructors

    In Java, a Constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type of method that is used to initialize the object. Every time an object is created using the new () keyword, at ...

  7. Static Final Variables in Java

    Here's an example of how to declare a static final field and assign a value: public static final int TIRE = 2; Here, we create a class named Bike with a constant class variable named TIRE and initialize it to two. Alternatively, we can initialize the variable via a static initializer block: static {. PEDAL = 5;

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

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

    This operator can also be used on objects to assign object references, as discussed in Creating Objects. The Arithmetic Operators. The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics.

  10. PDF Executing the assignment statement Example execution of an assignment

    To execute the assignment statement. x. int. x= x + 2; evaluate the expression x + 2, resulting in the value 7, and store this value in box x. Thus, cross out the value 5 and store the value 7 in the box. Since a variable can hold only one value, the old value is removed. Don't make this mistake.

  11. java

    1. Lets see what would happen when an object of foo is created. foo x = new foo(); On encountring new JVM will create an object of foo in heap. Next step (Note its Next step) is constructor execution. In java object is created on heap and then constructor is invoked. This is the reason even if constructor throws an exception, even then object ...

  12. Initialization, Declaration and Assignment in Java #54

    $1,000 OFF ANY Springboard Tech Bootcamps with my code ALEXLEE. See if you qualify for the JOB GUARANTEE! 👉 https://bit.ly/3HX970hFull Java Tutorial For Beg...

  13. Assignment Operator in Java with Example

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

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

    Java's basic assignment operator is a single equals-to (=) sign that assigns the right-hand side value to the left-hand side operand. On left side of the assignment operator there must be a variable that can hold the value assigned to it. Assignment operator operates on both primitive and reference types. It has the following syntax: var ...

  15. Avoid self-assigned variables

    About CAST and Highlight's Code Insights. Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15 ...

  16. Assigning in Java?

    In Java, your variables can be split into two categories: Objects, and everything else (int, long, byte, etc). A primitive type (int, long, etc), holds whatever value you assign it. An object variable, by contrast, holds a reference to an object somewhere. So if you assign one object variable to another, you have copied the reference, both A ...

  17. Clone() Method in Java

    There are 3 methods for creating Object Cloning in Java that are mentioned below: Using Assignment Operator to create a copy of the reference variable. Creating a copy using the clone () method. Usage of clone () method - Deep Copy. 1. Using Assignment Operator to create a copy of the reference variable. In Java, there is no operator to ...

  18. 7 Best Java Homework Help Websites: How to Choose Your Perfect Match?

    The rate of the website speaks for itself. Pricing . When you place your 'do my Java homework' request with AssignmentShark, you are to pay $20/page for the project that needs to be done in at ...

  19. java

    I have one class like this: public class AdvancedArrayList<T> extends ArrayList<T>. And I want to assign a new object to itself. But, I am unable to do that. Just see this code: AdvancedArrayList<T> abcd = this; // works fine. this = abcd; // ERROR: variable expected. And this is my entire class: public class AdvancedArrayList<T> extends ...

  20. Top 30+ Java 8 Interview Questions (2024)

    Java, originally evolved from the Oak language, was born in early 1996 with its major version as Java 1 or JDK 1.0. Java was initially designed and developed by Sir James Gosling at Sun Microsystems. Java 8 or JDK 8.0 is one of the major releases of the Java programming language in 2014. It is also known by the codename Spider.

  21. Array Variable Assignment in Java

    Array Variable Assignment in Java. An array is a collection of similar types of data in a contiguous location in memory. After Declaring an array we create and assign it a value or variable. During the assignment variable of the array things, we have to remember and have to check the below condition. 1.

  22. Analysis of Code and Test-Code generated by Large Language Models arXiv

    // Implement a java test class for the binary to decimal algorithm above using JUnit version 4. // Implement at least 3 different test cases. Breadth First Search // Implement a java test class for the breadth first search algorithm above using JUnit version 4. // Implement at least 3 different test cases. // Build a graph with the following edges:

  23. Self assignment check in assignment operator

    We have discussed assignment operator overloading for dynamically allocated resources here. In this article, we discussed that when we don't write our own assignment operator, the compiler creates an assignment operator itself that does shallow copy and thus causes problems. The difference between shallow copy and deep copy becomes visible when the

  24. assign

    Java does not allow returning multiple values. Python allows this: def foo(): return 1, 2, 3. a, b, c = foo() The main point, why this does not work in Java is, that the left hand side (LHS) of the assignment must be one variable: Wrapper wrapper = WrapperGenrator.generateWrapper(); You can not assign to a tuple on the LHS as you can in Python.