Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason to create the string variable before input?

Tags:

java

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?)

like image 489
pasta Avatar asked Aug 30 '26 15:08

pasta


1 Answers

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.

like image 158
Christian Avatar answered Sep 01 '26 05:09

Christian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!