Question:

What's the answer for this?

by  |  earlier

0 LIKES UnLike

What is the value of mark if the value of grade = 'C' ?

switch (grade) {

case 'A' : mark = 90;

case 'B' : mark = 80;

case 'C' : mark = 70;

case 'D' : mark = 60;

break;

case 'E': mark = 50;

break;

default: mark = 40;

}

a) 40

b) 50

c) 60

d) 70

e) 80

At first I thought the answer would be 70 60 = 130... But the answers do not include 130.. So i guess the answer would be 60.. correct?

 Tags:

   Report

1 ANSWERS


  1. Concerning the first problem, yes the answer is indeed 60.

    This is how execution would work

    --> switch(grade)

    --> case 'C': mark=70  // We jump here and set mark to 70

    --> case 'D': mark=60 // Even though grade!=D we execute the statement here as well, because no further comparison is performed.

    --> break; // Now we leave the switch statement.

    This would be the correct code if we wanted to get the right mark for each grade.

    switch (grade) {

    case 'A' : mark = 90;

    break; <-- If this break statement was missing, we would just continue

    case 'B' : mark = 80; <-- here

    break;

    case 'C' : mark = 70;

    break;

    case 'D' : mark = 60;

    break;

    case 'E': mark = 50;

    break;

    default: mark = 40;

    }

    Operators in Java that have the same precedence are evaluated according to their associativity. Operators that are left-associative are evaluated from left to right, operators that are right-associative are evaluated from right to left. *,/ and % as well as + and - are left-associative. Therefore they are evaluated from left to right.

    *, / and % however have a higher precedence than + and - and are therefore evaluated before + and -.

    === Evaluate operators with higher precedence from left to right

    9 + 3 % 4 * 3 - 5

    9 + 3 * 3 - 5

    === Evaluate operators with lower precedence from left to right

    9 + 9 - 5

    18 - 5

    13

    You can find the list of operators, their precedence and their associativity on the site posted below.

    EDIT:

    No. 3 % 4=3 ( the remainder of 3 / 4)

    9 + (3 % 4) * 3 - 5

    9 + (3) * 3 - 5

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions