March 02, 2015

What is the result when test("four") ,test("tee"),test("to") is Called ?

Given:

11. public static void test(String str) {
12. int check = 4;
13. if (check = str.length()) {
14. System.out.print(str.charAt(check -= 1) +", ");
15. } else {
16. System.out.print(str.charAt(0) + ", ");
17. }
18. } 
     \\ and the invocation:
21. test("four");
22. test("tee");
23. test("to");


A. r, t, t,
B. r, e, o,
C. Compilation fails.
D. An exception is thrown at runtime.








Answer: C

Explanation:

The biggest problem Java programmers confuse is with - if(condition) where to the condition they take it as  0 or 1 ( << its Wrong ,its not 0 or 1).In Java the Condition has to be either true or false (in words) and not 0 or 1.


Java has a separate data type called Boolean for condition  which evaluates to true or false (in words).But In Languages like C/C++ it is not so ,we use 1 to represent true and 0 to represent false.

Output of the above code is 
error: incompatible types
         if(check = str.length() ) {
                     ^
required :Boolean
found :    Int


The Entire trick in the above code is that they have used assignment operator = Instead of relational operator == .Therefore leads to Compilation failure .Option C





Related Topics

0 comments:

Post a Comment