In the below program, the variable "int x" is declared inside the "while" loop.
Will the program generate many variables of int x while the loop is executed over and over again?
Should I declare the int x outside the loop? like, int x = ""; then in the loop x = console.nextInt();
Scanner console = new Scanner(System.in);
int sum = 0;
while (console.hasNextInt())
{
int x = console.nextInt();
sum = sum + x;
}
System.out.println(sum);
Thank you
Evilpanda H.
Level 10
declare a variable inside a loop
Under discussion
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
Thomas
11 November 2022, 07:28
I modified your example a little bit and ran the disassembler over it
v1:
JVM instruction set
v2
The resulting assembler code was pretty much the same despite some line numbers. So it seems the compiler is smart enough to optimize that on its own. But to be honest, declaring a variable isn't necessary at all and the compiler doesn't do that. And a link to the 0
Thomas
11 November 2022, 07:30
Result 1: javap -v Test.class
0
Thomas
11 November 2022, 07:31
result 2:
0
Evilpanda H.
11 November 2022, 12:13
Thank you Thomas. I think I got it. Java compiler is smarter than C compiler. Thank you.
+1