100% found this document useful (2 votes)
3K views

Lesson 10 Exercises Answer Key

This document provides answers to questions about Java switch statements. It includes examples of using different data types like strings and characters in switch statements, and how fall-through works. It also covers whether the default case is mandatory and how to convert a string to a character.

Uploaded by

api-236387090
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
3K views

Lesson 10 Exercises Answer Key

This document provides answers to questions about Java switch statements. It includes examples of using different data types like strings and characters in switch statements, and how fall-through works. It also covers whether the default case is mandatory and how to convert a string to a character.

Uploaded by

api-236387090
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Key to Exercise on Lesson 10

Answers 10-3

1. What are the primary three permissible data types to use for x in the following?
switch (x){ . . . }
String, int and char (also short and byte)
2. int x = 3, p = 5, y =-8;
switch(x)
{
case 2:
p++;
case 3:
case 4:
y+=(--p);
break;
case 5:
y+=(p++);
}
System.out.println(y); //-4
3. Write a switch structure that uses the character myChar. It should increment the integer
variable, y, if myChar is either a capital or small letter G. It should decrement y if
myChar is either a capital or a small letter M. If myChar is anything else, add 100 to y.
switch (myChar)
{
case G:
case g:
y++;
break;
case M:
case m:
y--;
break;
default:
y = y + 100;
}
4. What is output by the following code?
String s = Green;
q = 0;
switch(s)
{
case Red:
q++;
case Green:
q++;
case Blue:
q++;
case Yellow:
q++;
default:
q++;
}
System.out.println(--q); //3

Answers 10-4
5. Write a line of code that declares the variable chr as a character type and assigns the
letter z to it.
char chr = z;
6. What is output by the following?
int x = 10, y = 12;
System.out.println( The sum is + x + y ); //The sum is 1012
System.out.println( The sum is + (x + y) ); //The sum is 22
7. Convert the following code into a switch statement.
if(speed = = 75)
{
System.out.println(Exceeding speed limit);
}
else if( (speed = = 69) || (speed = = 70) )
{
System.out.println(Getting close);
}
else if(speed = = 65)
{
System.out.println(Cruising);
}
else
{
System.out.println(Very slow);
}

switch(speed)
{
case 75:
System.out.println(Exceeding speed limit);
break;
case 69:
case 70:
System.out.println(Getting close);
break;
case 65:
System.out.println(Cruising);
break;
default:
System.out.println(Very slow);
}

8. Is default a mandatory part of a switch structure?


No
9. Write a line of code that converts String s = X into a character called chr.
char chr = s.charAt(0);

You might also like