Related questions with answers
Question
What is wrong in the following code?
public class Test {
public static void main(String[] args) {
Number x = new Integer(3);
System.out.println(x.intValue());
System.out.println((Integer) x.compareTo(new Integer(4)));
}
}
Solution
VerifiedAnswered 2 years ago
Answered 2 years ago
On line 5, the variable x is compared to a new Integer object. The variable x is of type Number and not Integer. The conversion before invoking the method compareTo is done on the result of the method and not on x.
To get a valid result, the program should look like this
public class Test {
public static void main(String[] args) {
Number x = new Integer(3);
System.out.println(x.intValue());
System.out.println(((Integer)x)
.compareTo(new Integer(4)));
}
}
Create an account to view solutions
By signing up, you accept Quizlet's Terms of Service and Privacy Policy
Create an account to view solutions
By signing up, you accept Quizlet's Terms of Service and Privacy Policy
Recommended textbook solutions

Computer Organization and Design MIPS Edition: The Hardware/Software Interface
5th Edition•ISBN: 9780124077263David A. Patterson, John L. Hennessy226 solutions

Intro to Java Programming, Comprehensive Version
10th Edition•ISBN: 9780133761313Y. Daniel Liang1,628 solutions

Fundamentals of Database Systems
7th Edition•ISBN: 9780133970777Ramez Elmasri, Shamkant B. Navathe895 solutions

Introduction to Algorithms
3rd Edition•ISBN: 9780262033848 (5 more)Charles E. Leiserson, Clifford Stein, Ronald L. Rivest, Thomas H. Cormen849 solutions
More related questions
- computer science
1/4
- computer science
1/7