In this case, it makes sense to see how the code looks in both cases after compilation.
Java code:
int x = 10; Random sc = new Random(); int a; for (int i = 0; i < x; i++){ a = sc.nextInt(); System.out.println(a); }
Part of the code byte that executes the instructions a = sc.nextInt();System.out.println(a); :
LINENUMBER 14 L5 ALOAD 2 INVOKEVIRTUAL java/util/Random.nextInt ()I ISTORE 3 L6 LINENUMBER 15 L6 GETSTATIC java/lang/System.out : Ljava/io/PrintStream; ILOAD 3 INVOKEVIRTUAL java/io/PrintStream.println (I)V
The ISTORE 3 and ILOAD 3 represent working with the local variable а .
Java code:
int x = 10; Random sc = new Random(); for (int i = 0; i < x; i++){ int a = sc.nextInt(); System.out.println(a); }
Part of the code byte that executes instructions int a = sc.nextInt(); System.out.println(a); int a = sc.nextInt(); System.out.println(a); :
LINENUMBER 13 L5 ALOAD 2 INVOKEVIRTUAL java/util/Random.nextInt ()I ISTORE 4 L6 LINENUMBER 14 L6 GETSTATIC java/lang/System.out : Ljava/io/PrintStream; ILOAD 4 INVOKEVIRTUAL java/io/PrintStream.println (I)V
The ISTORE 4 and ILOAD 4 represent working with the local variable а .
About local variables in jvm can be read here . From the above code, it is clear that in both cases we get an identical byte code, which means that the memory is used in the first case as much as in the second and the speed of work will be the same.