Invoke method without instance via constructor in Java

  • A+

I have a great doubt as to what this action is called and how it is administered in memory.

Inside the main() method I make these sentences or instructions.

public static void main(String[] args) {     int i = 0;     int j = new Random().nextInt(100); // As it is called this way of acting or as it is called. } 
  • I have clear that what it does is directly invoke the Random class constructor method, invoke the nextInt method and generate a random number that is stored inside the int j variable but I don't know how to define this type of action and I don't know if it is correct to do this kind of instructions.

  • I'm curious to know what this type of action is called.

Thank you for your attention.

P.D : Sorry .. I'm learning


int j = new Random().nextInt(100); 

is almost the same as

Random r = new Random(); int j = r.nextInt(100); 

i.e. both create an instance (object) of the Random class, and then call a method of that instance.

The difference is that in the first case, you don't keep a reference to the created instance, so you can't access that instance again, and since no reference to that instance exists, it can be immediately garbage collected.

As Andy suggested, you can look at it as if you created an instance of the Random class and assigned it to a variable, called the nextInt() method, and then exited the scope in which that variable was declared:

int j; {     Random r = new Random();     j = r.nextInt(100); } // at this point you have no access to the Random instance 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: