java实习生题目!求助!

来源:百度知道 编辑:UC知道 时间:2024/05/23 15:33:26
Please write down the output of the following java code:

Question 1

class A {
public void method(){
System.out.println("A");
}
}

class B extends A{
public void method(){
System.out.println("B");
}
}

public class Test {

public static void main(String[] args) {
A a = new A();
B b = new B();

((A)b).method();
}
}
Question 2
public class Test2 {

static String str1 = "Hello";
static String str2 = new String("Hello");
static String str3 = "Hello";
static String str4 = new String(str3);

public static void main(String[] args) {

System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.pr

1.B Java的多态,父类调用子类重写的方法
2.false true false false
String a = "Hello";和String a = new String("Hello"); 是不一样的。

前者会检查缓冲池中有没有"Hello",如果有就不分配新的系统资源生成对象了,所以有可能引用的是同一个地址。

后者每一次生成新的对象,不可能出现引用同一个地址的情况

3. 1 exchange(a,b); 传过去的是值而不是地址
4.Hello World hello.replaceAll("World", "China"); 应该赋予一新的字符串才打印得出来,原来的hello没变
5.a=1 “b-- ==1”为假,b--先与1判断后才自减
b=1

Q1 B
Q2 false true false false
Q3 1
Q4 Hello World
Q5 a=1, b=1

Q2:str4的构造和str2类似,结果在意料中
Q4:String是不可以改变的,replaceAll之后,返回值为Hello China但是hello字符串本身并未改变,打印hello仍然是以前的值。
Q5:分析if语句if(a > 1 & b-- ==1)
&为非短路的逻辑与,意思就是虽然a>1不成立,仍然会执行b-- ==1仍然不成立,但是执行之后b-1,b=1;if语句中的代码不执行
结果a=1,b=1

第二题最后一个为什么是false?
一般只要是通过 new 关键词创建的,都是一个新的对象,存放在堆内存。
所以str4指向的是堆内存的一个新对象,
而对于static String str3 = "Hello";
"Hello"是字符串常量,存放在数据区。
所以str3 指向数据区的 "Hello"