6

Newly learning java and for input, we did

Scanner scan = new Scanner(System.in);
String name;
System.out.println("What is your  name?");
name = scan.nextLine();
System.out.println(name);

However, I found that

Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
System.out.println(name);

works the same. Is this being taught to me in the bigger form because it's more generally used/is clearer or am I just being taught the bigger form since I'm a beginner to avoid too much confusion? (Basically, are there any reasons why people would use the expanded version rather than the condensed version?)

nobalG
  • 4,544
  • 3
  • 34
  • 72
pasta
  • 79
  • 8

3 Answers3

9

https://stackoverflow.com/a/288479

-> It seems that in some old C-Standards you had to declare all variables in the beginning of a method. So I think they are just adhering to this when teaching it like this, but nowadays there is no real reason for this.

Christian
  • 1,437
  • 2
  • 8
  • 14
4

Your correct extended version should be

Scanner scan = new Scanner(System.in);
String name;
System.out.println("What is your  name?");
name = scan.nextLine(); // no need of String keyword here
System.out.println(name);

And why someone would prefer it?

Consider a method definition, May be something like below,

public AccountDetails getDetails(Person person){
   Address address;
   AccountInfo accountInfo;
   address = person.getAddresses();
   accountInfo = getDetailsOfAccount();

.......many more lines
   return accountDetails;
}

So from the above code, declaring all the variables at the top of the method with proper naming conventions is just helping you out upfront like a sign barrier on the road ahead, that what the method is dealing with.

Other than that, you can follow any version of the code, both are equally same.

nobalG
  • 4,544
  • 3
  • 34
  • 72
2

In your case its one and the same thing. It is more useful though when used in the context of variable scoping.

Creating a reference variable before initializing it with a value is the preferred way while using code blocks, so that the reference can be used outside of the block as well. Check out this example:

int sum = 0;
for(int idx=0; idx<5; idx++) {
   sum+=idx;
}
return sum;
Lalit Mehra
  • 1,183
  • 1
  • 13
  • 33