0

What is the difference between

        Scanner keyboard= new Scanner(System.in);
        int answer= keyboard.nextInt();

and

        int answer= new Scanner(System.in).nextInt();

I am a beginner here so thorough explanation would help a lot. Thanks in advance!

5
  • 1
    Do you know what a (local) variable is? Commented Jan 22, 2018 at 14:21
  • 1
    no difference. first you assign the Scanner to a variable and in the next example you don't. they are equal, but the first one is more equal than the other. Commented Jan 22, 2018 at 14:23
  • 3
    There is no difference, except that you can't reuse the Scanner instance of the second snippet. Commented Jan 22, 2018 at 14:24
  • 1
    There is no difference. In the first case, you just assign your "new Scanner" in a local variable whereas in the second case you directly use the "new Scanner". The first case can be useful if you have to read several user input in the same method, the second one is enough if you only have one user input at a time. Commented Jan 22, 2018 at 14:25
  • @C-Otto Yes, I do know what local variable is! Commented Jan 22, 2018 at 16:44

2 Answers 2

1
Scanner keyboard= new Scanner(System.in);
int answer= keyboard.nextInt();

In the above code a Scanner object is created in the heap memory and its reference is stored in a variable called keyboard(keyboard varible is stored in stack memory). Using variable keyboard you can able access the Scanner object at any point of the program.

 int answer= new Scanner(System.in).nextInt();

In the second statement you are creating object which is also stored in heap memory , but the reference of the object is not stored in any variable. So you cannot able to access this object anymore. After this statement the object in heap memory are ready to be garbage collected , since its reference is not used anymore.

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

Comments

0

The first statement initializes a Scanner object that can be used multiple times.

The second statement creates a new Scanner object for just that line of code. You would have to call a new Scanner object next time you need input.

It is better practice to create the variable than to create a new object each time.

4 Comments

If the input I need from a user is only "answer" and I am using this in a loop, second code would suffice, right?
for (int i; i<10; i++){ int answer= new Scanner(System.in).nextInt(); System.out.println(answer); }
As I was saying, that code would work, but programming conventions would prefer that you declare the Scanner object before you use it,
(Accidentally pressed send). It makes the code easier to read and understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.