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.

Using Objects

Once you've created an object, you probably want to use it for something. You may need to use the value of one of its fields, change one of its fields, or call one of its methods to perform an action.

Referencing an Object's Fields

Object fields are accessed by their name. You must use a name that is unambiguous.

You may use a simple name for a field within its own class. For example, we can add a statement within the Rectangle class that prints the width and height :

In this case, width and height are simple names.

Code that is outside the object's class must use an object reference or expression, followed by the dot (.) operator, followed by a simple field name, as in:

For example, the code in the CreateObjectDemo class is outside the code for the Rectangle class. So to refer to the origin , width , and height fields within the Rectangle object named rectOne , the CreateObjectDemo class must use the names rectOne.origin , rectOne.width , and rectOne.height , respectively. The program uses two of these names to display the width and the height of rectOne :

Attempting to use the simple names width and height from the code in the CreateObjectDemo class doesn't make sense — those fields exist only within an object — and results in a compiler error.

Later, the program uses similar code to display information about rectTwo . Objects of the same type have their own copy of the same instance fields. Thus, each Rectangle object has fields named origin , width , and height . When you access an instance field through an object reference, you reference that particular object's field. The two objects rectOne and rectTwo in the CreateObjectDemo program have different origin , width , and height fields.

To access a field, you can use a named reference to an object, as in the previous examples, or you can use any expression that returns an object reference. Recall that the new operator returns a reference to an object. So you could use the value returned from new to access a new object's fields:

This statement creates a new Rectangle object and immediately gets its height. In essence, the statement calculates the default height of a Rectangle . Note that after this statement has been executed, the program no longer has a reference to the created Rectangle , because the program never stored the reference anywhere. The object is unreferenced, and its resources are free to be recycled by the Java Virtual Machine.

Calling an Object's Methods

You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.

The Rectangle class has two methods: getArea() to compute the rectangle's area and move() to change the rectangle's origin. Here's the CreateObjectDemo code that invokes these two methods:

The first statement invokes rectOne 's getArea() method and displays the results. The second line moves rectTwo because the move() method assigns new values to the object's origin.x and origin.y .

As with instance fields, objectReference must be a reference to an object. You can use a variable name, but you also can use any expression that returns an object reference. The new operator returns an object reference, so you can use the value returned from new to invoke a new object's methods:

The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle object. As shown, you can use the dot notation to invoke the new Rectangle 's getArea() method to compute the area of the new rectangle.

Some methods, such as getArea() , return a value. For methods that return a value, you can use the method invocation in expressions. You can assign the return value to a variable, use it to make decisions, or control a loop. This code assigns the value returned by getArea() to the variable areaOfRectangle :

Remember, invoking a method on a particular object is the same as sending a message to that object. In this case, the object that getArea() is invoked on is the rectangle returned by the constructor.

The Garbage Collector

Some object-oriented languages require that you keep track of all the objects you create and that you explicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and error-prone. The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection .

An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null . Remember that a program can have multiple references to the same object; all references to an object must be dropped before the object is eligible for garbage collection.

The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right.

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

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

Object Type Casting in Java

Last updated: May 11, 2024

java object reference assignment

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

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.

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

Do JSON right with Jackson

Download the E-book

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:

>> REST With Spring (new)

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

>> LEARN SPRING

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

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

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot .

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

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

1. Overview

The Java type system is made up of two kinds of types: primitives and references.

We covered primitive conversions in this article , and we’ll focus on references casting here to get a good understanding of how Java handles types.

Further reading:

The basics of java generics, java instanceof operator, 2. primitive vs reference.

Although primitive conversions and reference variable casting may look similar, they’re quite different concepts .

In both cases, we’re “turning” one type into another. But, in a simplified way, a primitive variable contains its value, and conversion of a primitive variable means irreversible changes in its value:

After the conversion in the above example, myInt variable is 1 , and we can’t restore the previous value 1.1 from it.

Reference variables are different ; the reference variable only refers to an object but doesn’t contain the object itself.

And casting a reference variable doesn’t touch the object it refers to but only labels this object in another way, expanding or narrowing opportunities to work with it. Upcasting narrows the list of methods and properties available to this object, and downcasting can extend it.

A reference is like a remote control to an object. The remote control has more or fewer buttons depending on its type, and the object itself is stored in a heap. When we do casting, we change the type of the remote control but don’t change the object itself.

3. Upcasting

Casting from a subclass to a superclass is called upcasting. Typically, the upcasting is implicitly performed by the compiler.

Upcasting is closely related to inheritance — another core concept in Java. It’s common to use reference variables to refer to a more specific type. And every time we do this, implicit upcasting takes place.

To demonstrate upcasting, let’s define an Animal class:

Now let’s extend Animal :

Now we can create an object of Cat class and assign it to the reference variable of type Cat :

And we can also assign it to the reference variable of type Animal :

In the above assignment, implicit upcasting takes place.

We could do it explicitly:

But there is no need to do explicit cast up the inheritance tree. The compiler knows that cat is an Animal and doesn’t display any errors.

Note that reference can refer to any subtype of the declared type.

Using upcasting, we’ve restricted the number of methods available to Cat instance but haven’t changed the instance itself. Now we can’t do anything that is specific to Cat — we can’t invoke meow() on the animal variable.

Although Cat object remains Cat object, calling meow() would cause the compiler error:

To invoke meow() we need to downcast animal , and we’ll do this later.

But now we’ll describe what gives us the upcasting. Thanks to upcasting, we can take advantage of polymorphism.

3.1. Polymorphism

Let’s define another subclass of Animal , a Dog class:

Now we can define the feed() method, which treats all cats and dogs like animals :

We don’t want AnimalFeeder to care about which animal is on the list — a Cat or a Dog . In the feed() method they are all animals .

Implicit upcasting occurs when we add objects of a specific type to the animals list:

We add cats and dogs, and they are upcast to Animal type implicitly. Each Cat is an Animal and each Dog is an Animal . They’re polymorphic.

By the way, all Java objects are polymorphic because each object is an Object at least. We can assign an instance of Animal to the reference variable of Object type and the compiler won’t complain:

That’s why all Java objects we create already have Object -specific methods, for example toString() .

Upcasting to an interface is also common.

We can create Mew interface and make Cat implement it:

Now any Cat object can also be upcast to Mew :

Cat is a Mew ; upcasting is legal and done implicitly.

Therefore, Cat is a Mew , Animal , Object  and Cat . It can be assigned to reference variables of all four types in our example.

3.2. Overriding

In the example above, the eat() method is overridden. This means that although eat() is called on the variable of the Animal type, the work is done by methods invoked on real objects — cats and dogs:

If we add some logging to our classes, we’ll see that Cat  and Dog  methods are called:

  • A reference variable can refer to an object if the object is of the same type as a variable or if it is a subtype.
  • Upcasting happens implicitly.
  • All Java objects are polymorphic and can be treated as objects of supertype due to upcasting.

4. Downcasting

What if we want to use the variable of type Animal to invoke a method available only to Cat class? Here comes the downcasting. It’s the casting from a superclass to a subclass.

Let’s look at an example:

We know that animal variable refers to the instance of Cat . And we want to invoke Cat ’s meow() method on the animal . But the compiler complains that meow() method doesn’t exist for the type Animal .

To call meow() we should downcast animal to Cat :

The inner parentheses and the type they contain are sometimes called the cast operator. Note that external parentheses are also needed to compile the code.

Let’s rewrite the previous AnimalFeeder example with meow() method:

Now we gain access to all methods available to Cat class. Look at the log to make sure that meow() is actually called:

Note that in the above example we’re trying to downcast only those objects that are really instances of Cat . To do this, we use the operator instanceof .

4.1. instanceof Operator

We often use instanceof operator before downcasting to check if the object belongs to the specific type:

4.2. ClassCastException

If we hadn’t checked the type with the instanceof operator, the compiler wouldn’t have complained. But at runtime, there would be an exception.

To demonstrate this, let’s remove the instanceof operator from the above code:

This code compiles without issues. But if we try to run it, we’ll see an exception:

java.lang.ClassCastException: com.baeldung.casting.Dog cannot be cast to com.baeldung.casting.Cat

This means that we are trying to convert an object that is an instance of Dog into a Cat instance.

ClassCastException is always thrown at runtime if the type we downcast to doesn’t match the type of the real object.

Note that if we try to downcast to an unrelated type, the compiler won’t allow this:

The compiler says “Cannot cast from Animal to String.”

For the code to compile, both types should be in the same inheritance tree.

Let’s sum up:

  • Downcasting is necessary to gain access to members specific to subclass.
  • Downcasting is done using cast operator.
  • To downcast an object safely, we need instanceof operator.
  • If the real object doesn’t match the type we downcast to, then ClassCastException will be thrown at runtime.

5. cast() Method

There’s another way to cast objects using the methods of Class :

In the above example, cast( ) and isInstance() methods are used instead of cast and instanceof operators correspondingly.

It’s common to use cast() and isInstance() methods with generic types.

Let’s create AnimalFeederGeneric<T> class with feed() method that “feeds” only one type of animal, cats or dogs, depending on the value of the type parameter:

The feed() method checks each animal and returns only those that are instances of T .

Note that the Class instance should also be passed to the generic class, as we can’t get it from the type parameter T . In our example, we pass it in the constructor.

Let’s make T equal to Cat and make sure that the method returns only cats:

6. Conclusion

In this foundational tutorial, we’ve explored upcasting, downcasting, how to use them and how these concepts can help you take advantage of polymorphism.

As always, the code for this article is available over on GitHub .

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

>> Try out the Profiler

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.

Just published a new writeup on how to run a standard Java/Boot application as a Docker container, using the Liberica JDK on top of Alpaquita Linux:

>> Spring Boot Application on Liberica Runtime Container.

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.

Build your API with SPRING - book cover

Java Object Reference Variable

In this chapter you will learn:

Description

Object reference variables act differently when an assignment takes place.

For example,

After this fragment executes, b1 and b2 will both refer to the same object.

The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is referring.

A subsequent assignment to b1 will simply unhook b1 from the original object without affecting the object or affecting b2.

For example:

Here, b1 has been set to null, but b2 still points to the original object.

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  • Watch & Listen
  • Oracle University

Previous in the Series: Calling Methods and Constructors

Next in the Series: More on Classes

Creating and Using Objects

Understanding what objects are.

A typical Java program creates many objects, which as you know, interact by invoking methods. Through these object interactions, a program can carry out various tasks, such as implementing a GUI, running an animation, or sending and receiving information over a network. Once an object has completed the work for which it was created, its resources are recycled for use by other objects.

Here is a small program, called CreateObjectDemo , that creates three objects: one Point object and two Rectangle objects. You will need all three source files to compile this program.

Here is the Point class:

And the Rectangle class:

This program creates, manipulates, and displays information about various objects. Here's the output:

The following three sections use the above example to describe the life cycle of an object within a program. From them, you will learn how to write code that creates and uses objects in your own programs. You will also learn how the system cleans up after an object when its life has ended.

Creating Objects

As you know, a class provides the blueprint for objects; you create an object from a class. Each of the following statements taken from the CreateObjectDemo program creates an object and assigns it to a variable:

The first line creates an object of the Point class, and the second and third lines each create an object of the Rectangle class.

Each of these statements has three parts (discussed in detail below):

  • Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
  • Instantiation: The new keyword is a Java operator that creates the object.
  • Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

Declaring a Variable to Refer to an Object

Previously, you learned that to declare a variable, you write:

This notifies the compiler that you will use name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable.

You can also declare a reference variable on its own line. For example:

If you declare originOne like this, its value will be undetermined until an object is actually created and assigned to it. Simply declaring a reference variable does not create an object. For that, you need to use the new operator, as described in the next section. You must assign an object to originOne before you use it in your code. Otherwise, you will get a compiler error.

A variable in this state, currently references no object.

Instantiating a Class

The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.

Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate.

The new operator returns a reference to the object it created. This reference is usually assigned to a variable of the appropriate type, like:

The reference returned by the new operator does not have to be assigned to a variable. It can also be used directly in an expression. For example:

This statement will be discussed in the next section.

Initializing an Object

Here is the code for the Point class:

This class contains a single constructor. You can recognize a constructor because its declaration uses the same name as the class and it has no return type. The constructor in the Point class takes two integer arguments, as declared by the code (int a, int b) . The following statement provides 23 and 94 as values for those arguments:

The result of executing this statement can be illustrated in the next figure:

A Point Object

Here is the code for the Rectangle class, which contains four constructors:

Each constructor lets you provide initial values for the rectangle's origin , width , and height , using both primitive and reference types. If a class has multiple constructors, they must have different signatures. The Java compiler differentiates the constructors based on the number and the type of the arguments. When the Java compiler encounters the following code, it knows to call the constructor in the Rectangle class that requires a Point argument followed by two integer arguments:

This calls one of Rectangle 's constructors that initializes origin to originOne . Also, the constructor sets width to 100 and height to 200. Now there are two references to the same Point object—an object can have multiple references to it, as shown in the next figure:

A Rectangle Object

The following line of code calls the Rectangle constructor that requires two integer arguments, which provide the initial values for width and height . If you inspect the code within the constructor, you will see that it creates a new Point object whose x and y values are initialized to 0:

The Rectangle constructor used in the following statement does not take any arguments, so it is called a no-argument constructor:

All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor ( Object does have one), the compiler will reject the program.

Using Objects

Once you have created an object, you probably want to use it for something. You may need to use the value of one of its fields, change one of its fields, or call one of its methods to perform an action.

Referencing an Object's Fields

Object fields are accessed by their name. You must use a name that is unambiguous.

You may use a simple name for a field within its own class. For example, we can add a statement within the Rectangle class that prints the width and height :

In this case, width and height are simple names.

Code that is outside the object's class must use an object reference or expression, followed by the dot ( . ) operator, followed by a simple field name, as in:

For example, the code in the CreateObjectDemo class is outside the code for the Rectangle class. So to refer to the origin , width , and height fields within the Rectangle object named rectOne , the CreateObjectDemo class must use the names rectOne.origin , rectOne.width , and rectOne.height , respectively. The program uses two of these names to display the width and the height of rectOne :

Attempting to use the simple names width and height from the code in the CreateObjectDemo class does not make sense — those fields exist only within an object — and results in a compiler error.

Later, the program uses similar code to display information about rectTwo . Objects of the same type have their own copy of the same instance fields. Thus, each Rectangle object has fields named origin , width , and height . When you access an instance field through an object reference, you reference that particular object's field. The two objects rectOne and rectTwo in the CreateObjectDemo program have different origin , width , and height fields.

To access a field, you can use a named reference to an object, as in the previous examples, or you can use any expression that returns an object reference. Recall that the new operator returns a reference to an object. So you could use the value returned from new to access a new object's fields:

This statement creates a new Rectangle object and immediately gets its height . In essence, the statement calculates the default height of a Rectangle . Note that after this statement has been executed, the program no longer has a reference to the created Rectangle , because the program never stored the reference anywhere. The object is unreferenced, and its resources are free to be recycled by the Java Virtual Machine.

Calling an Object's Methods

You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator ( . ). Also, you provide, within enclosing parentheses, any arguments to the method. If the method does not require any arguments, use empty parentheses.

The Rectangle class has two methods: getArea() to compute the rectangle's area and move() to change the rectangle's origin. Here's the CreateObjectDemo code that invokes these two methods:

The first statement invokes rectOne 's getArea() method and displays the results. The second line moves rectTwo because the move() method assigns new values to the object's origin.x and origin.y .

As with instance fields, objectReference must be a reference to an object. You can use a variable name, but you also can use any expression that returns an object reference. The new operator returns an object reference, so you can use the value returned from new to invoke a new object's methods:

The expression new Rectangle(100, 50) returns an object reference that refers to a Rectangle object. As shown, you can use the dot notation to invoke the new Rectangle 's getArea() method to compute the area of the new rectangle.

Some methods, such as getArea() , return a value. For methods that return a value, you can use the method invocation in expressions. You can assign the return value to a variable, use it to make decisions, or control a loop. This code assigns the value returned by getArea() to the variable areaOfRectangle :

In this case, the object that getArea() is invoked on is the rectangle returned by the constructor.

The Garbage Collector

Some object-oriented languages require that you keep track of all the objects you create and that you explicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and error-prone. The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you do not have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.

An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null . Remember that a program can have multiple references to the same object; all references to an object must be dropped before the object is eligible for garbage collection.

The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right.

In this tutorial

Last update: January 5, 2024

Java, A Beginner's Guide, 5th Edition, 5th Edition by Herbert Schildt

Get full access to Java, A Beginner's Guide, 5th Edition, 5th Edition and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Reference Variables and Assignment

In an assignment operation, object reference variables act differently than do variables of a primitive type, such as int . When you assign one primitive-type variable to another, the situation is straightforward. The variable on the left receives a copy of the value of the variable on the right. When you assign one object reference variable to another, the situation is a bit more complicated because you are changing the object that the reference variable refers to. The effect of this difference can cause some counterintuitive results. For example, consider the following fragment:

Image

At first glance, it is easy to ...

Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

java object reference assignment

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

Lesson 10- Object References

This lesson discusses object reference variables. These variables refer to objects (as opposed to holding a primitive data value.)

The key topics for this lesson are:

A. Primitive Data Type Variables
B. Object Reference variables
C. Variable Versus Object Reference Assignment
D. Object References
E. The == operator with Variables and Object References
F. The Method.
G. The Value.


PRIMITIVE DATA
GARBAGE COLLECTION

OBJECT REFERENCE

1. Java has many data types built into it, and you (as a programmer) can define as many more as you need. Other than the primitive data types, all data types are classes. In other words, data is primitive data or object data. The only type of data a programmer can define is an object data type (a class).

2. Here is a tiny program that uses a primitive data type:
PrimitiveDataType { main(String[] args) { primitiveValue; primitiveValue = 95124; System.out.println(primitiveValue); } }

In this program, the variable value is the name for a 64 bit section of memory that is used to hold long integers. The statement

puts a particular bit pattern in that 64 bit section of memory.

3. With primitive data types, a variable is a section of memory reserved for a value of a particular style. For example by saying value, 64 bits of memory are reserved for an integer. By saying sum, 32 bits of memory are reserved an integer.

1. Since objects are big, complicated, and vary in size you do not automatically get an object when you declare an object reference variable. All you get is a name for a future object. For example:

2. Here is a tiny program that uses a String object (NOT a primitive data type):

3. An object contains data and methods (state and behavior). You can visualize the String object in the above program like this:

The data section of the object contains the characters. The methods section of the object contains many methods.

4. An object reference is information on how to find a particular object. The object is a chunk of main memory; a reference to the object is a way to get to that chunk of memory. The variable str does not actually contain the object, but contains information about where the object is.

5. Objects are created while a program is running. Each object has a unique object reference, which is used to find it. When an object reference is assigned to a variable, then that variable says how to find that object.

1. Notice that there is a difference between the two statements:

and

In the first statement, is a primitive type, so the assignment statement puts the data directly into it. In the second statement, is an object reference variable (the only other possibility) so a reference to the object is put into that variable.

2. A variable will contain an object. There are only primitive variables and object reference variables, and each contains a specific kind of information:

3. The two types of variable are distinguished by how they are declared. Unless it was declared to be of a primitive type, it is an object reference variable. A variable will not change its declared type.

D. Object References

2. Notice that:

a. Each time the new operator is used, a new object is created. b. Each time an object is created, there is a reference to it. c. This reference is saved in a variable. d. Later on, the reference in the variable is used to find the object. e. If another reference is saved in the variable, it replaces the previous reference. f. If no variables hold a reference to an object, there is no way to find it, and it becomes " garbage. "

3. The word "garbage" is the correct term from computer science to use for objects that have no references. This is a commonly occurring situation, not usually a mistake. As a program executes, a part of the Java system called the "garbage collector" reclaims the lost objects (the "garbage") so that their memory can be used again.

4. Multiple objects of the same class can be maintained by creating unique reference variables for each object.

5. Different reference variables that refer to the same object are called aliases . In effect, there are two names for the same object. For example:

When this program runs, only one object is created (by new). Information about how to find the object is put into strA. The assignment operator in the statement

strB = strA; // copy the reference to strB.

copies the information that is in strA to strB. It does not make a copy of the object.

E. The == operator with Variables and Object References.

1. The == operator is used to look at the contents of two reference variables. If the contents of both reference variables is the same, then the result is true . Otherwise the result is false .

2. In this program, there are two completely separate objects, each of which happens to contain character data equivalent to that in the other. Each object consists of a section of main memory completely separate from the memory that makes up the other object. The variable strA contains information on how to find the first object, and the variable strB contains information on how to find the second object

Since the information in strA is different from the information in strB, (strA == strB) is false, for the first comparison. Since there are two objects, made out of two separate sections of main memory, the reference stored in strA is different from the reference in strB. It doesn't matter that the data inside the objects looks the same.

3. The == operator does not look at objects. It only looks at references (information about where an object is located.)

4. For primitive types, the == operator looks only at the variables. For example:

In this code, only the contents of the variables x and y are examined. But with primitive types, the contents of a variable is the data, so with primitive types == looks at data.

5. With primitive and reference types, == looks at the contents of the variables. However, with reference types, the variables contain object references and with primitive types, the variables contain the actual data values.

F. The equals() Method.

2. The equals(String) method does look at the contents of objects. It detects "equivalence." The == operator detects "identity". For example,

3. In this example, there are two objects. Since each object has its own identity, == reports false. Each object contains equivalent data so equals() reports true.

G. The null Value

1. In most programs, objects are created and objects are destroyed, depending on the data and on what is being computed. A reference variable sometimes does and sometimes does not refer to an object. You need a way to say that a variable does not now refer to an object. You do this by assigning null to the variable.

2. The value null is a special value that means "no object." A reference variable is set to null when it is not referring to any object.

3. Variables a and c are initialized to object references. Variable b is initialized to null. Note that variable c is initialized to a reference to a String object containing no characters. This is a different value than null.

SUMMARY/ REVIEW:

Home

Last Minute Java Object Assignment and Object Passing By Value or Reference Explained Tutorial

Java Object Assignment and Object Passing by Value or Reference Infographic

In Java, we create Classes. We create objects of the Classes. Let us know if it is possible to assign a Java Object  from one variable to another variable by value or reference in this Last Minute Java Tutorial. We also try to know whether it is possible to pass Java Objects to another method by Value or Reference in this tutorial.

You may also read about Introduction to Java Class Structure .

Java Object Assignment by Value or Reference Explained

In Java, objects are always passed by Reference. Reference is nothing but the starting address of a memory location where the actual object lies. You can create any number of references to just One Object. Let us go by an example.

We create a Class "Cloud" with a single Property called "color". It is a String object. We create 3 objects of the Cloud type.

Notice that all three references obj1, obj2 and obj3 are pointing to the same Cloud object. Thus the above example outputs the same color-property value " RED ". Later, we made the references obj2 and obj3 to point to the null location. Still the original object pointed or referenced by obj1 holds the value. So the final PRINT statement outputs "RED" as usual.

Note : Reference is also called a Variable whether Primitive or Object.

This concludes that a Java object assignment happens by Reference . But the actual value of memory location pointed by References are copied by Value only. So we are actually copying memory locations from one Reference variable to another Reference variable by Value . Interviewers ask this famous Java question just to test your knowledge. If someone asks in C language point of view , say that it is by Reference . If they ask in Java point of view , say that it is by Value. 

Java Object Passing by Value or Reference to a Method Explained

You already learnt that Object assignment in Java happens by Reference. Let us try to pass Objects to another method as a parameter or argument. We try to know whether Objects are passed by Value or Reference to another Method using the below example.

In the above example, we have created an object "obj1" of type Tractor. We assigned value of 100 to the property "height". We printed the value before passing the object to another method. Now, we passed the object to another method called "change" from the calling-method " main ". We modified the height property to 200 in the called-method . Now, we tried to print the value of the property in the Calling method. It shows that the Object is modified in the called-method.

Similarly, we can pass Java objects to the Constructor using Pass by Reference or simply Reference . 

This concludes that Java Objects are passed to methods by Reference . Here also, we pass the memory location pointed by one Reference variable to another Reference variable of a Called method as a Value only. So, you are actually passing Values (memory locations represented by integer or long data type). But the actual passed-object can only be referenced by a Reference variable. Interviewers take advantage of this tricky logic to confuse you. If someone asks in C language point of view , say that it is by Reference . If they ask in Java point of view , say that it is by Value .

Let us know more about Java Classes with different Constructors and Methods in coming chapters.

Share this Last Minute Java  Tutorial explaining Java Object Assignment using Reference and Java Object Passing with Pass by Reference with your friends and colleagues to encourage authors.

Java Class Structure Tutorial

Java Method Signature Rules Tutorial

  • Artificial Intelligence
  • Generative AI
  • Cloud Computing
  • Data Management
  • Emerging Technology
  • Technology Industry
  • Software Development
  • Microsoft .NET
  • Development Tools
  • Open Source
  • Programming Languages
  • Enterprise Buyer’s Guides
  • Newsletters
  • Foundry Careers
  • Terms of Service
  • Privacy Policy
  • Cookie Policy
  • Copyright Notice
  • Member Preferences
  • About AdChoices
  • E-commerce Affiliate Relationships
  • Your California Privacy Rights

Our Network

  • Computerworld
  • Network World

rafael_del nero

Does Java pass by reference or pass by value?

You might know that java passes by value, but it helps to understand why. here's what happens when you pass mutable and immutable object references in java..

Scoring the winning points at a basketball game

Many programming languages allow passing objects by reference or by value. In Java, we can only pass object parameters by value. This imposes limits and also raises questions. For instance, if the parameter value is changed in the method, what happens to the value following method execution? You may also wonder how Java manages object values in the memory heap. This article helps you resolve these and other common questions about object references in Java.

Passing object references in Java

In this article you’ll learn the difference between passing by reference and passing by value in Java and how to pass Java object references:

‘Pass by reference’ and ‘pass by value’ defined

Java object references are passed by value, passing primitive types in java, passing immutable object references in java, passing mutable object references in java.

  • What to avoid when passing object references
  • What to remember about passing object references

Pass by reference  means we pass the location in memory where the variable’s value is stored and pass by value means we pass a copy of the variable’s actual value. It’s a bit more complicated than that, of course, but this definition is a good starting point.

  • Passing by value means we pass a copy of the value.
  • Passing by reference means we pass the real reference to the variable in memory.

All object references in Java are passed by value. This means that a copy of the value will be passed to a method. The tricky part is that passing a copy of the value changes the real value of the object. This example should help you understand why:

What do you think the simpson.name will be after the transformIntoHomer method is executed?

In this case, it will be Homer! The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.

If you’re still not sure how this works, consider the following diagram:

Flow diagram of object references in Java

Like object types, primitive types are also passed by value. Can you guess what will happen to the primitive types in the following code example?

If you determined that the value would change to 30, you are correct. It’s 30 because (again) Java passes object parameters by value. The number 30 is just a copy of the value, not the real value. Primitive types are allocated in the stack memory, so only the local value will be changed. In this case, there is no object reference.

What if we did the same test with an immutable String object? Notice what happens when we change the value of a String :

What do you think the output will be? If you guessed “” then congratulations! That happens because a String object is immutable , which means that the fields inside the String are final and can’t be changed.

Making the String class immutable gives us better control over one of Java’s most used objects. If the value of a String could be changed, it would create many bugs. Note, also, that we are not changing an attribute of the String class; instead, we’re simply assigning a new String value to it. In this case, the “Homer” value will be passed to name in the changeToHomer method. The String “Homer” will be eligible to be garbage collected as soon as the changeToHomer method completes execution. Even though the object can’t be changed, the local variable will be.

Unlike String , most objects in the JDK are mutable, like the StringBuilder class. The example below is similar to the previous one, but features StringBuilder rather than String :

Can you guess the output for this example? In this case, because we’re working with a mutable object, the output will be “Homer Simpson.” You could expect the same behavior from any other mutable object in Java.

Summary of what you’ve learned

You’ve learned that Java objects are passed by value, meaning that a copy of the value is passed . Just remember that the copied value points to a real object in the Java memory heap. Also, remember that passing by value changes the value of the real object.

What to avoid when passing Java object references

  • Don’t try to change an immutable value by reference.
  • Don’t try to change a primitive variable by reference.
  • Don’t expect the real object won’t change when you change a mutable object parameter in a method (it will change).

What to remember about passing Java object references

  • Java always passes parameter variables by value.
  • Object variables in Java always point to the real object in the memory heap.
  • A mutable object’s value can be changed when it is passed to a method.
  • An immutable object’s value cannot be changed, even if it is passed a new value.

Test what you’ve learned about object references

Now, let’s test what you’ve learned about object references. In the code example below, you see the immutable String and the mutable StringBuilder class. Each is being passed as a parameter to a method. Knowing that Java only passes by value, what do you believe will be the output once the main method from this class is executed?

Here are the options, check the end of the article for the answer.

A : Warrior=null Weapon=null B : Warrior=Dragon Weapon=Dragon C : Warrior=Dragon Knight Weapon=Dragon Sword D : Warrior=Dragon Knight Weapon=Sword

Solving the challenge

The first parameter in the above example is the warriorProfession variable, which is a mutable object. The second parameter, weapon, is an immutable String :

At the first line of this method, we append the Knight value to the warriorProfession variable. Remember that warriorProfession is a mutable object; therefore the real object will be changed, and the value from it will be “Dragon Knight.”

In the second instruction, the immutable local String variable will be changed to “Dragon Sword.” The real object will never be changed, however, since String is immutable and its attributes are final:

Finally, we pass null to the variables here, but not to the objects. The objects will remain the same as long as they are still accessible externally—in this case through the main method. And, although the local variables will be null, nothing will happen to the objects:

From this we can conclude that the final values from our mutable StringBuilder and immutable String will be:

The only value that changed in the changeWarriorClass method was warriorProfession , because it’s a mutable StringBuilder object. Note that warriorWeapon did not change because it’s an immutable String object.

The correct output from our Challenger code would be:

D : Warrior=Dragon Knight Weapon=Sword .

Video challenge! Debugging object references in Java

Debugging is one of the easiest ways to fully absorb programming concepts while also improving your code. In this video, you can follow along while I debug and explain object references in Java.

Learn more about Java

  • Get more quick code tips: Read all of Rafael’s articles in the InfoWorld Java Challengers series.
  • Check out more videos in Rafael’s Java Challengers video playlist .
  • Find even more Java Challengers on Rafael’s Java Challengers blog and in his book, with more than 70 code challenges .

Related content

Thread behavior in the jvm, polymorphism and inheritance in java, java inheritance vs. composition: how to choose, sorting java objects with comparable and comparator.

rafael_del nero

Rafael del Nero is a Java Champion and Oracle Ace, creator of the Java Challengers initiative, and a quiz master in the Oracle Dev Gym. Rafael is the author of "Java Challengers" and "Golden Lessons." He believes there are many techniques involved in creating high-quality software that developers are often unaware of. His purpose is to help Java developers use better programming practices to code quality software for stress-free projects with fewer bugs.

More from this author

Comparing java objects with equals() and hashcode(), replace calendar with localdate in java programs, shallow and deep copy: two ways to copy objects in java, when to use abstract classes vs. interfaces in java, how to write reusable java code, make java fast performance tuning java, all about java class loaders, most popular authors.

java object reference assignment

Show me more

How to choose the right low-code, no-code, or process automation platform.

Image

Qdrant review: A highly flexible option for vector search

Image

The other shoe drops on generative AI

Image

How to use dbm to stash data quickly in Python

Image

How to auto-generate Python type hints with Monkeytype

Image

How to make HTML GUIs in Python with NiceGUI

Image

Javatpoint Logo

Java Tutorial

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

JavaTpoint

Java, being an object-oriented programming language, allows the use of reference variables to work with objects and their data. In Java, objects are created dynamically on the heap memory, and reference variables are used to hold the memory address of these objects. This concept of reference variables is fundamental to Java's approach to object-oriented programming.

In Java, a reference variable is a variable that holds the memory address of an object rather than the actual object itself. It acts as a reference to the object and allows manipulation of its data and methods. Reference variables are declared with a specific type, which determines the methods and fields that can be accessed through that variable.

When an object is created using the new keyword, memory is allocated on the heap to store the object's data. The reference variable is then used to refer to this memory location, making it possible to access and manipulate the object's properties and behaviors.

Here's an example that demonstrates the concept of reference variables in Java:

The code creates a Car object, assigns values to its brand and year properties, and then uses the reference variable myCar to access and print those values. Therefore, the output displays the brand as "Toyota" and the year as "2021".

In the example above, we declare a reference variable called myCar of type Car. Then, we create a new Car object using the new keyword and assign its reference to myCar. After that, we can use the myCar reference variable to access and modify the object's properties (brand and year) as well as perform actions on the object.

Reference variables offer several benefits and play a crucial role in Java programming:

Reference variables allow programmers to work with objects, access their properties, and invoke their methods. They enable object-oriented programming principles such as encapsulation, inheritance, and polymorphism. Reference variables only store the memory address of an object rather than the entire object itself. This approach helps conserve memory by avoiding unnecessary object duplication. Reference variables are often used when passing objects as arguments to methods or returning objects from methods. This allows for efficient memory usage and facilitates modular programming. Reference variables enable dynamic behavior in Java programs. Different objects can be assigned to the same reference variable, allowing flexibility in handling different types of objects at runtime. Using reference variables, developers can control the lifetime of objects dynamically. When a reference variable is no longer referencing an object, the object becomes eligible for garbage collection, freeing up memory resources.

It's important to note that reference variables are distinct from primitive variables in Java. Primitive variables directly hold the actual values (e.g., int, boolean, etc.) rather than references to objects.

In conclusion, reference variables in Java provide a mechanism to work with objects by holding their memory addresses. They enable object manipulation, memory efficiency, dynamic behavior, and control over object lifetimes. Understanding and effectively using reference variables is crucial for developing robust and flexible Java applications.





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

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 is an object-oriented programming language. The core concept of the object-oriented approach is to break complex problems into smaller objects.

An object is any entity that has a state and behavior . For example, a bicycle is an object. It has

  • States : idle, first gear, etc
  • Behaviors : braking, accelerating, etc.

Before we learn about objects, let's first know about classes in Java.

A class is a blueprint for the object. Before we create an object, we first need to define the class.

We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.

Since many houses can be made from the same description, we can create many objects from a class.

  • Create a class in Java

We can create a class in Java using the class keyword. For example,

Here, fields ( variables ) and methods represent the state and behavior of the object respectively.

  • fields are used to store data
  • methods are used to perform some operations

For our bicycle object, we can create the class as

In the above example, we have created a class named Bicycle . It contains a field named gear and a method named braking() .

Here, Bicycle is a prototype. Now, we can create any number of bicycles using the prototype. And, all the bicycles will share the fields and methods of the prototype.

Note : We have used keywords private and public . These are known as access modifiers. To learn more, visit Java access modifiers .

  • Java Objects

An object is called an instance of a class. For example, suppose Bicycle is a class then MountainBicycle , SportsBicycle , TouringBicycle , etc can be considered as objects of the class.

Creating an Object in Java

Here is how we can create an object of a class.

We have used the new keyword along with the constructor of the class to create an object. Constructors are similar to methods and have the same name as the class. For example, Bicycle() is the constructor of the Bicycle class. To learn more, visit Java Constructors .

Here, sportsBicycle and touringBicycle are the names of objects. We can use them to access fields and methods of the class.

As you can see, we have created two objects of the class. We can create multiple objects of a single class in Java.

Note : Fields and methods of a class are also called members of the class.

  • Access Members of a Class

We can use the name of objects along with the . operator to access members of a class. For example,

In the above example, we have created a class named Bicycle . It includes a field named gear and a method named braking() . Notice the statement,

Here, we have created an object of Bicycle named sportsBicycle . We then use the object to access the field and method of the class.

  • sportsBicycle.gear - access the field gear
  • sportsBicycle.braking() - access the method braking()

We have mentioned the word method quite a few times. You will learn about Java methods in detail in the next chapter.

Now that we understand what is class and object. Let's see a fully working example.

  • Example: Java Class and Objects

In the above program, we have created a class named Lamp . It contains a variable: isOn and two methods: turnOn() and turnOff() .

Inside the Main class, we have created two objects: led and halogen of the Lamp class. We then used the objects to call the methods of the class.

  • led.turnOn() - It sets the isOn variable to true and prints the output.
  • halogen.turnOff() - It sets the isOn variable to false and prints the output.

The variable isOn defined inside the class is also called an instance variable. It is because when we create an object of the class, it is called an instance of the class. And, each instance will have its own copy of the variable.

That is, led and halogen objects will have their own copy of the isOn variable.

Example: Create objects inside the same class

Note that in the previous example, we have created objects inside another class and accessed the members from that class.

However, we can also create objects inside the same class.

Here, we are creating the object inside the main() method of the same class.

Table of Contents

  • Introduction
  • Example: Create objects inside a class

Sorry about that.

Related Tutorials

Java Tutorial

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

Overview of Java

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

Basics of Java

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

Operators in Java

  • Java Variables
  • Scope of Variables In Java

Wrapper Classes in Java

Input/output in java.

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

Flow Control in Java

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

Java Assignment Operators with Examples

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

OOPS in Java

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

Access Modifiers in Java

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

Inheritance in Java

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

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

Constructors in Java

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

Methods in Java

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

Keywords in Java

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

Memory Allocation in Java

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

Classes of Java

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

Packages in Java

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

Exception Handling in Java

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

File Handling in Java

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

JDBC - Java Database Connectivity

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

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

Types of Operators: 

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

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

Assignment Operators

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

Types of Assignment Operators in Java

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

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

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

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

1. (=) operator: 

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

Syntax:  

Example:  

2. (+=) operator: 

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

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

Reason for the Above Calculation

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

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

3. (-=) operator: 

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

4. (*=) operator:

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

5. (/=) operator: 

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

6. (%=) operator: 

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

Please Login to comment...

Similar reads.

  • Java-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

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

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

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

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

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

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

  • The JavaScript guide
  • The JavaScript reference

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

Learn how to program in JavaScript with guides and tutorials.

For complete beginners

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

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

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

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

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

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

JavaScript guide

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

Intermediate

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

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

Overview of available data structures in JavaScript.

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

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

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

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

Memory life cycle and garbage collection in JavaScript.

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

Browse the complete JavaScript reference documentation.

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

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

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

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

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

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

Why is reference assignment atomic in Java?

As far as I know reference assignment is atomic in a 64 bit JVM. Now, I assume the jvm doesn't use atomic pointers internally to model this, since otherwise there would be no need for Atomic References. So my questions are:

Is atomic reference assignment in the "specs" of java/Scala and guaranteed to happen or is it just a happy coincidence that it is that way most times ?

Is atomic reference assignment implied for any language that compiles to the JVM's bytecode (e.g. clojure, Groovy, JRuby, JPython...etc) ?

How can reference assignment be atomic without using an atomic pointer internally ?

  • concurrency

George's user avatar

  • @JornVernee I meant assignment not swapping, thanks for the correction –  George Commented May 31, 2017 at 11:21
  • This might give a first clue: stackoverflow.com/questions/23232242/… –  GhostCat Commented May 31, 2017 at 11:35
  • I did... however I've been searching all over the internet for how getfield, putfiled and iastore are implemented and I haven't found an explaination that doesn't involve digging through the openjvm code, which I'm not proficient enough to do :( –  George Commented May 31, 2017 at 12:23

3 Answers 3

First of all, reference assignment is atomic because the specification says so. Besides that, there is no obstacle for JVM implementors to fulfill this constraint, as 64 Bit references are usually only used on 64 Bit architectures, where atomic 64 Bit assignment comes for free.

Your main confusion stems from the assumption that the additional “Atomic References” feature means exactly that, due to its name. But the AtomicReference class offers far more, as it encapsulates a volatile reference, which has stronger memory visibility guarantees in a multi-threaded execution.

Having an atomic reference update does not necessarily imply that a thread reading the reference will also see consistent values regarding the fields of the object reachable through that reference. All it guarantees is that you will read either the null reference or a valid reference to an existing object that actually was stored by some thread. If you want more guarantees, you need constructs like synchronization, volatile references, or an AtomicReference .

AtomicReference also offers atomic update operations like compareAndSet or getAndSet . These are not possible with ordinary reference variables using built-in language constructs (but only with special classes like AtomicReferenceFieldUpdater or VarHandle ).

Basil Bourque's user avatar

  • 2 An “atomic pointer” isn’t necessarily an “atomic reference”, in the sense of AtomicReference . Hence, it was necessary to point out that references (i.e. the underlying pointers) are atomic, still don’t match the functionality of an AtomicReference . –  Holger Commented May 31, 2017 at 15:54
  • 3 “Publishing” means assigning to a variable that is visible to other threads. And no, there are no guaranties regarding visibility of previous updates when publishing though normal references. If you write point=new Point(42,100) and point is neither final nor volatile , other threads may see the new reference, while still seeing the default value ( 0 ) for either, x or y , or both (in the absence of other synchronization). –  Holger Commented May 31, 2017 at 15:57
  • 3 This is not about an older instance; the reference might have been null before the assignment, that doesn’t matter. The issue is, new Point(42,100) is not an atomic operation. It creates a new Point instance, all fields being at their default value ( 0 for int ), then, the constructor will be executed, which will assign the values 42 to x and 100 to y , then the reference is assigned to point , from a single thread’s point of view . A different thread may see these actions out of order, see the reference to the new Point instance without seeing the effect of the assignments. –  Holger Commented May 31, 2017 at 16:36
  • 2 This doesn’t apply to immutable objects. If you declare x and y as final , they’re immune to such data races. Alternatively, you may declare point as final , but this implies that the whole action is part of a constructor or initializer. Or, well, declaring point as volatile ensures that other threads see all previous updates ( x=42; y=100; ) when seeing the new Point instance through the point reference. –  Holger Commented May 31, 2017 at 16:37
  • 2 @Powet any reference assignment that doesn’t care about the previous reference, is atomic. The update operations provided by AtomicReference include compareAndSet (“only assign the new reference if the old reference has the expected value”) and getAndSet (“give me the old reference after assigning the new one”). If you try to implement the same logic without AtomicReference , it will inevitably consist of more than one access to the field, so it’ll be obvious why this wouldn’t be atomic (without additional measures). –  Holger Commented Apr 16 at 8:16

Atomic reference assignment is in the specs.

Writes to and reads of references are always atomic, regardless of whether they are implemented as 32 or 64 bit values.

Quoted from JSR-133: Java(TM) Memory Model and Thread Specification , section 12 Non-atomic Treatment of double and long , http://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf .

Anonymous's user avatar

  • Ok, that answers the first part but not the other 2. To be honest the thing that I'm most curios about here is how this behavior happens if references are not atomic pointers and that's related to how one would implement a JVM rather than the specifications for java and/or the jvm. –  George Commented May 31, 2017 at 12:17
  • True. I on purpose did not pretend to be a wiseguy on matters where I’m not sure. The way I understand it, though, this is a spec of the JVM, so I would expect it to cover all languages running on the JVM. And the way I read it, in requires internal pointer operations to happen atomically (at least as seen from outside the JVM). –  Anonymous Commented May 31, 2017 at 12:25
  • Well yes, but I doubt those are actual atomic pointer operations since otherwise things like compare and swap would also be atomic using standard references. –  George Commented May 31, 2017 at 12:29
  • 1 Nice answer - good find; my vote for that. And thanks for leaving out that small part that left room for my answer ;-) –  GhostCat Commented May 31, 2017 at 12:29
  • 3 The linked PDF describes the memory model for Java 5 proposed by JSR133. To prove that it indeed made it into the Java 5 JLS and is still there today, it’s better to link to JLS §17.7 . –  Holger Commented May 31, 2017 at 14:38

As the other answer outlines, the Java Memory Model states that references read/writes are atomic.

But of course, that is the Java language memory model. On the other hand: no matter if we talk Java or Scala or Kotlin or ... in the end everything gets compiled into bytecode .

There are no special bytecode instructions for Java. Scala in the end uses the very same instructions.

Leading to: the properties of that memory model must be implemented inside the VM platform. Thus they must apply to other languages running on the platform as well.

GhostCat's user avatar

  • Since the name was ' JavaTM Memory Model' I was unsure if it referred to the JVM as a whole and as such I assumed there might be instructions to non atomically asign available to other JVM languages –  George Commented May 31, 2017 at 12:40
  • Back then when that memory model was written, there was only the Java language on the Java VM platform. Methinks. –  GhostCat Commented May 31, 2017 at 12:41
  • Even now, I don't think there are JVM instructions that aren't used by Java itself. –  Jasper-M Commented May 31, 2017 at 12:44
  • 5 @Jasper-M: there are. E.g., swap is never used by javac generated code. In Java 7, the invokedynamic instruction was not used by Java itself, which is quite a big feature of that JVM version… –  Holger Commented May 31, 2017 at 14:26
  • 3 One thing to keep in mind when drawing this conclusion, is, that this only applies if the concepts of that other language (i.e. references) are compiled 1:1 to the equivalent byte code artifacts. E.g. a reference of a particular language might be so far away from what Java’s object references do, that it doesn’t match a sole byte code reference variable, but, e.g. a compound data structure. For Java, it is impossible to encounter an object reference having a not-yet-initialized vtable, but that doesn’t have to apply to another language, having an entirely different method dispatch algorithm. –  Holger Commented Jun 1, 2017 at 8:28

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 scala concurrency jvm atomic or ask your own question .

  • Featured on Meta
  • Announcing a change to the data-dump process
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...

Hot Network Questions

  • What to do about chain rubbing on unusually placed chainstay?
  • Where can I find a switch to alternate connections between two pairs of two wires?
  • Report a police emergency at home while abroad
  • UK citizen travel document to enter Ireland by air
  • What are the not-winglet wingtips on the CL-415?
  • Bicolor/double-sided feathers as part of a thermoregulatory apparatus?
  • Connect 3 on different board sizes
  • 2008 civic ex where do wires from connector on top of alternator run to
  • Which Jesus died or in what sense did Jesus ("God") die for our sins
  • Are "very alone" and "very much alone" interchangeable?
  • Can someone legally go out in public with only their underwear on?
  • Structure of the headline "Olympics organizers scramble as furor over woke blasphemy grows."
  • What do the H and the E stand for in John Cohn's name?
  • Is there a difference between "set" and "collection"?
  • How do manganese nodules in the ocean sustain oxygen production without depleting over geological time scales?
  • Why try to explain the unexplainable?
  • What concerns are there with soldering stainless steel cable on electronics?
  • Is it dangerous if an LED lightbulb fails to light up?
  • Array of Objects not getting reflecting in LWC html
  • Pistorius: “We must be ready for war by 2029”. Why 2029?
  • Terminology: A "corollary" to a proof?
  • What did Rohan and Gondor think Sauron was?
  • Why is it plural for one example and singular for the second
  • How can life which cannot live on the surface of a planet naturally reach the supermajority of the planet's caves?

java object reference assignment

IMAGES

  1. What are object referenced variables in Java ?

    java object reference assignment

  2. Java Programming # 44

    java object reference assignment

  3. Classes Part 3: Objects and References (Java)

    java object reference assignment

  4. java.lang.ref.ReferenceQueue-Klasse in Java

    java object reference assignment

  5. Java: Objects and Object References

    java object reference assignment

  6. Object in java Assignment and Object Passing By Value

    java object reference assignment

VIDEO

  1. Java Programming # 44

  2. Object initialization in Java By Reference, By Method, By Constructor #codewithravikant #java

  3. Java Objects Explained

  4. What is an Object in Java| lec 14| Java Tutorial| BhanuPriya

  5. Tittel में OBJ कैसे लगाए

  6. What is Object In Java Script ?

COMMENTS

  1. Java Object Assignment

    Test t2 = t1; You are actually creating another Test reference, and you assign it to refer to the same object that t1 refers to. So t1.i = 1; will affect t2.i for it is the same object after all. As for the Strings, Strings are immutable and can not be modified after instantiated. Regarding your edit:

  2. Reference Variable in Java

    1. Reference variable is used to point object/values. 2. Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java. Reference variables hold the objects/values of reference types in Java. 3. Reference variable can also store null value. By default, if no object is passed to a reference variable then it will store a ...

  3. Using Objects (The Java™ Tutorials > Learning the Java Language

    The first statement invokes rectOne's getArea() method and displays the results. The second line moves rectTwo because the move() method assigns new values to the object's origin.x and origin.y.. As with instance fields, objectReference must be a reference to an object. You can use a variable name, but you also can use any expression that returns an object reference.

  4. Object Type Casting in Java

    By the way, all Java objects are polymorphic because each object is an Object at least. We can assign an instance of Animal to the reference variable of Object type and the compiler won't complain: Object object = new Animal(); That's why all Java objects we create already have Object-specific methods, for example toString().

  5. Java Object Reference Variable

    Object reference variables act differently when an assignment takes place. For example, Box b1 = new Box(); Box b2 = b1; After this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same object as does b1.

  6. Creating and Using Objects

    The object is unreferenced, and its resources are free to be recycled by the Java Virtual Machine. Calling an Object's Methods. You also use an object reference to invoke an object's method. You append the method's simple name to the object reference, with an intervening dot operator (.). Also, you provide, within enclosing parentheses, any ...

  7. PDF References (pointers) inJava

    Dereferencing. Dereferencing: Accessing the value of the pointee for some reference variable. Is done with the "dot" (.) operator to access a field or method of an object. Examples: dereferencing empRef in the previous slide gives back its pointee, the Employee object. String myName = empRef.getName();

  8. Java. Operations on objects. The operation of assigning objects. Object

    2. How does the assignment of objects = is realized? General form. The assignment operation has the following general form: obj1 = obj2; here. obj1, obj2 - reference to objects that have the same type (class). When assigning objects, the value of the reference to the object obj2 is assigned to the reference obj1. In fact, only references are ...

  9. Reference Variables and Assignment

    Reference Variables and Assignment. In an assignment operation, object reference variables act differently than do variables of a primitive type, such as int. When you assign one primitive-type variable to another, the situation is straightforward. The variable on the left receives a copy of the value of the variable on the right.

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

  11. Lesson 10

    Lesson 10- Object References. INTRODUCTION: This lesson discusses object reference variables. These variables refer to objects (as opposed to holding a primitive data value.) The key topics for this lesson are: A. Primitive Data Type Variables. B. Object Reference variables. C. Variable Versus Object Reference Assignment.

  12. Java Object Assignment and Object Passing By Value or Reference

    In Java, we create Classes. We create objects of the Classes. Let us know if it is possible to assign a Java Object from one variable to another variable by value or reference in this Last Minute Java Tutorial. We also try to know whether it is possible to pass Java Objects to another method by Value or Reference in this tutorial.. You may also read about Introduction to Java Class Structure.

  13. Does Java pass by reference or pass by value?

    Passing by value means we pass a copy of the value.; Passing by reference means we pass the real reference to the variable in memory.; Java object references are passed by value. All object ...

  14. What is a Reference Variable in Java

    In Java, a reference variable is a variable that holds the memory address of an object rather than the actual object itself. It acts as a reference to the object and allows manipulation of its data and methods. Reference variables are declared with a specific type, which determines the methods and fields that can be accessed through that ...

  15. Java Class and Objects (With Example)

    Java Class and Objects. Java is an object-oriented programming language. The core concept of the object-oriented approach is to break complex problems into smaller objects. An object is any entity that has a state and behavior. For example, a bicycle is an object. It has. States: idle, first gear, etc. Behaviors: braking, accelerating, etc.

  16. java

    Object obj1=Object() Object obj2=obj1; two objects will be created. That is property values of obj1 are copied to obj2. If you do not want to create a new object, you should use pointers. Ex: Object obj1=Object() Object *obj1ref=&obj1; //this is like assigning reference in java.

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

  18. JavaScript

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

  19. Are arrays passed by value or passed by reference in Java?

    Like all Java objects, arrays are passed by value ... but the value is the reference to the array. So, when you assign something to a cell of the array in the called method, you will be assigning to the same array object that the caller sees. This is NOT pass-by-reference. Real pass-by-reference involves passing the address of a variable.

  20. Why is reference assignment atomic in Java?

    First of all, reference assignment is atomic because the specification says so. Besides that, there is no obstacle for JVM implementors to fulfill this constraint, as 64 Bit references are usually only used on 64 Bit architectures, where atomic 64 Bit assignment comes for free. Your main confusion stems from the assumption that the additional ...