Q: What is the output of the following program?
1 class Test {
2 private long a;
3 private int b;
4 private String c;
5 public static void main(String...args) {
6 Test t = new Test();
7 t.print(a);
8 t.print(b);
9 t.print(c);
10 }
11 public void print(Object o) {System.out.print(1);}
12 public void print(long l) {System.out.print(2);}
13 public void print(int i) {System.out.print(3);}
14 public void print(String s) {System.out.print(4);}
15 public void print(Long L) {System.out.print(5);}
16 public void print(Integer I) {System.out.print(6);}
17 }
A. 0.00null
B. 00null
C. 0.00
D. 00
E. This code doesn't compile
A: E
Explain: non-static variable a cannot be referenced from a static context. If the variables are all static, the result will be 234.
Study: http://xyzcode.blogspot.com/2016/02/define-scope-of-variables.html, http://xyzcode.blogspot.com/2016/03/create-methods-with-arguments-and.html
======
Q: Which of the following are true?
Q: Which of the following are true?
11 byte b = 90;
12 int c = b + 1;
13 double d = 9;
14 String var = "test";
15 var.length();
16 d.length();
A. Line 11 generate compiler error.
B. Line 12 generate compiler error.
C. Line 13 generate compiler error.
D. Line 16 generate compiler error.
E. The code compile as is.
A: D
Explain: byte, short, int, and long are used for numbers without decimal points. When byte, short and char are used with java arithmetic operator, the type is automatically converted to int. So A and B is incorrect. It is ok to cast from low precision numeric type to higher precision numeric type. String literal 9 has type int, it can be casted to double, so C is incorrect. String have method length(). Primitive data type don't have length, So D is correct.
Study: http://xyzcode.blogspot.com/2016/02/define-scope-of-variables.html, http://xyzcode.blogspot.com/2016/02/use-java-operators-including.html
======
Q: What's the output of the following code?
======
Q: What's the output of the following code?
1 class Test {
2 static private float a;
3 static private Long b;
4 private String c;
5 public static void main(String...args) {
6 Test t = new Test();
7 t.tester();
8 }
9 void tester() {
10 byte a = 90;
11 int b = 10L;
12 double c = 9;
13 long e = 1;
14 a = e;
15 System.out.println(c);
16 }
17 }
A. 9.0
B. there is no output
C. Line 10 generate compile error
D. Line 11 generate compile error
E. Line 12 generate compile error
F. Line 14 generate compile error
A: D, F
Explain: D, F generate compile error incompatible types: possible lossy conversion from long to int. Local variable a, b, c here hide global variable with the same name, you can access static variable with class name and access instance variable with this keyword. If line 11 and line 14 is removed, the output is 9.0
Study: http://xyzcode.blogspot.com/2016/02/define-scope-of-variables.html, http://xyzcode.blogspot.com/2016/02/use-java-operators-including.html
======
======