0% found this document useful (0 votes)
49 views12 pages

Understanding Conditional Statements in Java

The document contains a sample quiz with multiple choice questions about Java programming concepts like switch statements, if-else statements, and logical errors. It also includes questions that test the ability to predict the output of code snippets involving conditional statements. The answers provided explain the use of different conditional statements and jump statements in Java along with examples.

Uploaded by

Samrudh Mysore
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views12 pages

Understanding Conditional Statements in Java

The document contains a sample quiz with multiple choice questions about Java programming concepts like switch statements, if-else statements, and logical errors. It also includes questions that test the ability to predict the output of code snippets involving conditional statements. The answers provided explain the use of different conditional statements and jump statements in Java along with examples.

Uploaded by

Samrudh Mysore
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Question 1

In a switch case, when the switch value does not respond to any case then the execution
transfers to:

1. a break statement
2. a default case ✓
3. a loop
4. none

Question 2

Which of the following is a compound statement?

1. p=[Link]([Link]());
2. c=++a;
3. if(a>b) a++; b- - ; ✓
4. a=4;

Question 3

Condition is essentially formed by using:

1. Arithmetic operators
2. Relational operators
3. Logical operators
4. All ✓

Question 4

If(a>b)&&(a>c)), then which of the statement is true?

1. b is the smallest number


2. b is the greatest number
3. a is the greatest number ✓
4. all of the above

Question 5

if(a>b)
c=a;
else
c=b;
It can be written as:

1. c= (b>a)?a:b;
2. c= (a!=b)?a:b;
3. c= (a>b)?b:a;
4. None ✓
Question 6

If a, b and c are the sides of a triangle then which of the following statement is true for:
if(a!=b && a!=c && b!=c)?

1. Equilateral triangle
2. Scalene triangle ✓
3. Isosceles triangle
4. All of the above

Question 7

Two arithmetic expressions can be compared with if statement, using:

1. Arithmetic operator
2. Relational operator ✓
3. Ternary operator
4. None

Question 8

Which of the following is a conditional statement?

1. if ✓
2. goto
3. for
4. none

Question 9

Which of the following statements accomplishes 'fall through'?

1. for statement
2. switch statement ✓
3. if-else
4. none

Question 10

A Java program executes but doesn't give the desired output. It is due to:

1. the logical error in the program ✓


2. the syntax error in the program
3. the run time error in the program
4. none

Answer the Following Questions

Question 1

Name the different ways to manage the flow of control in a program.


Answer

Normal flow of control, Bi-directional flow of control, Multiple branching of control

Question 2

Mention one statement each to achieve:

(a) Bi-directional flow of control

Answer

if-else statement

(b) Multiple branching of control

Answer

switch statement

Question 3

Explain the following statements with their constructs:

(a) nested if

Answer

We can write an if-else statement within another if-else statement. We call this nested if.
It has the following syntax:

if (condition 1) {
if (condition 2) {
Statement a;
Statement b;
..
}
else {
Statement c;
Statement d;
..
}
}
else {
if (condition 3) {
Statement e;
Statement f;
..
}
else {
Statement g;
Statement h;
..
}
}
(b) if - else
Answer

if - else statement is used to execute one set of statements when the condition is true and
another set of statements when the condition is false. It has the following syntax:

if (condition 1) {
Statement a;
Statement b;
..
}
else {
Statement c;
Statement d;
..
}
(c) if - else - if

Answer

if - else - if ladder construct is used to test multiple conditions and then take a decision.
It provides multiple branching of control. It has the following syntax:

if (condition)
statement;
else if (condition)
statement;
else if (condition)
statement;
..
..
else
statement;

Question 4

Differentiate between if and switch statement.

Answer

Following are the difference between if and switch statement:

1. switch can only test for equality whereas if can test for any Boolean expression.
2. switch tests the same expression against constant values while if-else-if ladder
can use different expression involving unrelated variables.
3. switch expression must only evaluate to byte, short, int, char, String or an enum.
if doesn’t have such limitations.
4. A switch statement will run much faster than the equivalent program written
using the if-else-if ladder

Question 5

What is the purpose of switch statement in a program?

Answer
switch statement in a program, is used for multi-way branch. It compares its expression
to multiple case values for equality and executes the case whose value is equal to the
expression of switch. If none of the cases match, default case is executed. If default case
is absent then none of the statements from switch are executed.

Question 6

Explain with the help of an example, the purpose of default in a switch statement.

Answer

When none of the case values are equal to the expression of switch statement then
default case is executed. In the example below, value of number is 4 so case 0, case 1 and
case 2 are not equal to number. Hence sopln of default case will get executed printing
"Value of number is greater than two" to the console.

int number = 4;

switch(number) {

case 0:
[Link]("Value of number is zero");
break;

case 1:
[Link]("Value of number is one");
break;

case 2:
[Link]("Value of number is two");
break;

default:
[Link]("Value of number is greater than two");
break;

Question 7

Is it necessary to use 'break' statement in a switch case statement? Explain.

Answer

Use of break statement in a switch case statement is optional. Omitting break statement
will lead to fall through where program execution continues into the next case and
onwards till end of switch statement is reached.

Question 8

Explain 'Fall through' with reference to a switch case statement.

Answer

break statement at the end of case is optional. Omitting break leads to program
execution continuing into the next case and onwards till a break statement is
encountered or end of switch is reached. This is termed as Fall Through in switch case
statement.

Question 9

What is a compound statement? Give an example.

Answer

Two or more statements can be grouped together by enclosing them between opening
and closing curly braces. Such a group of statements is called a compound statement.

if (a < b) {

/*
* All statements within this set of braces
* form the compound statement
*/

[Link]("a is less than b");


a = 10;
b = 20;
[Link]("The value of a is " + a);
[Link]("The value of b is " + b);

Question 10

Explain with an example the if-else-if construct.

Answer

if - else - if ladder construct is used to test multiple conditions and then take a decision.
It provides multiple branching of control. Below is an example of if - else - if:

if (marks < 35)


[Link]("Fail");
else if (marks < 60)
[Link]("C grade");
else if (marks < 80)
[Link]("B grade");
else if (marks < 95)
[Link]("A grade");
else
[Link]("A+ grade");

Question 11

Name two jump statements and their use.

Answer

break statement, it is used to jump out of a switch statement or a loop. continue


statement, it is used to skip the current iteration of the loop and start the next iteration.

Question 12
Give two differences between the switch statement and the if-else statement.

Answer

switch if-else

if-else can test for any boolean


switch can only test if the expression is
expression like less than, greater
equal to any of its case constants
than, equal to, not equal to, etc.

It is a multiple branching flow of control


It is a bi-directional flow of control statement
statement

Predict the Output of the Given Snippet, when Executed

Question 1

int a=1,b=1,m=10,n=5;
if((a==1)&&(b==0))
{
[Link]((m+n));
[Link]((m—n));
}
if((a==1)&&(b==1))
{
[Link]((m*n));
System. [Link]((m%n));
}

Output

50

Explanation

First if condition is false, second if condition is true. Statements inside the code block of
second if condition are executed.
m*n => 10 * 5 => 50
m%n => 10 % 5 => 0

Question 2

int x=1,y=1;
if(n>0)
{
x=x+1;
y=y+1;
}
What will be the value of x and y, if n assumes a value (i) 1 (ii) 0?

Output
(i) n = 1

x = 2

y = 2

(ii) n = 0

x = 1

y = 1

Explanation

When n = 1, if condition is true, its code block is executed adding 1 to both x and y. When n
= 0, if condition is false so x and y retain their original values.

Question 3

int b=3,k,r;
float a=15.15,c=0;
if(k==1)
{
r=(int)a/b;
[Link](r);
}
else
{
c=a/b;
[Link](c);
}

Output

Compile time error in the line if(k==1)

"variable k might not have been initialized"

Explanation

Assuming k to be a local variable declared inside a method, we are using k in the if condition
before initializing it i.e. before assigning any value to k. Due to this, the above code will
generate a compile time error.

Question 4

switch (opn)
{
case 'a':
[Link]("Platform Independent");
break;
case 'b':
[Link]("Object Oriented");
case 'c':
[Link]("Robust and Secure");
break;
default:
[Link]("Wrong Input");
}
When (i) opn = 'b' (ii) opn = 'x' (iii) opn = 'a'

Output

(i) opn = 'b'

Object Oriented

Robust and Secure

Explanation

case 'b' is matched, "Object Oriented" gets printed to the console. As there is no case
statement in case 'b', program control falls through to case 'c' printing "Robust and Secure" to
the console. case 'c' has a break statement which transfers the program control outside switch
statement.

(ii) opn = 'x'

Wrong Input

Explanation

None of the 3 cases match so default case is executed.

(ii) opn = 'a'

Platform Independent

Explanation

case 'a' is matched, "Platform Independent" gets printed to the console. break statement in
case 'a' transfers the program control outside switch statement.

Correct the errors in the given programs

Question 1

class public
{
public static void main(String args{})
{
int a=45,b=70,c=65.45;
sum=a+b;
diff=c-b;
[Link](sum,diff);
}
}

Explanation

1. public is a keyword so it can't be used as an identifier for naming the class. Change
the class name from public to any valid identifier, for example class Sample
2. Argument of main method is an array of Strings. Use square brackets instead of curly
brackets — String args[]
3. c is an int variable. We cannot assign a double literal 65.45 to it.
4. Variables sum & diff are not defined
5. The line [Link](sum,diff); should be written like
this [Link](sum + " " + diff);

Corrected Program

class Sample //1st correction


{
public static void main(String args[]) //2nd correction
{
int a=45,b=70,c=65; //3rd correction
int sum=a+b; //4th Correction
int diff=c-b;
[Link](sum + " " + diff); //5th Correction
}
}

Question 2

class Square
{
public static void main(String args[])
{
int n=289,r;
r=sqrt(n);
if(n==r)
[Link]("Perfect Square");
else
[Link]("Not a Perfect Square");
}
}

Explanation

1. Variable r must be of double type as [Link] method returns a double value.


2. The line r=sqrt(n); should be r=[Link](n);

Corrected Program

class Square
{
public static void main(String args[])
{
int n=289;
double r=[Link](n); //1st & 2nd correction
if(n==r)
[Link]("Perfect Square");
else
[Link]("Not a Perfect Square");
}
}
Question 3

class Simplify
{
public static void main(String args[])
{
int a,b,c,d;
a=10,b=5,c=1,d=2;
c=a2+b2;
d=(a+b)2;
p=c/d;
[Link](c + " "+ " "+d+ " "+p);
}
}

Explanation

1. The line a=10,b=5,c=1,d=2; generates a compile time error. We will combine the
declaration and initialization of these variables.
2. The line c=a2+b2; is written in Java like this c = (int)([Link](a, 2) + [Link](b,
2));
3. The line d=(a+b)2; is written in Java like this d=(int)[Link]((a+b), 2);
4. Variable p is not defined

Corrected Program

class Simplify
{
public static void main(String args[])
{
int a=10,b=5,c=1,d=2; //1st correction
c = (int)([Link](a, 2) + [Link](b, 2)); //2nd correction
d = (int)[Link]((a+b), 2); //3rd correction
int p=c/d; //4th correction
[Link](c + " "+ " "+d+ " "+p);
}
}

Question 4

class Sample
{
public static void main(String args[])
{
int n,p;
float k,r;
n=25;p=12;
if(n=25)
{
k=pow(p,2)
[Link]("The value of"+p+ " = "+k);
}
else
{
r=[Link] root(n);
[Link]("The value of"+n+ " = "+r);
}
}
}

Explanation

1. The line if(n=25) should be if(n==25)


2. The line k=pow(p,2) should be k=(float)[Link](p,2);
3. The line r=[Link] root(n); should be r=(float)[Link](n);

Corrected Program

class Sample
{
public static void main(String args[])
{
int n,p;
float k,r;
n=25;p=12;
if(n==25) //1st correction
{
k=(float)[Link](p,2); //2nd correction
[Link]("The value of"+p+ " = "+k);
}
else
{
r=(float)[Link](n); //3rd correction
[Link]("The value of"+n+ " = "+r);
}
}
}

Common questions

Powered by AI

Switch statements focus on checking a single variable against constant values and offer faster execution, whereas if-else-if statements can evaluate complex Boolean expressions involving unrelated variables but execute slower. The switch expression supports limited data types while if-else-if does not have such limitations.

Compound statements group multiple simple statements within curly braces, thus allowing them to be treated as a single unit. Unlike simple statements that execute individually, compound statements execute collectively.

An if-else-if ladder tests multiple conditions sequentially and executes the block of the first true condition. For instance: if (marks < 35) { print 'Fail'; } else if (marks < 60) { print 'C grade'; } else { print 'B grade'; }. It allows multiple branching decision-making.

Break statements prevent fall-through by terminating the current case execution and transferring control outside the switch block. Omitting them results in 'fall-through', where execution continues into subsequent cases until a break statement is encountered or the switch block ends.

'Fall-through' occurs when break statements are omitted, leading to sequential execution of subsequent cases. For example, in a switch block with cases 'b' and 'c', omitting break at case 'b' causes both 'b' and 'c' to execute if 'b' is matched. This can be useful for common code sharing among cases.

Bi-directional flow control is achieved using 'if-else' which selects between two paths based on a condition. E.g., if (x > 0) do A; else do B. Multi-directional flow is managed using 'switch' which evaluates an expression to match multiple case values. E.g., switch(x) { case 1: do A; break; default: do C; }.

Logical errors occur due to incorrect program logic, leading to undesired results (e.g., using incorrect operators in a condition). Syntactic errors arise from violating language syntax rules, causing compilation failures (e.g., mismatched parentheses)

Fall-through is caused by omitting a break statement in a switch case, allowing execution to continue into subsequent cases. To avoid unintended fall-through, include a break at the end of every case block unless follow-though is intentionally needed.

Variables must be initialized before use to avoid unpredictable behaviors and guarantee logical accuracy. Uninitialized variables hold undefined data, leading to errors. For example, using a variable 'k' in an if condition without initialization results in a compilation error.

The default case in a switch statement is executed when none of the case values match the expression. If it is omitted and no cases match, none of the statements in the switch block are executed.

You might also like