【Java】-NO.12.Java.2.OCJP.1.001-【Java OCJP】-

1.0.0 Summary

Tittle:【Java】-NO.12.Java.2.OCJP.1.001-【Java OCJP】-

Style:Java

Series:OCJP

Since:2017-05-12

End:....

Total Hours:...

Degree Of Diffculty:8

Degree Of Mastery:8

Practical Level:8

Desired Goal:8

Archieve Goal:....

Gerneral Evaluation:...

Writer:kingdelee

Related Links:

http://www.cnblogs.com/kingdelee/

http://docs.oracle.com/javase/8/docs/api/

1.1.0 need to know 

1.1.1 Comparable or Comparator

2.1.1 extends

类的实例化过程:

1.分层概念:

先父类后子类

2.初始化概念:

成员变量---构造方法

主动引用:

1.创建类的实例   new A();

2.访问类的静态变量  

static int a = 10;

A.static_int_a;

2.2.1

案例1:

package com.lee.test.ocjp.u1;

class Singleton{
    public static int count1 ;
    public static int count2 = 10;
    private static Singleton singleton = new Singleton();

    private Singleton(){
        count1++;
        count2++;
    }

    public static Singleton getInstance(){
        
        return singleton;
    }
    
}
public class SingletonTest {
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        System.out.println(singleton.count1);
        System.out.println(singleton.count2);
    }
}

output:
1
11

案例2:

package com.lee.test.ocjp.u1;

class Singleton{
    private static Singleton singleton = new Singleton();
    public static int count1 ;
    public static int count2 = 10;

    private Singleton(){
        count1++;
        count2++;
    }

    public static Singleton getInstance(){
        
        return singleton;
    }
    
}
public class SingletonTest {
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        System.out.println(singleton.count1);
        System.out.println(singleton.count2);
    }
}

output:
1
10

解释:

1.Singleton singleton = Singleton.getInstance();调用public static Singleton getInstance()类的静态方法,主动引用。类初始化进行。
2.JVM对类进行以下阶段操作:加载,验证,准备
准备阶段:
static静态变量在方法区依次被分配内存,并初始化为默认值
count1 = 0;
count2 = 0;
singleton = null;
通过debug可以发现,进入类方法的第一步就读取了所有的类变量
3.解析,初始化。
初始化由类构造器Clinit方法执行的过程。
完成类变量赋值动作和静态语句块的语句合并产生。
通过debug可以发现,代码从上至下依次读取并进行赋值操作。

具体过程可以参考:http://blog.csdn.net/mashangyou/article/details/21384855

案例1:
count1; //无赋值操作初始值0无变化
count2 = 10;
new Singleton();
count1++;
count2++;

即 count1为1
count2为11

案例2:
new Singleton();
count1++; // 初始值为1
count2++;
count1; // 无赋值操作,1不变化
count2 = 10; // 赋值为10

即 count1为1
count2为10

2.2

父类与子类的构造函数的关系:

构造函数的第一个语句,要么是super直接调用父类的构造函数,要么是this调用本类的构造函数后间接的super调用父类构造函数

QUESTION 37
Given:
1. class Super {
2. private int a;
3. protected Super(int a) { this.a = a; }
4. } ...
11. class Sub extends Super {
12. public Sub(int a) { super(a); }
13. public Sub() { this.a = 5; }
14. }
Which two, independently, will allow Sub to compile? (Choose two.)
A. Change line 2 to:
public int a;
B. Change line 2 to:
protected int a;
C. Change line 13 to:
public Sub() { this(5); }
D. Change line 13 to:
public Sub() { super(5); }
E. Change line 13 to:
public Sub() { super(a); }
Answer: CD

子类重写的方法的作用域不能缩小,可以扩大。

QUESTION 76
Given:
1. public class Blip {
2. protected int blipvert(int x) { return 0; }
3. }
4. class Vert extends Blip {
5. // insert code here
6. }
Which five methods, inserted independently at line 5, will compile? (Choose five.)
A. public int blipvert(int x) { return 0; }
B. private int blipvert(int x) { return 0; }
C. private int blipvert(long x) { return 0; }
D. protected long blipvert(int x) { return 0; }
E. protected int blipvert(long x) { return 0; }
F. protected long blipvert(long x) { return 0; }
G. protected long blipvert(int x, int y) { return 0; }
Answer: A,C,E,F,G
重写和重载。A是重写,C,E,F,G是重载。

  

3.0 Inner and Outer

举例:Cow 与 CowLeg的关系

应用:内部类可以访问外部类,外部类不能访问内部类【仅指无静态成员的情况下,有静态成员的情况下见下面】

意义:更好的封装

class文件:Cow.class  Cow#CowLeg.class,即 Outer.class Outer#Inner.class

特点:

1.访问循序:

内部类可以访问外部类,从内到外依次寻找需要访问的元素

如内部类的某个方法需要访问某个元素

       定位到内部:this.varName 

       定位到外部类:Outer.this.varName

内部类中静态与非静态的关系:

1.静态成员的不能访问非静态成员

public class StaticTest
{
    // 定义一个非静态的内部类,是一个空类
	private class In{}
	// 外部类的静态方法
	public static void main(String[] args)
	{
		// 下面代码引发编译异常,因为静态成员(main()方法)
		// 无法访问非静态成员(In类)
//		new In();
	}
}

2.非静态内部类中不能用静态成员  

public class InnerNoStatic
{
    private class InnerClass
	{
		/*
		下面三个静态声明都将引发如下编译错误:
		非静态内部类不能有静态声明
		*/
//		static
//		{
//			System.out.println("==========");
//		}
//		private static int inProp;
//		private static void test(){}
	}
}

3.静态内部类可以访问外部静态变量,不能访问实例变量

public class StaticInnerClassTest
{
    private int prop1 = 5;
	private static int prop2 = 9;
	static class StaticInnerClass
	{
		// 静态内部类里可以包含静态成员
		private static int age;
		public void accessOuterProp()
		{
			// 下面代码出现错误:
			// 静态内部类无法访问外部类的实例变量
//			System.out.println(prop1);
			// 下面代码正常
			System.out.println(prop2);
		}
	}
}

4.static变量是类相关的,非static变量时对象相关的,类变量可以直接通过类取出,成员变量需要通过构建对象取出

public class AccessStaticInnerClass
{
    static class StaticInnerClass
	{
		private static int prop1 = 5;
		private int prop2 = 9;
	}
	public void accessInnerProp()
	{
		// System.out.println(prop1);
		// 上面代码出现错误,应改为如下形式:
		// 通过类名访问静态内部类的类成员
		System.out.println(StaticInnerClass.prop1);
		// System.out.println(prop2);
		// 上面代码出现错误,应改为如下形式:
		// 通过实例访问静态内部类的实例成员
		System.out.println(new StaticInnerClass().prop2);
	}
}

5.在外部类以外的地方定义内部类变量

Outer.Inner varName

6.在外部类以外的地方定义非静态内部类实例

out.new Instatnce()

class Out
{
    // 定义一个内部类,不使用访问控制符,
	// 即只有同一个包中其他类可访问该内部类
	class In
	{
		public In(String msg)
		{
			System.out.println(msg);
		}
	}
}
public class CreateInnerInstance
{
	public static void main(String[] args)
	{
		Out.In in = new Out().new In("测试信息");
		/*
		上面代码可改为如下三行代码:
		使用OutterClass.InnerClass的形式定义内部类变量
		Out.In in;
		创建外部类实例,非静态内部类实例将寄存在该实例中
		Out out = new Out();
		通过外部类实例和new来调用内部类构造器创建非静态内部类实例
		in = out.new In("测试信息");
		*/
	}
}

Out.In in = new Out().new In();

7.在外部类以外的地方创建静态内部类

new StaticOuter.InnerConstructor();

class StaticOut
{
    // 定义一个静态内部类,不使用访问控制符,
	// 即同一个包中其他类可访问该内部类
	static class StaticIn
	{
		public StaticIn()
		{
			System.out.println("静态内部类的构造器");
		}
	}
}
public class CreateStaticInnerInstance
{
	public static void main(String[] args)
	{
		StaticOut.StaticIn in = new StaticOut.StaticIn();
		/*
		上面代码可改为如下两行代码:
		使用OutterClass.InnerClass的形式定义内部类变量
		StaticOut.StaticIn in;
		通过new来调用内部类构造器创建静态内部类实例
		in = new StaticOut.StaticIn();
		*/
	}
}

总结 6、7

在外部创建内部类对象时,静态内部类只需要调用外部类即可调用构造器【new Out.StaticIn()】,非静态内部类就需要外部类对象来调用构造器【new Out().new In()】

由于静态内部类更为简单方便,故优先使用。

局部内部类,即定义在方法里边的类。因为作用域太小,很少使用

public class LocalInnerClass
{
    public static void main(String[] args)
	{
		// 定义局部内部类
		class InnerBase
		{
			int a;
		}
		// 定义局部内部类的子类
		class InnerSub extends InnerBase
		{
			int b;

			// error 因为已经是局部内部类受限于方法,不能再有静态内部类
//			static class AA{
//
//			}
			
			
		}
		// 创建局部内部类的对象
		InnerSub is = new InnerSub();
		is.a = 5;
		is.b = 8;
		System.out.println("InnerSub对象的a和b实例变量是:"
			+ is.a + "," + is.b);
	}
}

class Out1{
	
	static class AA{
		
	}
	
}

  

匿名内部类:

interface Product
{
    public double getPrice();
	public String getName();
}
public class AnonymousTest
{
	public void test(Product p)
	{
		System.out.println("购买了一个" + p.getName()
			+ ",花掉了" + p.getPrice());
	}
	public static void main(String[] args)
	{
		AnonymousTest ta = new AnonymousTest();
		// 调用test()方法时,需要传入一个Product参数,
		// 此处传入其匿名实现类的实例
		ta.test(new Product()
		{
			public double getPrice()
			{
				return 567.8;
			}
			public String getName()
			{
				return "AGP显卡";
			}
		});
	}
}

匿名内部类访问外部变量时,必须是显示或者隐式(jdk1.8)是final修饰

4.0 polymophic

1.

编译时  = 运行时

域不具备多态的性质。编译时是神马状态,就调用神马状态的域。

interface A{
    void a();
}

interface B{
    void b();
}

interface C extends A, B{
    void c();
}

class D implements B{

    @Override
    public void b() {
        System.out.println("D_b");
    }
}

class E extends D implements C{

    @Override
    public void a() {
        System.out.println("E_a");
    }

    @Override
    public void b() {
        System.out.println("E_b");
    }

    @Override
    public void c() {
        System.out.println("E_c");
    }
}

public class T_30_extends_implements {

    public static void main(String[] args) {
        D e = new E();
        e.b();
    }

}

output:
E_b

  

QUESTION 38
Given:
1. public class Base {
2. public static final String FOO = "foo";
3. public static void main(String[] args) {
4. Base b = new Base();
5. Sub s = new Sub();
6. System.out.print(Base.FOO);
7. System.out.print(Sub.FOO);
8. System.out.print(b.FOO);
9. System.out.print(s.FOO);
10. System.out.print(((Base)s).FOO);
11. } }
12. class Sub extends Base {public static final String FOO="bar";} What is the result?
A. foofoofoofoofoo
B. foobarfoobarbar
C. foobarfoofoofoo
D. foobarfoobarfoo
E. barbarbarbarbar
F. foofoofoobarbar
G. foofoofoobarfoo
Answer: D

  

多态,方法级用的总是运行时的类的数据

即   父类 f = 子类

f.a(); 用的是子类的数据

static class A{
        String name = "A";

        public String getName() {
            return name;
        }

        public String greeting(){
            return "classA";
        }
        
    }
    
    static class B extends A{
        String name = "B";
        
        public String greeting(){
            return "classB";
        }
    }

    public static void main(String[] args) {
        A a = new A();
        A b = new B();
        System.out.println(a.greeting() + "__" + a.getName() );
        System.out.println(b.greeting() + "__" + b.getName() );
    }

A__a
B__a

  

  

5. Exception

QUESTION 42
Given:
11. class A {
12. public void process() { System.out.print("A,"); }
13. class B extends A {
14. public void process() throws IOException {
15. super.process();
16. System.out.print("B,");
17. throw new IOException();
18. }
19. public static void main(String[] args) {
20. try { new B().process(); }
21. catch (IOException e) { System.out.println("Exception"); }
22. }
What is the result?
A. Exception
B. A,B,Exception
C. Compilation fails because of an error in line 20.
D. Compilation fails because of an error in line 14.
E. A NullPointerException is thrown at runtime.
Answer: D
第十四行抛出了一个父类没有的异常,错误。子类不可以抛出父类没有的异常。

 

QUESTION 47
Given:
11. static void test() throws Error {
12. if (true) throw new AssertionError();
13. System.out.print("test ");
14. }
15. public static void main(String[] args) {
16. try { test(); }
17. catch (Exception ex) { System.out.print("exception "); }
18. System.out.print("end ");
19. }
What is the result?
A. end
B. Compilation fails.
C. exception end
D. exception test end
E. A Throwable is thrown by main.
F. An Exception is thrown by main.
Answer: E
如果抛出一个异常,就不会执行下面的内容,而是返回调用产生异常的方法那里去。Error类和Exception类同继承自Throwable类,main函数不能处理Error类异常,所以一个Thorwable被main抛出。

继承的异常是可以被重写的抹去的。

QUESTION 51
Given:
11. static class A {
12. void process() throws Exception { throw new Exception(); }
13. }
14. static class B extends A {
15. void process() { System.out.println("B"); }
16. }
17. public static void main(String[] args) {
18. new B().process();
19. }
What is the result?
A. B
B. The code runs with no output.
C. Compilation fails because of an error in line 12.
D. Compilation fails because of an error in line 15.
E. Compilation fails because of an error in line 18.
Answer: A
B类重写了A类的process方法,并没有抛出A类没有的异常。

  

异常的传递性,逐级往下传递时,必须是从小到大,不能从大到小,否则第一层捕获了,之后就没法捕获了

QUESTION 105
Given:
11. public static void main(String[] args) {
12. try {
13. args = null;
14. args[0] = "test";
15. System.out.println(args[0]);
16. } catch (Exception ex) {
17. System.out.println("Exception");
18. } catch (NullPointerException npe) {
19. System.out.println("NullPointerException");
20. }
21. }
What is the result?
A. test
B. Exception
C. Compilation fails.
D. NullPointerException
Answer: C
NullPointerException 是Exception 的子类,在编译器中会有无法达到(not available)的警告。

  

catch 由上到下传递,但是只捕获一次

QUESTION 148
Given:
33. try {
34. // some code here
35. } catch (NullPointerException e1) {
36. System.out.print("a");
37. } catch (Exception e2) {
38. System.out.print("b");
39. } finally {
40. System.out.print("c");
41. }
If some sort of exception is thrown at line 34, which output is possible?
A. a
B. b
C. c
D. ac
E. abc
Answer: D
要么ac,要么bc

  

内层异常被catch后,就不会抛出外层给外层的catch

QUESTION 151
Given:
11. static void test() throws RuntimeException {
12. try {
13. System.out.print("test ");
14. throw new RuntimeException();
15. }
16. catch (Exception ex) { System.out.print("exception "); }
17. }
18. public static void main(String[] args) {
19. try { test(); }
20. catch (RuntimeException ex) { System.out.print("runtime "); }
21. System.out.print("end ");
22. }
What is the result?
A. test end
B. Compilation fails.
C. test runtime end
D. test exception end
E. A Throwable is thrown by main at runtime.
Answer: D
19. try { test(); },首先输出13. System.out.print("test ");然后会抛出throw new RuntimeException();,这个异常16行的catch可以处理,,输出exception ,然后执行21行~~

  

多态编译时用的是父类,运行时才用的是子类

public class T_180_Exception {

    static class A{
        void foo() throws Exception{
            System.out.println("A");
            throw new Exception();
        }
    }

    static class B extends A{
        void foo(){
            System.out.println("B");
        }
    }

    public static void main(String[] args) {
        A a = new B();
        a.foo(); //error,必须try catch或者 throw

    }

}





QUESTION 180
Given:
5. class A {
6. void foo() throws Exception { throw new Exception(); }
7. }
8. class SubB2 extends A {
9. void foo() { System.out.println("B "); }
10. }
11. class Tester {
12. public static void main(String[] args) {
13. A a = new SubB2();
14. a.foo();
15. }
16. }
What is the result?
A. B
B. B, followed by an Exception.
C. Compilation fails due to an error on line 9.
D. Compilation fails due to an error on line 14.
E. An Exception is thrown with no other output.
Answer: D
编译器会报错:Unhandled exception type Exception

必须按照以下格式来:
 try {
a.foo();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
或者throws一个Exception。这种多态性在编译的时候是完全按照 父类的方法来的,即在compiler的时候检查foo()方法是否在 A类中,如果在那么就按照父类的要求抛出异常或者捕获异常,在runtime的时候再调用SubB2 的foo()方法。如果子类的方法允许抛出一个父类没有的异常,那么就没有异常处理器来处理此异常,所以,不允许子类方法抛出父类没有的异常。

  

 

6. Assert

QUESTION 43
Given:
11. public void go(int x) {
12. assert (x > 0);
13. switch(x) {
14. case 2: ;
15. default: assert false;
16. }
17. }
18. private void go2(int x) { assert (x < 0); }
Which statement is true?
A. All of the assert statements are used appropriately.
B. Only the assert statement on line 12 is used appropriately.
C. Only the assert statement on line 15 is used appropriately.
D. Only the assert statement on line 18 is used appropriately.
E. Only the assert statements on lines 12 and 15 are used appropriately.
F. Only the assert statements on lines 12 and 18 are used appropriately.
G. Only the assert statements on lines 15 and 18 are used appropriately.
Answer: D
使用断言的规则:
1.不要使用断言验证公共方法的参数。 
2.可以使用断言验证私有方法的参数。 
3.不要使用断言验证命令行参数 
4.在公共方法内,可以使用断言检查从不会发生的情况
5.不要使用可能产生副作用的断言,也就是断言表达式应该使程序保持在进入它之前的状态。

对于第12行,assert不能检测公共方法的参数,违反了原则4
15行,assert肯定会发生,不会回到之前的状态,违反了原则5
18行符合原则2。

  

  

7.equals

Integer等数据对象,其hashcode就是其值,所以值相等,对象相等。

QUESTION 63
Given:
1. public class KungFu {
2. public static void main(String[] args) {
3. Integer x = 400;
4. Integer y = x;
5. x++;
6. StringBuilder sb1 = new StringBuilder("123");
7. StringBuilder sb2 = sb1;
8. sb1.append("5");
9. System.out.println((x==y) + " " + (sb1==sb2));
10. }
11. }
What is the result?
A. true true
B. false true
C. true false
D. false false
E. Compilation fails.
F. An exception is thrown at runtime.
Answer: B

  

QUESTION 167
Given:
1. import java.util.*;
2. public class WrappedString {
3. private String s;
4. public WrappedString(String s) { this.s = s; }
5. public static void main(String[] args) {
6. HashSet<Object> hs = new HashSet<Object>();
7. WrappedString ws1 = new WrappedString("aardvark");
8. WrappedString ws2 = new WrappedString("aardvark");
9. String s1 = new String("aardvark");
10. String s2 = new String("aardvark");
11. hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2);
12. System.out.println(hs.size()); } }
What is the result?
A. 0
B. 1
C. 2
D. 3
E. 4
F. Compilation fails.
G. An exception is thrown at runtime.
Answer: D
WrappedString 的hashCode()是继承自Object类,而String的hashCode()时重写过的仅与字符串的内容有关。ws1 和ws2存储地址不同,所以hashCode()的返回值不同,而s1和s2字符串的内容相同,哈希值相同。

  

8.Thread

QUESTION 68
Given:
1. public class Threads3 implements Runnable {
2. public void run() {
3. System.out.print("running");
4. }
5. public static void main(String[] args) {
6. Thread t = new Thread(new Threads3());
7. t.run();
8. t.run();
9. t.start();
10. }
11. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints "running".
D. The code executes and prints "runningrunning".
E. The code executes and prints "runningrunningrunning".
Answer: E
run()函数仅在主线程中运行,而start()函数是开辟一个新的线程。running出现三次。

  

QUESTION 70
Given:
11. public class PingPong implements Runnable {
12. synchronized void hit(long n) {
13. for(int i = 1; i < 3; i++)
14. System.out.print(n + "-" + i + " ");
15. }
16. public static void main(String[] args) {
17. new Thread(new PingPong()).start();
18. new Thread(new PingPong()).start();
19. }
20. public void run() {
21. hit(Thread.currentThread().getId());
22. }
23. }
Which two statements are true? (Choose two.)
A. The output could be 8-1 7-2 8-2 7-1
B. The output could be 7-1 7-2 8-1 6-1
C. The output could be 8-1 7-1 7-2 8-2
D. The output could be 8-1 8-2 7-1 7-2
Answer: CD
synchronized 仅仅是同一对象等等hit函数互斥,第17,18行是对两个不同的PingPong对象开辟的新线程。

  

QUESTION 129
Given:
1. public class Threads4 {
2. public static void main (String[] args) {
3. new Threads4().go();
4. }
5. public void go() {
6. Runnable r = new Runnable() {
7. public void run() {
8. System.out.print("foo");
9. }
10. };
11. Thread t = new Thread(r);
12. t.start();
13. t.start();
14. }
15. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes normally and prints "foo".
D. The code executes normally, but nothing is printed.
Answer: B
t.start()是让线程t开始,已经开始了,不能再次t.start()。会抛出非法状态异常,IllegalThreadStateException。

  

9.this

QUESTION 73
Given:
10: public class Hello {
11: String title;
12: int value;
13: public Hello() {
14: title += " World";
15: }
16: public Hello(int value) {
17: this.value = value;
18: title = "Hello";
19: Hello();
20: }
21: } and:
30: Hello c = new Hello(5);
31: System.out.println(c.title);
What is the result?
A. Hello
B. Hello World
C. Compilation fails.
D. Hello World 5
E. The code runs with no output.
F. An exception is thrown at runtime.
Answer: C
第19行,调用本类的其他构造函数应该是:this();

  

10. constructor

QUESTION 74
Given:
1. class ClassA {
2. public int numberOfInstances;
3. protected ClassA(int numberOfInstances) {
4. this.numberOfInstances = numberOfInstances;
5. }
6. }
7. public class ExtendedA extends ClassA {
8. private ExtendedA(int numberOfInstances) {
9. super(numberOfInstances);
10. }
11. public static void main(String[] args) {
12. ExtendedA ext = new ExtendedA(420);
13. System.out.print(ext.numberOfInstances);
14. }
15. }
Which statement is true?
A. 420 is the output.
B. An exception is thrown at runtime.
C. All constructors must be declared public.
D. Constructors CANNOT use the private modifier.
E. Constructors CANNOT use the protected modifier.
Answer: A

  

QUESTION 88
Given:
1. public class Plant {
2. private String name;
3. public Plant(String name) { this.name = name; }
4. public String getName() { return name; }
5. }
1. public class Tree extends Plant {
2. public void growFruit() { }
3. public void dropLeaves() { }
4. }
Which statement is true?
A. The code will compile without changes.
B. The code will compile if public Tree() { Plant(); } is added to the Tree class.
C. The code will compile if public Plant() { Tree(); } is added to the Plant class.
D. The code will compile if public Plant() { this("fern"); } is added to the Plant class.
E. The code will compile if public Plant() { Plant("fern"); } is added to the Plant class.
Answer: D
Tree 的构造器只有一个默认构造器,而这个默认构造器必须调用父类的无参数构造器,故Plant缺少一个无参数的构造器。

  

A. 4321
B. 0000
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 18.
Answer: D
Person中没有默认的无参数的构造函数,所以Employee中的构造函数必须显式调用super(id);

  

11. i++ 与 ++i

1.i++时,当作为return返回值,也遵循先返回后赋值,作为参数传入时,也是遵循先返回后赋值

QUESTION 75
Given:
1. public class Target {
2. private int i = 0;
3. public int addOne(){
4. return ++i;
5. }
6. } And:
1. public class Client {
2. public static void main(String[] args){
3. System.out.println(new Target().addOne());
4. }
5. }
Which change can you make to Target without affecting Client?
A. Line 4 of class Target can be changed to return i++;
B. Line 2 of class Target can be changed to private int i = 1;
C. Line 3 of class Target can be changed to private int addOne(){
D. Line 2 of class Target can be changed to private Integer i = 0;
Answer: D
要更改Target类而不影响Client类,只有D

  

public class T_75_operator {

    public static void main(String[] args) {
        int a = 10;
        AA aa = new AA();
        // 11
        System.out.println("return ++a:" + aa.getA());
        // 11
        System.out.println("return a++:" + aa.getB());
        // 10
        System.out.println("a:" +a);
        // 11
        System.out.println("getA(++a):" + aa.getA(++a));
        // 11
        System.out.println("a:" + a);
        // 11
        System.out.println("getA(a++):" + aa.getA(a++));
        // 12
        System.out.println("a:" + a);

    }
}

class AA{
    private int a = 10;

    public int getA(){
        return ++a;
    }

    public int getB(){
        return a++;
    }

    public int getA(int a){
        return a;
    }
}

  

12.operator

两个数(非 是自己一个数)转化为二进制后进行对比计算

与 &, 都是1才为1

或 |,  有一个是1则为1

非 !, 1为0,0为1

异或 ^, 同则0, 异为1(true)

逐位取反 ~, 32位逐位取反(即0变1,1变0,32位第一位为符号位)

移位运算符:

数值转化为32位二进制后,向 ... 移动 ... 几位

<<,向左移动,右边的低位补0

>>,(有符号)向右移动,左边的高位,若为正补0,若为负补1

>>>,(无符号)向右移动,左边的高位补0.

数学关系:

a * 2^b, a << b;

a / 2^b, a >> b; 

  

QUESTION 85
Given:
3. public class Spock {
4. public static void main(String[] args) {
5. Long tail = 2000L;
6. Long distance = 1999L;
7. Long story = 1000L;
8. if((tail > distance) ^ ((story * 2) == tail))
9. System.out.print("1");
10. if((distance + 1 != tail) ^ ((story * 2) == distance))
11. System.out.print("2");
12. }
13. }
What is the result?
A. 1
B. 2
C. 12
D. Compilation fails.
E. No output is produced.
F. An exception is thrown at runtime.
Answer: E
^ 是异或,第一次两边都是true,不会输出1,第二次两边都是false,不会输出2。

  

 13. obj

对象引用

public class T_96_obj {

    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        Integer i1 = 10;
        Integer i2 = 20;
        set.add(i1);
        set.add(i1);
        set.add(i2);
        set.add(null);
        System.out.println("size:" + set.size());
        set.remove(i1);
        System.out.println("size:" + set.size());
        i2 = 30;
        set.remove(null);
        set.remove(i2);
        System.out.println("size:" + set.size());

    }

}

  

14. Comparable and Compartor  

QUESTION 97
Given:
1. public class Score implements Comparable<Score> {
2. private int wins, losses;
3. public Score(int w, int l) { wins = w; losses = l; }
4. public int getWins() { return wins; }
5. public int getLosses() { return losses; }
6. public String toString() {
7. return "<" + wins + "," + losses + ">";
8. }
9. // insert code here
10. }
Which method will complete this class?
A. public int compareTo(Object o){/*more code here*/}
B. public int compareTo(Score other){/*more code here*/}
C. public int compare(Score s1,Score s2){/*more code here*/}
D. public int compare(Object o1,Object o2){/*more code here*/}
Answer: B
Comparable接口只有一个方法,public int CompareTo(T other)

  

15. HashSet 

public static void main(String[] args) {
        TreeSet<Integer> s = new TreeSet<>();
        TreeSet<Integer> subs = new TreeSet<>();
        for (int i = 606; i < 613; i++) {
            if (i % 2 == 0) s.add(i);
        }
        subs = (TreeSet<Integer>) s.subSet(608, true, 611, true);
        subs.add(629);
        System.out.println(s + "" + subs);
    }


s:606, 608, 610, 612

subs:608, 610
range:608<= subs, subs<=611

这时候add 一个629,超过subs的range。 Exception in thread "main" java.lang.IllegalArgumentException: key out of range 返回的view subs是一个包含元素和限定范围的集合 即第一次 subs是一个容量为0的集合,这时候再add就越界了

  

@Test
    public void t1() {
        TreeSet<Integer> s = new TreeSet<Integer>();
        TreeSet<Integer> subs = new TreeSet<Integer>();
        for (int i = 606; i < 613; i++)
            if (i % 2 == 0) s.add(i);
        subs = (TreeSet) s.subSet(608, true, 611, true);
        subs.add(609);
        System.out.println(s + " " + subs);
    }

s:606, 608, 610, 612
subs: 608, 610,
subs range:  608<=subs, subs<=611

subs.add 609
属于范围内的,可以add
因为subs是view,操作view本质上也是操作了主体s

所以
s: 606, 608, 609, 610, 612
subs: 608, 609, 610

  

@Test
    public void t2() {
        TreeSet<Integer> s = new TreeSet<Integer>();
        TreeSet<Integer> subs = new TreeSet<Integer>();
        for (int i = 606; i < 613; i++)
            if (i % 2 == 0) s.add(i);
        subs = (TreeSet) s.subSet(608, true, 611, true);
        s.add(609);
        System.out.println(s + " " + subs);
    }


s:606, 608, 610, 612
subs: 608, 610,
subs range:  608<=subs, subs<=611

subs.add 609
属于范围内的,可以add
因为subs是view,操作了主体s其映射的view同样会被影响

所以输出结果同上
s: 606, 608, 609, 610, 612
subs: 608, 609, 610

16. Arrays

    public static void main(String[] args) {

        Object [] objects = {   //23
                new Integer(12),
                new String("too"),
                new Integer(1),
                new Boolean(true)
        };

        Arrays.sort(objects);  // 29 Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
        for (int i = 0; i < objects.length; i++) {
            System.out.println(objects[i].toString());  //31
            System.out.print(" ");
        }

    }

What is the result?
A. Compilation fails due to an error in line 23.
B. Compilation fails due to an error in line 29.
C. A ClassCastException occurs in line 29.
D. A ClassCastException occurs in line 31.
E. The value of all four objects prints in natural order.
Answer: C

sort方法比较的必须是可以转化成相同的而且实现了Comparable接口的相同对象。

  

17. Param

public class T_138_Param {

    public static void main(String[] args) {
        Foo2 foo2 = new Foo2(300);
        System.out.println(foo2.getX() + "_");
        System.out.println(foo2.hashCode());
        Foo2 fooFoo = fooBar(foo2);
        System.out.println(foo2.hashCode());
        System.out.println(foo2.getX() + "_");
        System.out.println(fooFoo.getX() + "_");
    }

    private static Foo2 fooBar(Foo2 foo2) {
        foo2 = new Foo2(100);
        return foo2;
    }

}

class Foo2{
    private int x;
    public Foo2(int x){
        this.x = x;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }
}

  

20. instanceof 

QUESTION 140
Given:
3. interface Fish { }
4. class Perch implements Fish { }
5. class Walleye extends Perch { }
6. class Bluegill { }
7. public class Fisherman {
8. public static void main(String[] args) {
9. Fish f = new Walleye();
10. Walleye w = new Walleye();
11. Bluegill b = new Bluegill();
12. if(f instanceof Perch) System.out.print("f-p ");
13. if(w instanceof Fish) System.out.print("w-f ");
14. if(b instanceof Fish) System.out.print("b-f ");
15. }
16. }
What is the result?
A. w-f
B. f-p w-f
C. w-f b-f
D. f-p w-f b-f
E. Compilation fails.
F. An exception is thrown at runtime.
Answer: B
a instanceof  b,指的是a对象是否是b类或其子类的一个实例对象,或者说a对象是否是实现了b接口的一个实例对象。
f对象是Perch子类的实例对象,w对象实现了Fish接口,b对象没有实现Fish接口。

  

 

21. switch

default 默认也相当于匹配上,从这里开始读取

public class T_149_case {

    enum Dogs{
        a, b, c, d
    }

    public static void main(String[] args) {

Dogs dog = Dogs.d; // a b // Dogs dog = Dogs.c; // c a b switch (dog){ case c: System.out.println("c"); default: System.out.println("a"); case b: System.out.println("b"); } } }

  

22.enum

枚举实际上就是静态类

QUESTION 154
Given:
10. class Nav{
11. public enum Direction { NORTH, SOUTH, EAST, WEST }
12. }
13. public class Sprite{
14. // insert code here
15. }
Which code, inserted at line 14, allows the Sprite class to compile?
A. Direction d = NORTH;
B. Nav.Direction d = NORTH;
C. Direction d = Direction.NORTH;
D. Nav.Direction d = Nav.Direction.NORTH;
Answer: D

 

23.abstract

抽象类无需实现接口

QUESTION 159
Given:
11. public interface A { public void m1(); }
12.
13. class B implements A { }
14. class C implements A { public void m1() { } }
15. class D implements A { public void m1(int x) { } }
16. abstract class E implements A { }
17. abstract class F implements A { public void m1() { } }
18. abstract class G implements A { public void m1(int x) { } }
What is the result?
A. Compilation succeeds.
B. Exactly one class does NOT compile.
C. Exactly two classes do NOT compile.
D. Exactly four classes do NOT compile.
E. Exactly three classes do NOT compile.
Answer: C
B类没有实现接口A,C类无错,D类没有实现函数void m1();,而是重载了~~abstract抽象类可以不去实现接口。

  

24.NumberFormat

set...FractionDigits()....注意四舍五入,保留小数点几位

QUESTION 162
Given:
12. NumberFormat nf = NumberFormat.getInstance();
13. nf.setMaximumFractionDigits(4);
14. nf.setMinimumFractionDigits(2);
15. String a = nf.format(3.1415926);
16. String b = nf.format(2);
Which two statements are true about the result if the default locale is Locale.US? (Choose two.)
A. The value of b is 2.
B. The value of a is 3.14.
C. The value of b is 2.00.
D. The value of a is 3.141.
E. The value of a is 3.1415.
F. The value of a is 3.1416.
G. The value of b is 2.0000.
Answer: CF
setMaximumFractionDigits是设置小数点后的数字的最max个数~~
setMinimumFractionDigits是设置小数点后的数字的最min个数~~
setMinimumIntegerDigits是设置小数点前的数字的最min个数~~

  

25.directory

QUESTION NO: 80
Given:
1. package com.company.application;
2.
3. public class MainClass {
4. public static void main(String[] args) {}
5. }
And MainClass exists in the /apps/com/company/application directory. Assume the CLASSPATH
environment variable is set to "." (current directory). Which two java commands entered at the
command line will run MainClass? (Choose two.)
A. java MainClass if run from the /apps directory
B. java com.company.application.MainClass if run from the /apps directory
C. java -classpath /apps com.company.application.MainClass if run from any directory
D. java -classpath . MainClass if run from the /apps/com/company/application directory
E. java -classpath /apps/com/company/application:. MainClass if run from the /apps directory
F. java com.company.application.MainClass if run from the /apps/com/company/application
directory
Answer: B,C
Explanation:

  

QUESTION NO: 82
A developer is creating a class Book, that needs to access class Paper. The Paper class is
deployed in a JAR named myLib.jar. Which three, taken independently, will allow the developer to
use the Paper class while compiling the Book class? (Choose three.)
A. The JAR file is located at $JAVA_HOME/jre/classes/myLib.jar. B. The JAR file is located at $JAVA_HOME/jre/lib/ext/myLib.jar.. C. The JAR file is located at /foo/myLib.jar and a classpath environment variable is set that includes /foo/myLib.jar/Paper.class. D. The JAR file is located at /foo/myLib.jar and a classpath environment variable is set that includes /foo/myLib.jar. E. The JAR file is located at /foo/myLib.jar and the Book class is compiled using javac -cp /foo/myLib.jar/Paper Book.java. F. The JAR file is located at /foo/myLib.jar and the Book class is compiled using javac -d /foo/myLib.jar Book.java G. The JAR file is located at /foo/myLib.jar and the Book class is compiled using javac -classpath /foo/myLib.jar Book.java Answer: B,D,G

  

QUESTION NO: 133
A developer is creating a class Book, that needs to access class Paper. The Paper class is
deployed in a JAR named myLib.jar. Which three, taken independently, will allow the developer to
use the Paper class while compiling the Book class? (Choose three.)
A. The JAR file is located at $JAVA_HOME/jre/classes/myLib.jar.
B. The JAR file is located at $JAVA_HOME/jre/lib/ext/myLib.jar..
C. The JAR file is located at /foo/myLib.jar and a classpath environment variable is set that
includes /foo/myLib.jar/Paper.class.
D. The JAR file is located at /foo/myLib.jar and a classpath environment variable is set that
includes /foo/myLib.jar.
E. The JAR file is located at /foo/myLib.jar and the Book class is compiled using javac -cp
/foo/myLib.jar/Paper Book.java.
F. The JAR file is located at /foo/myLib.jar and the Book class is compiled using javac -d
/foo/myLib.jar Book.java
G. The JAR file is located at /foo/myLib.jar and the Book class is compiled using javac -classpath
/foo/myLib.jar Book.java
Answer: B,D,G
Explanation:

  

A UNIX user named Bob wants to replace his chess program with a new one, but he is not sure
where the old one is installed. Bob is currently able to run a Java chess program starting from his
home directory /home/bob using the command: java -classpath /test:/home/bob/downloads/*.jar
games.Chess Bob's CLASSPATH is set (at login time) to:
/usr/lib:/home/bob/classes:/opt/java/lib:/opt/java/lib/*.jar What is a possible location for the
Chess.class file?
A. /test/Chess.class
B. /home/bob/Chess.class
C. /test/games/Chess.class
D. /usr/lib/games/Chess.class
E. /home/bob/games/Chess.class
F. inside jarfile /opt/java/lib/Games.jar (with a correct manifest)
G. inside jarfile /home/bob/downloads/Games.jar (with a correct manifest)
Answer: C
Explanation:

  

QUESTION NO: 139
Given the following directory structure: bigProject |--source | |--Utils.java | |--classes |-- And the
following command line invocation: javac -d classes source/Utils.java Assume the current directory
is bigProject, what is the result?
A. If the compile is successful, Utils.class is added to the source directory.
B. The compiler returns an invalid flag error.
C. If the compile is successful, Utils.class is added to the classes directory.
D. If the compile is successful, Utils.class is added to the bigProject directory.
Answer: C

  

QUESTION NO: 211
Given:
1. package com.company.application;
2.
3. public class MainClass {
4. public static void main(String[] args) {}
5. }
And MainClass exists in the /apps/com/company/application directory. Assume the CLASSPATH
environment variable is set to "." (current directory). Which two java commands entered at the
command line will run MainClass? (Choose two.)
A. java MainClass if run from the /apps directory
B. java com.company.application.MainClass if run from the /apps directory
C. java -classpath /apps com.company.application.MainClass if run from any directory
D. java -classpath . MainClass if run from the /apps/com/company/application directory
E. java -classpath /apps/com/company/application:. MainClass if run from the /apps directory
F. java com.company.application.MainClass if run from the /apps/com/company/application
directory
Answer: B,C

  

QUESTION NO: 237
Given a correctly compiled class whose source code is:
1. package com.sun.sjcp;
2. public class Commander {
3. public static void main(String[] args) {
4. // more code here
5. }
6. }
Assume that the class file is located in /foo/com/sun/sjcp/, the current directory is /foo/, and that
the classpath contains "." (current directory). Which command line correctly runs Commander?
A. java Commander
B. java com.sun.sjcp.Commander
C. java com/sun/sjcp/Commander
D. java -cp com.sun.sjcp Commander
E. java -cp com/sun/sjcp Commander
Answer: B

  

A developer is creating a class Book, that needs to access class Paper. The Paper class is
deployed in a JAR named myLib.jar. Which three, taken independently, will allow the developer to
use the Paper class while compiling the Book class? (Choose three.)
A. The JAR file is located at $JAVA_HOME/jre/classes/myLib.jar.
B. The JAR file is located at $JAVA_HOME/jre/lib/ext/myLib.jar..
C. The JAR file is located at /foo/myLib.jar and a classpath environment variable is set that
includes /foo/myLib.jar/Paper.class.
D. The JAR file is located at /foo/myLib.jar and a classpath environment variable is set that
includes /foo/myLib.jar.
E. The JAR file is located at /foo/myLib.jar and the Book class is compiled using javac -cp
/foo/myLib.jar/Paper Book.java.
F. The JAR file is located at /foo/myLib.jar and the Book class is compiled using javac -d
/foo/myLib.jar Book.java
Oracle 1z0-851 Exam
http://www.maitiku.com QQ:860424807 192
G. The JAR file is located at /foo/myLib.jar and the Book class is compiled using javac -classpath
/foo/myLib.jar Book.java
Answer: B,D,G

 

QUESTION NO: 240
Given:
1. package com.company.application;
2.
3. public class MainClass {
4. public static void main(String[] args) {}
5. } And MainClass exists in the /apps/com/company/application directory. Assume the
CLASSPATH environment variable is set to "." (current directory).
Which two java commands entered at the command line will run MainClass? (Choose two.)
A. java MainClass if run from the /apps directory
B. java com.company.application.MainClass if run from the /apps directory
C. java -classpath /apps com.company.application.MainClass if run from any directory
D. java -classpath . MainClass if run from the /apps/com/company/application directory
E. java -classpath /apps/com/company/application:. MainClass if run from the /apps directory
F. java com.company.application.MainClass if run from the /apps/com/company/application
directory
Answer: B,C

  

 

猜你喜欢

转载自www.cnblogs.com/kingdelee/p/6847885.html