Java面向对象编程习题总结(三)
1. 对于以下程序,运行“java Abs”,将得到什么打印结果?
public class Abs
{
static int a = 0x11; //十六进制
static int b = 0011; //八进制
static int c = '/u0011'; //十六进制数据的Unicode字符编码
static int d = 011; //八进制
/**
* @param args
*/
public static void main(String[] args)
{
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.println("d="+d);
}
}
答:输出如下
a=17
b=9
c=17
d=9
(a) char a = ‘a’;
char b = 1;
char c = 08;
(b) int a = ‘a’;
(c) long a =’/u00FF’;
(d) char a = ‘/u0FF’;
(e) char d = “d”;
答:(b)、(c)能通过编译。(a)中“char c=08”将int赋值给char需要部分强制转换,“char c=8”就正确;(d)中unicode编码错误,java采用的是UCS-2编码,共16位;(e)字符赋值是使用单引号,字符串String赋值时才使用双引号。
(a) short myshort=99S;
(b) String name = ‘Excellent tutorial Mr Green’;
(c) char c = 17c;
(d) int z = 015;
答:(d)可以编译通过。(a)中char赋值给short需要强制转换;(b)中String类型赋值用双引号;(c)中int赋值给char需要部分强制转换。
4. 字符“A”的Unicode字符编码为65.下面哪些代码正确定义了一个代表字符“A”的变量?
(a) Char ch=65;
(b) Char ch=’/65’;
(c) Char ch =’/u0041’;
(d) Char ch=’A’;
(e) Char ch =”A”
答:(c)、(d)可以得到”A”。(b)的输出为5,其他无法编译通过。
String s1=new String(“hello”);
String s2=new String(“hello”);
String s3=s1;
String s4=s2;
答:共创建了2个对象。栈区4个局部变量分别引用了堆区的2个实例,而2个实例又引用了工作区的同一个类。
6. 以下代码能否编译通过?假如能编译通过,运行时将得到什么打印结果?
class Test
{
static int myArg = 1;
public static void main(String[] args)
{
Int myArg;
System.out.println(myArg);
}
}
答:无法编译通过,因为局部变量myArg声明之后Java虚拟机就不会自动给它初始化为默认值,若在使用前未被初始化,编译会报错。
7. 对于以下程序,运行“java Mystery Mighty Mouse”,将得到什么打印结果?
public class Mystery
{
public static void main(String[] args)
{
Changer c = new Changer();
c.method(args);
System.out.println(args[0]+" "+args[1]);
}
static class Changer
{
void method(String[] s)
{
String temp = s[0];
s[0] = s[1];
s[1] = temp;
}
}
}
答:打印结果为“Mighty Mystery”
8. 对于以下程序,运行“java Pass”,将得到什么打印结果?
public class Pass
{
static int j = 20;
public static void main(String[] args)
{
int i=10;
Pass p = new Pass();
p.amethod(i);
System.out.println("i="+i);
System.out.println("j="+j);
}
public void amethod(int x)
{
x*=2;
j*=2;
}
}
答:打印结果是
i=10
j=40
其中“int x”是传参,作用域仅在amethod之中