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
  • 3
    It isn't. One is a declaration, the other an instantiation. Commented Apr 7, 2021 at 11:43
  • 3
    And with recent Java versions, the type of the variable can be inferred: var numberArray = new int[10] Commented Apr 7, 2021 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. Commented Apr 7, 2021 at 11:48

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but why is the var or int etc needed in the first place if Java can clearly work out the data type?
@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.
@actuallyatiger What Mark said, and I would also favor having var or int to ease readability.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.