(a) Differentiate between if else if and switch-case statements
(b) Give the output of the following code:
String P = "20", Q ="19"; int a = Integer.parseInt(P); int b = Integer.valueOf(Q); System.out.println(a+""+b);
(c) What are the various types of errors in Java?
(d) State the data type and value of res after the following is executed:
char ch = '9'; res= Character.isDigit(ch);
(e) What is the difference between the linear search and the binary search technique?
Answer:
Answer (a)
if else if | switch-case |
---|---|
if else if can test for any Boolean expression like less than, greater than, equal to, not equal to, etc. | switch-case can only test if the expression is equal to any of its case constants. |
if else if can use different expression involving unrelated variables in its different condition expressions. | switch-case statement tests the same expression against a set of constant values. |
Answer (b)
Output of the above code is:
2019
Explanation
Both Integer.parseInt() and Integer.valueOf() methods convert a string into integer. Integer.parseInt() returns an int value that gets assigned to a. Integer.valueOf() returns an Integer object (i.e. the wrapper class of int). Due to auto-boxing, Integer object is converted to int and gets assigned to b. So a becomes 20 and b becomes 19. 2019 is printed as the output.
Answer (c)
There are 3 types of errors in Java:
- Syntax Error
- Runtime Error
- Logical Error
Answer (d)
Data type of res is boolean as return type of method Character.isDigit() is boolean. Its value is true as '9' is a digit.
Answer (e)
Linear search | Binary search |
---|---|
Linear search works on sorted and unsorted arrays. | Binary search works on only sorted arrays. |
In Linear search, each element of the array is checked against the target value until the element is found or end of the array is reached. | In Binary search, array is successively divided into 2 halves and the target element is searched either in the first half or in the second half. |
Linear Search is slower. | Binary Search is faster. |
Related Articles:
This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.
Join Our telegram group to ask Questions
Click below button to join our groups.