Home > categories > Hardware > Brackets > Java - difference between brackets or no brackets under For loop?
Question:

Java - difference between brackets or no brackets under For loop?

For a program trying to print out all the possible values of the AUGC combination of mRNA, the out put ofString aucg AUCG ; // Input, String class for(int i 0; i lt; aucg.length( ); i++) // Loop control { for (int j 0; j lt; aucg.length( ); j++) // Loop control { for(int k 0; k lt; aucg.length( ); k++) // Loop control // Output System.out.print ( + aucg.charAt(i) + aucg.charAt(j) + aucg.charAt(k) + ); System.out.println();}}is different from the output if we put brackets in the last For loop likefor(int k 0; k lt; aucg.length( ); k++) // Loop control{ // Output System.out.print ( + aucg.charAt(i) + aucg.charAt(j) + aucg.charAt(k) + ); System.out.println();}How is the output affected (or how is the program running differently) if we add or do not add the brackets under a For loop? Thanks.

Answer:

If you don't place brackets, the for loop will only execute the first following command in the loop. So in the first case where you don't place brackets, one iteration of the for-loop will consist of: System.out.print ( + aucg.charAt(i) + aucg.charAt(j) + aucg.charAt(k) + ); While, in the second case where you did place brackets, one iteration will be: System.out.print ( + aucg.charAt(i) + aucg.charAt(j) + aucg.charAt(k) + ); System.out.println(); And that it the difference.

Share to: