sir mordred
sir mordred

Reputation: 161

Java Difference between { Object a = new Object(); a.getVariable() } and { new Object().getVariable() }

i don't know if its asked before (i searched but couldn't find)

Is there any difference between the following 2 code blocks?

1:

// Let's say we want to get variable from non-static object
Object a = new Object();
int varWeWant = a.getVariable();

2:

int varWeWant = new Object().getVariable();

as you see second option is one-line code and i know the java, both codes create object first and retrieve variable via method but i'm not java expert so i wonder if they have any differences ?

Sorry if it is silly question :D i was just wondered this for too long

thanx

Upvotes: 1

Views: 246

Answers (4)

Ralf Kleberhoff
Ralf Kleberhoff

Reputation: 7290

The result in varWeWant is the same.

Some minor differences:

  • In the first version you can later use the Object for other purposes, as you stored a reference to it in the a variable (that's obvious).
  • Introducing the variable a comsumes a small amount of memory.
  • As long as the variable a refers to this Object, the garbage collector cannot reclaim its memory. (But compiler and runtime optimizations might be able to free the memory earlier, as soon as a is no longer used).
  • Storing the reference in a variable will take a tiny amount of time.

Upvotes: 0

Stif Spear Subba
Stif Spear Subba

Reputation: 77

int x = new Object().getVariable(); This is done when the object have one time use. Object a = new Object(); //Creates an object named a This is done when object has multiple variables and functions. This way object is created only once and the variables and functions are called. If we were to use new Object().getSomeFunction() every time then new object is created every time. Its expensive memory wise and more lines has to be written.

Upvotes: 0

Carcigenicate
Carcigenicate

Reputation: 45750

The first creates an object that can be referred to later, then calls a method on it.

The second creates a temporary object that can only be used to call that single method.

Really, if you're using the second way, you should question if the object was necessary in the first place. It might make more sense to just make that method a standalone function unless you're using the Builder or similar pattern.

Upvotes: 5

both produce the same BUT option 2 is the object instance an anonymous reference... that means you can not do anything with that object after that statement...

Upvotes: 0

Related Questions