Semester 1 Exam Practice: Java Code Snippets
Assume all the following code snippets are part of the main method of a Java class, unless
otherwise stated.
public class Snippets extends IBIO
{ public static void main(String[] args)
{
// snippet code …
}
}
Think in terms of:
• What does the code snippet do?
• How many variables are in the algorithm?
• Trace the code
• What will the output be, given the inputs provided?
1. Determine the output of the following snippet:
int a = 17;
int b = a % 10;
if( a > b )
{ output( b + " " + a ); }
else
{ output( a + " " + b ); }
, 2. Calculate the outputs for the following values for mark: 120, 100, 70, 20, 5.
switch(mark/10)
{
case 10:
case 9:
case 8:
System.out.println("Excellent");
break;
case 7:
System.out.println("Very Good");
break;
case 6:
System.out.println("Good");
break;
case 5:
System.out.println("Work Hard");
break;
case 4:
System.out.println("Poor");
break;
case 3:
case 2:
case 1:
case 0:
System.out.println("Very Poor");
break;
default:
System.out.println("Invalid value Entered");
break;
}
3. Determine the output for num = 128
int temp = num, result = 0;
while(temp > 0)
{ result = result + (temp % 10);
temp = temp / 10;
}
System.out.println(result);
Assume all the following code snippets are part of the main method of a Java class, unless
otherwise stated.
public class Snippets extends IBIO
{ public static void main(String[] args)
{
// snippet code …
}
}
Think in terms of:
• What does the code snippet do?
• How many variables are in the algorithm?
• Trace the code
• What will the output be, given the inputs provided?
1. Determine the output of the following snippet:
int a = 17;
int b = a % 10;
if( a > b )
{ output( b + " " + a ); }
else
{ output( a + " " + b ); }
, 2. Calculate the outputs for the following values for mark: 120, 100, 70, 20, 5.
switch(mark/10)
{
case 10:
case 9:
case 8:
System.out.println("Excellent");
break;
case 7:
System.out.println("Very Good");
break;
case 6:
System.out.println("Good");
break;
case 5:
System.out.println("Work Hard");
break;
case 4:
System.out.println("Poor");
break;
case 3:
case 2:
case 1:
case 0:
System.out.println("Very Poor");
break;
default:
System.out.println("Invalid value Entered");
break;
}
3. Determine the output for num = 128
int temp = num, result = 0;
while(temp > 0)
{ result = result + (temp % 10);
temp = temp / 10;
}
System.out.println(result);