1

I'm learning Java and I can't understand why variables are created the way they are. For example: int[] numberArray = new int[10]; or StringBuilder newString = new StringBuilder();

Surely when you create the object (like an array of integers of size 10) the type can automatically be inferred and doesn't need to be specified again, or for the 2nd case, I'm creating a StringBuilder, which means Java would already know the object that it is going to be right?

I'm coming from having my main language be Python and while I know Java is statically typed it doesn't make sense that this is necessary.

  • 3
    It isn't. One is a declaration, the other an instantiation. – Stultuske Apr 07 '21 at 11:43
  • 3
    And with recent Java versions, the type of the variable can be inferred: `var numberArray = new int[10]` – Thilo Apr 07 '21 at 11:45
  • 1
    Not to mention that `numberArray` is *not* an array of `int`, and `newString` is *not* a `StringBuilder`: both are just references to the respective objects. – tquadrat Apr 07 '21 at 11:48

2 Answers2

6

Starting Java 10, Java has local variable inference, so you can write those as:

var numberArray = new int[10];

Note that this is really syntactic sugar, there is no dynamic typing involved.

M A
  • 71,713
  • 13
  • 134
  • 174
  • Thanks, but why is the `var` or `int` etc needed in the first place if Java can clearly work out the data type? – actuallyatiger Apr 07 '21 at 11:48
  • 1
    @actuallyatiger Consider the case of subtyping, a variable can have a different type than the assigned value; a variable can also be declared at some point and initialized later. In both cases, a type needs to be known. And using `var` or `int` itself is necessary to distinguish between declaring a variable and assigning to an existing local variable or field. – Mark Rotteveel Apr 07 '21 at 11:49
  • @actuallyatiger What Mark said, and I would also favor having `var` or `int` to ease readability. – M A Apr 07 '21 at 11:52
1

Somtimes, the type can't be infered, including generic, and you need the declaration to help you a bit with that

List<? extends Number> numberList = new ArrayList<Integer>();
Number anIntegerAsANumber = Integer.valueOf(5);

As MA said in his answer, var can be used since but there is a tradeoff, the fact you can't anymore work on interfaces like I did hereabove with List and ArrayList

var listOfIntegers = new ArrayList<>();
// Here the type of listOfIntegers is a ArrayList and thus can't be reused to store a LinkedList for example
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89