-2

I'm currently doing the mooc java course and I'm not able to understand why exactly we need to include new Random() part after declaring a new new variable randomVar with the class type Random?

   private Random randomNum = new Random(); // Why this? 

   private Random randomNum; //Instead of this? 
  • 5
    In Java a declaration does not initialize. Actually, in the second line, granted it's an instance variable, randomNum *is* initialized, to the default `null` value. Trying to get a random number from that will throw a NullPointerException. For a local variable see https://stackoverflow.com/questions/16415848/java-what-is-the-difference-between-assigning-null-to-object-and-just-declarati –  Aug 17 '19 at 07:53
  • Unlike in C++, in java everything is a reference; this is kinda equivalent to `Random *random = new Random()` – Coderino Javarino Aug 17 '19 at 07:54
  • See also https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it –  Aug 17 '19 at 07:58
  • Only declaring Random variable does not make sense in Java as it need Reference to that class – Lalit Verma Aug 17 '19 at 08:00
  • Thank you guys, The null pointer link was really helpful . And it solved the doubt for me – harikrishnan Aug 17 '19 at 08:30
  • @Jean-ClaudeArbaut Thank you ,that's what I was looking for – harikrishnan Aug 17 '19 at 08:31
  • @CoderinoJavarino Wrong. Variables of type char, byte, short, int, long, float, double and boolean [are not references](https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-4.2). –  Aug 17 '19 at 08:58
  • @Jean-ClaudeArbaut those aren't objects; I wasn't talking about primitive types – Coderino Javarino Aug 17 '19 at 09:57
  • @CoderinoJavarino Yet you wrote "in java everything is a reference". There is no "object" in your sentence. Which is thus wrong. For the reader passing by, there is no hint that you are talking specifically about objects. –  Aug 17 '19 at 10:21

1 Answers1

4

In Java there is no implicit calling of constructors. In your example, the variable will either be non-initialized or initialized to null (such as when declaring a class field). ie:

void foo() {
    Random r; // r never gets initialized
}
...
class Foo {
    Random r; // gets initialized to null
}

If you want to get an instance of an object, then new must be called somewhere, either directly during the variable declaration, or by assigning it from another variable which was already instantiated.

flakes
  • 21,558
  • 8
  • 41
  • 88