[置顶] java基础部分代码相关题2

时间:2023-02-16 10:36:59
public class Test{
static{
int x=5;
}
static int x,y;
public static void main(String args[]){
x--;
myMethod( );
System.out.println(x+y+ ++x);
}
public static void myMethod( ){
y=x++ + ++x;
}
}
答案:prints:3

静态变量初始化为0;x–为-1,y=0;++x先加,所以x=1.打印语句中x+y=1,++x=2,所以结果为3


class Person {
String name = "No name";
public Person(String nm) {
name = nm;
}
}
class Employee extends Person {
String empID = "0000";
public Employee(String id) {
empID = id;
}
}
public class Test {
public static void main(String args[]) {
Employee e = new Employee("123");
System.out.println(e.empID);
}
}
答案:编译报错

父类没有无参的构造函数,所以子类需要在自己的构造函数中显式调用父类的构造函数,
添加
super(“nm”);
否则报错


Integer i = 42;
Long l = 42l;
Double d = 42.0;
答案正确的是:d.equals(l)
l.equals(42L)

不同类型引用的 == 比较,会出现编译错误,不能比较。
调用 equals 方法,因为此方法先是比较类型是不同的类型,所以返回假。
选项 G ,会自动装箱,将 42L 装箱成 Long 类型,所以调用 equals 方法时,类型相同,且值也相同,因此返回真。


String s1="abc"+"def";//1
String s2=new String(s1);//2
if(s1.equals(s2))//3
System.out.println(".equals succeeded");//4
if(s1==s2)//5
System.out.println("==succeeded");//6
答案:行4执行,行6不执行

s1指向的内容在常量池中,s2指向的内容在堆内存中。s1,s2保存在栈内存中。所以==比较的是地址,故第二个if语句不执行。


public class Test{
static int cnt = 6;
static{
cnt += 9;
}
public static void main(String[] args){
System.out.println(“cnt =” + cnt);
}
static{
cnt /=3;
};
}
答案:cnt=5

静态初始化块,静态变量这两个是属于同一级别的,是按代码写得顺序执行的!


int i=0;
ing j=0;
if((++i)>0 || (++j)>0){
打印i,j的值
}

答案:i=1;j=0

注意这里的坑,|| 前面为1后面不执行。


class Car extends Vehicle
{

public static void main (String[] args)
{
new Car(). run();
}
private final void run()
{
System. out. println ("Car");
}
}
class Vehicle
{

private final void run()
{
System. out. println("Vehicle");
}
}

首先final声明的方法是不能被覆盖的,但是这里并不错误,因为方法是private的,也就是子类没有继承父类的run方法,因此子类的run方法跟父类的run方法无关,并不是覆盖。new Car().run()也是调用子类的run方法。


class C {
C() {
System.out.print("C");
}
}

class A {
C c = new C();

A() {
this("A");
System.out.print("A");
}

A(String s) {
System.out.print(s);
}
}

class Test extends A {
Test() {
super("B");
System.out.print("B");
}

public static void main(String[] args) {
new Test();
}
}
答案:CBB

(1)初始化父类的普通成员变量和代码块,执行 C c = new C(); 输出C
(2)super(“B”); 表示调用父类的构造方法,不调用父类的无参构造函数,输出B
(3) System.out.print(“B”);
所以输出CBB