前言
最近面试某公司,其技术主管精选了几道java题目用以面试,个人觉得很经典,也比起那些动不动就做几页试卷的,其面试效率更高更能体现应聘者的功底,因此附上自己的答案和理解分享出来。
第一道:该程序输出是true或false?
//该程序的运行结果是?
public static void main(String... args){
String str1 = "hello";
String str2 = "he" + new String("llo");
System.out.println(str1==str2);
}
答案为:false。对于对象来说,“==”比较的是其内存地址,两个new出来的对象其内存地址不同,对比结果自然为false,如“Integer i = new Integer("1");”和“Integer i2 = new Integer("1");”其“==”对比返回的为false。对于面试官来说,只回答这点是不够的,这道题里str1指向了“hello”的内存地址,但jvm栈内存会对“he"+new String("llo")的计算开辟新的存储空间,因此str2的内存地址与str1并不同。
第二道:如下程序输出是什么?
public class NULL {
public static void main(String... args){
((NULL)null).haha();
}
public static void haha(){
System.out.println("haha");
}
}
答案为:haha。这道题很能体现个人对jvm和java这门语言的理解。null代指一个不确定的实例,存储在栈帧中,从面向对象的角度出发这里应该是要报错的,但实际上因为static关键字,这里并没有创建实例,确定了类型为NULL,haha()方法即可正确运行。
第三道:如下输出是什么
public class HelloA {
public HelloA(){
System.out.println("Hello A");
}
{System.out.println("I am A class.");}
static {System.out.println("I am A static.");}
}
public class HelloB extends HelloA{
public HelloB(){
System.out.println("Hello B");
}
{System.out.println("I am B class.");}
static {System.out.println("I am B static.");}
public static void main(String... args){
new HelloB();
}
}
答案为:
I am A static.
I am B static.
I am A instance.
Hello A
I am B instance.
Hello B
熟悉jvm的类加载过程这道题其实很简单。
第四道:如下程序输出结果是什么?
public class Test2 {
String str = new String("good");
char[] ch = {'a','b','c'};
public static void main(String... args){
Test2 test2 = new Test2();
test2.change(test2.str, test2.ch);
System.out.println(test2.str);
System.out.println(test2.ch);
}
public void change(String str, char[] ch){
str = "test ok";
ch[0] = 'd';
}
}
答案:
good
dbc
很多bug的造成都跟这道题有关,我们需要清楚地理解值传递和引用传递。数组在java中都是以对象的形式存储,因此调用change方法时,实际上传递进去的是ch的内存地址,方法中修改其值自然会生效。str虽然也是对象,但实际上java对String、Integer、Double等immutable类做了处理,change方法改变的是其内存地址的副本地址,因此不会影响到外部的值。
第五道:一群猴子选大王,12只猴子围成1,2,3,4,5...一圈,每次报数报到4,则出局,然后再从1开始重新报数,问最后剩下的猴子是哪只?
答案为第一只猴子,前面四道题体现的是java的功底,而这道题体现的是快速建模的能力,这些只能经验积累了,附上我的代码实现:
public class Test {
private static List<String> monkeyNames =
Stream.of("M1","M2","M3","M4","M5","M6","M7","M8","M9","M10","M11","M12").collect(Collectors.toList());
public static void main(String... args){
selectKing(monkeyNames, 4);
System.out.println(monkeyNames.get(0));
}
public static void selectKing(List<String> monkeyNames, int base){
int count = 1;//从1开始喊号
int index = 0;
int length = 0;
while((length=monkeyNames.size())>1){
if(index>=length){
index = 0;
}
if(count == base){
monkeyNames.remove(index);
count = 1;
index--;
}else{
count++;
}
index++;
}
}
}