Loop based output questions
int a, b;
for (a = 6, b = 4; a <= 24; a = a + 6)
{
if (a % b == 0)
break;
}
System.out.println(a);
Output:
12
char ch = 'F';
int m = ch;
m=m+5;
System.out.println(m + " " + ch);
Output:
75 F
int i = 1;
int d = 5;
do
{
d = d * 2;
System.out.println(d);
i++;
}
while (i <= 5);
Output:
10 20 40 80 160
for (int i = 3; i <= 4; i++)
{
for (int j = 2; j < i; j++)
{
System.out.print("");
}
System.out.println("WIN");
}
Output:
WIN WIN
String arr[]= {"DELHI", "CHENNAI", "MUMBAI", "LUCKNOW", "JAIPUR"};
System.out.println(arr[0].length()> arr[3].length());
System.out.print(arr[4].substring(0,3));
Output:
false JAI
int i;
for ( i = 5 ; i > 10; i ++ )
System.out.println( i );
System.out.println( i * 4 );
Output:
20
int i;
for( i=5 ; i>=1 ;i--)
{
if(i%2 ==1)
continue;
System.out.print( i+ "");
}
Output:
42
public class Test
{
public static void main(String[] args)
{
for (int i = 0; i < 10; i++)
{
int x = 10;
}
}
}
Compile time error
Explanation: Curly braces are optional and without curly braces we can take only one statement under for loop which should not be declarative statement. Here we are declaring a variable that’s why we will get compile time error saying error: variable declaration not allowed here.
public class Test
{
public static void main(String[] args)
{
int i = 0;
for (System.out.println("HI"); i < 1; i++)
{
System.out.println("HELLO GEEKS");
}
}
}
Compile time error
Explanation: Initialization part of the for loop will be executed only once in the for loop life cycle. Here we can declare any number of variables but should be of same type. By mistake if we are trying to declare different data types variables then we will get compile time error saying error: incompatible types: String cannot be converted to int.
public class Test
{
public static void main(String[] args)
{
int i = 0;
for (System.out.println("HI"); i < 1; i++)
{
System.out.println("HELLO GEEKS");
}
}
}
Output:
HI HELLO GEEKS
Explanation:I n the initialization section we can take any valid java statement including System.out.println(). In the for loop initialization section is executed only once that’s why here it will print first HI and after that HELLO GEEKS
public class Test
{
public static void main(String[] args)
{
for (int i = 0;; i++)
{
System.out.println("HELLO GEEKS");
}
}
}
Output:
HELLO GEEKS (Infinitely)
Explanation: In the conditional check we can take any valid java statement but should be of type Boolean. If we did not give any statement then it always returns true.
public class Test
{
public static void main(String[] args)
{
for (int i = 0; i < 1; System.out.println("WELCOME"))
{
System.out.println("GEEKS");
}
}
}
Output:
GEEKS WELCOME(Infinitely)
Explanation: In increment-decrement section we can take any valid java statement including System.out.println(). Here in the increment/decrement section, a statement is there, which result the program to go to infinite loop.
java java tutorials learn java study java