Javatpoint Logo
Javatpoint Logo

Aliasing in Java

When two or more references are used in Java to refer to the same object, this is called a "alias." When a user writes to an object and its owner does not expect it to change for multiple references, aliasing becomes problematic. Here, the aliasing code can become quite complicated very quickly, and debugging it can be very time-consuming. Let's understand Java Alias's operation.

How do alias work in Java?

Aliasing happens when numerous references are linked to the same object, as we have already covered. It also indicates that a place is modified through multiple aliases, each of which has multiple types.

Let's use an example. Two variable names, a and b, correspond to the types A and B. A is extended by B.

They both point to the same place in memory as well.

Aliasing in Java

Both a and b are pointing to the same memory address. The actual object that is saved, however, gets to decide which runtime technique to use.

Let us see another example.

The provided item has two names, such as b1 and b2, or both b1 and b2 belong to the same object. Objects can have multiple names, just like persons can.

Changes made to one aliased variable also affect the other, as the example below shows.

You will observe that the modifications made to one rectangle also affect the second rectangle after running the code.

Some sample programs on Java Alias are listed below.




Exception in thread "main" java.lang.ArrayStoreException: A
at Alias1.main(


This exception only occurs because Java handles aliases while the program is running. It won't be able to determine that the first one should be an object of B rather than A until the run time.



sample function 1 is called

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA