Commits

Micha Kops committed a80e17a

SCJP/OCPJP Certification Samples / Gotchas added

Comments (0)

Files changed (39)

ocjp-preparation-samples/.classpath

+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+	<classpathentry kind="src" path="src"/>
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
+	<classpathentry kind="output" path="bin"/>
+</classpath>

ocjp-preparation-samples/.project

+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>ocjp-preparation-samples</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.jdt.core.javabuilder</name>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.jdt.core.javanature</nature>
+	</natures>
+</projectDescription>

ocjp-preparation-samples/src/com/hascode/exam/Child.java

+package com.hascode.exam;
+
+public class Child extends Dad {
+	static {
+		System.out.println("6");
+	}
+
+	{
+		System.out.println("15");
+	}
+
+	public Child() {
+		System.out.println("17");
+	}
+
+	{
+		System.out.println("16");
+	}
+
+	static {
+		System.out.println("7");
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Dad.java

+package com.hascode.exam;
+
+public class Dad extends Grampa {
+	static {
+		System.out.println("4");
+	}
+
+	{
+		System.out.println("12");
+	}
+
+	public Dad() {
+		System.out.println("14");
+	}
+
+	{
+		System.out.println("13");
+	}
+
+	static {
+		System.out.println("5");
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example1.java

+package com.hascode.exam;
+
+public class Example1 {
+	private final int	x	= 10;
+
+	public static void main(String[] args) {
+		x = 11; // fails
+		System.out.println(getX()); // fails
+		new Example1().getX(); // works
+
+	}
+
+	public int getX() {
+		return x;
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example10.java

+package com.hascode.exam;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class Example10 {
+	public static void main(String[] args) {
+		Map<String, String> map = new HashMap<String, String>();
+		List<String> list = new ArrayList<String>();
+		Set<String> set = new HashSet<String>();
+
+		list.add("test"); // works
+		set.add("test"); // works, too
+		map.add("test", "test"); // does not work
+		map.put("test", "foo"); // that is how it works
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example11.java

+package com.hascode.exam;
+
+public abstract class Example11 {
+	public abstract void doSomething(){}; // no body allowed for abstract methods
+}

ocjp-preparation-samples/src/com/hascode/exam/Example12.java

+package com.hascode.exam;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+
+public class Example12 {
+	public static void main(String[] args) {
+		FileInputStream is;
+		try {
+			is = new FileInputStream(new File("/tmp/test.data"));
+		} catch (FileNotFoundException e) {
+		} finally {
+			is.close(); // unhandled exception of type IOException !!
+		}
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example13.java

+package com.hascode.exam;
+
+public class Example13 {
+	public static void main(String[] args) {
+		final Example13 e = new Example13();
+
+		Integer i1 = 13;
+		e.processLong(i1); // error: you cannot widen a wrapper into another
+							// wrapper ..
+							// this only works for is-a relations
+
+		float f1 = 13f;
+		e.processDouble(f1); // error: first widen (float->double), then box
+								// (double->Double) is not possible
+
+		int i2 = 13;
+		e.processNumber(i2); // works: boxing, then widening is allowed
+	}
+
+	public void processLong(Long l) {
+	}
+
+	public void processDouble(Double d) {
+	}
+
+	public void processNumber(Number n) {
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example14.java

+package com.hascode.exam;
+
+public class Example14 {
+	public static void main(String[] args) {
+		Integer i = 11;
+		new Example14().dieAtRuntime(i); // At runtime we'll get: Exception in
+											// thread "main"
+											// java.lang.ClassCastException:
+											// java.lang.Integer cannot be cast
+											// to java.lang.String
+	}
+
+	public void dieAtRuntime(Object obj) {
+		String s = (String) obj;
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example17.java

+package com.hascode.exam;
+
+public class Example17 {
+	public static void main(String[] args) {
+		new Example17().doSomething();
+	}
+
+	void doSomething() {
+		String str1 = "test";
+		final String str2 = "test";
+		new Thread(new Runnable() {
+			@Override
+			public void run() {
+				System.out.println(str1); // this one fails - cannot refer to
+											// non final variable
+				System.out.println(str2); // this one works
+			}
+		}).start();
+
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example18.java

+package com.hascode.exam;
+
+public class Example18 {
+	public static void main(String[] args) {
+		int x;
+		try {
+			System.out.println(x + 2);
+		} catch (Exception e) {
+		}
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example19.java

+package com.hascode.exam;
+
+public class Example19 {
+	public static void main(String[] args) {
+		int x = 3;
+		if (x > 2 & ++x > 3) // no short circuit AND .. pre-increment on x will
+								// be executed
+			x++;
+		if (x % 5 == 0 ^ true)
+			x += 2;
+		if (x > 1 || ++x > 0) // short circuit operator .. pre increment on x
+								// won't be run
+			x += 20;
+		System.out.println(x); // result is 25
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example2.java

+package com.hascode.exam;
+
+public class Example2 {
+	final Integer	i	= 10;
+	public static void main(String[] args) {
+		new Example2().doIncrement();
+	}
+
+	public void doIncrement() {
+		i++; // fails
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example20.java

+package com.hascode.exam;
+
+import static java.lang.Math; // this won't work
+
+/* 
+ * the correct way is one of those:
+ * 
+ * import static java.lang.Math.*;
+ * import static java.lang.Math.max;
+ * 
+ */
+
+public class Example20 {
+	public static void main(String[] args) {
+		max(2, 4);
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example21.java

+package com.hascode.exam;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
+
+public class Example21 {
+	public static void main(String[] args) {
+		Map<SomeObject, SomeObject> map = new TreeMap<SomeObject, SomeObject>();
+		Set<SomeObject> set = new TreeSet<SomeObject>();
+
+		for (int i = 0; i < 30; i++) {
+			SomeObject obj = new SomeObject(i);
+			map.put(obj, obj); // Exception in thread "main"
+								// java.lang.ClassCastException:
+								// com.hascode.exam.SomeObject cannot be cast to
+								// java.lang.Comparable
+
+			set.add(obj); // Exception in thread "main"
+							// java.lang.ClassCastException:
+							// com.hascode.exam.SomeObject cannot be cast to
+							// java.lang.Comparable
+		}
+	}
+
+}

ocjp-preparation-samples/src/com/hascode/exam/Example22.java

+package com.hascode.exam;
+
+public class Example22 {
+	public static void main(String[] args) {
+		String t = "test";
+		t.replace("te", "this is a te"); // this won't change the String
+											// referenced by t
+		System.out.println(t); // the output is "test"
+	}
+
+}

ocjp-preparation-samples/src/com/hascode/exam/Example23.java

+package com.hascode.exam;
+
+public class Example23 {
+	public static void main(String[] args) throws InterruptedException {
+		RobotTask robot = new RobotTask();
+		for (int i = 0; i < 5; i++) {
+			Worker worker = new Worker(robot);
+			worker.start();
+		}
+		robot.start();
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example24.java

+package com.hascode.exam;
+
+public class Example24 {
+	public static void main(String[] args) {
+		System.out.println("1");
+		new Child();
+		System.out.println("18");
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example25.java

+package com.hascode.exam;
+
+public class Example25 {
+	public static void main(String[] args) {
+
+	}
+
+}

ocjp-preparation-samples/src/com/hascode/exam/Example26.java

+package com.hascode.exam;
+
+public class Example26 extends SomeParent {
+	/**
+	 * fails .. return type must match or be covariant return
+	 */
+	public int doSomething(String test) throws IllegalArgumentException {
+	}
+
+	/**
+	 * fails .. exception is broader than the original exception
+	 */
+	public void doAnotherThing(String test) throws Exception {
+	}
+
+	/**
+	 * works .. NumberFormatException is a narrower exception to the original
+	 * IllegalArgumentException and the less restrictive access modifier is
+	 * allowed
+	 */
+	public void doAThirdThing(String test) throws NumberFormatException {
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example27.java

+package com.hascode.exam;
+
+public class Example27 {
+	public static void main(String[] args) {
+		short x = 4;
+		long y = 10l;
+		Long[] z = new Long[]{};
+
+		Example27 e = new Example27();
+		e.printOut(x);
+		e.printOut(y);
+		e.printOut(z);
+
+	}
+
+	public void printOut(int val) {
+		System.out.println("Integer");
+	}
+
+	public void printOut(Long... val) {
+		System.out.println("Long...");
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example28.java

+package com.hascode.exam;
+
+public class Example28 {
+	public static void main(String[] args) {
+		int[] values = new int[]{};
+		new Example28().process(values); // output is "Object"
+
+		int[][] otherValues = new int[][]{};
+
+		if (values == otherValues) { // this won't compile - different operand
+										// types
+		}
+	}
+	public void process(long x) {
+		System.out.println("long");
+	}
+
+	public void process(Object obj) {
+		System.out.println("Object");
+	}
+
+	public void process(long... values) {
+		System.out.println("int...");
+	}
+
+}

ocjp-preparation-samples/src/com/hascode/exam/Example29.java

+package com.hascode.exam;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class Example29 {
+	public static void main(String[] args) {
+		Set<User> users = new HashSet<User>();
+		User user1 = new User(1l);
+		User user2 = new User(2l);
+		User user3 = new User(1l);
+
+		users.add(user1);
+		users.add(user2);
+		users.add(user3);
+
+		System.out.println(users.size()); // set contains 3 elements
+
+		// if we uncomment the hashCode method the set is going to contain 2
+		// elements
+	}
+
+	private static class User {
+		private Long	userId;
+		public User(Long userId) {
+			this.userId = userId;
+		}
+
+		public Long getUserId() {
+			return userId;
+		}
+
+		public boolean equals(Object obj) {
+			return getUserId().equals(((User) obj).getUserId());
+		}
+
+		// public int hashCode() {
+		// return 12345;
+		// }
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example3.java

+package com.hascode.exam;
+
+public class Example3 {
+	public static void main(String[] args) {
+		String str = "test";
+		str.insert(0, "ing is good"); // StringBuffer's method
+		str.append(" indeed"); // StringBuffer's method
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example4.java

+package com.hascode.exam;
+
+public class Example4 {
+	public static void main(String[] args) {
+		int x = 4;
+		int y = 5;
+		switch (x) {
+			case 4 :
+				System.out.println("A");
+				break;
+			case y : // this one does not work
+				System.out.println("B");
+				break;
+			default :
+				System.out.println("Default");
+		}
+
+		// working sample
+		final int z = 5;
+		switch (x) {
+			case 4 :
+				System.out.println("A");
+				break;
+			case z : // now z is final ..
+				System.out.println("B");
+				break;
+			default :
+				System.out.println("Default");
+		}
+
+		final String str = "test";
+		switch (str) { // strings do not work at all .. wait for Java 7 :)
+		// [..]
+		}
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example5.java

+package com.hascode.exam;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+
+public class Example5 {
+	public static void main(String[] args) {
+		try {
+			BufferedReader reader = new BufferedReader(new FileReader(new File("/tmp/test.dat")));
+		} 
+		System.err.println("test"); // this line is not allowed
+		catch (final FileNotFoundException e) {
+		}
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example6.java

+package com.hascode.exam;
+
+public class Example6 {
+	public static void main(String[] args) {
+		for (int i = 0; i < 100; i++) {
+			System.out.println("iteration: " + i);
+		}
+		System.out.println("total iterations: " + i);
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example7.java

+package com.hascode.exam;
+
+public class Example7 extends ParentExample7 {
+	public void calculateProgress() {
+	}
+
+	public static void main(String[] args) {
+		new Example7().calculateProgress();
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example8.java

+package com.hascode.exam;
+
+public class Example8 {
+	public static void main(String[] args) {
+		int x = 0;
+		int out = 0;
+		boolean z = true;
+		if (z & (++x == 1))
+			out++;
+		if ((z == true) & ++out == 2)
+			out += 3;
+		System.out.println(out);
+
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Example9.java

+package com.hascode.exam;
+
+import java.util.List;
+
+public class Example9 {
+	public void doSomething(List<String> names) {
+	}
+
+	public void doSomething(List<Integer> userIds) {
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Father.java

+package com.hascode.exam;
+
+public class Father {
+	public Father(String name) {
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Grampa.java

+package com.hascode.exam;
+
+public class Grampa {
+	static {
+		System.out.println("2");
+	}
+
+	{
+		System.out.println("8");
+	}
+
+	public Grampa() {
+		this("test");
+		System.out.println("11");
+	}
+
+	public Grampa(String s) {
+		System.out.println("10");
+	}
+
+	{
+		System.out.println("9");
+	}
+
+	static {
+		System.out.println("3");
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/ParentExample7.java

+package com.hascode.exam;
+
+public class ParentExample7 {
+	public static void calculateProgress() {
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/RobotTask.java

+package com.hascode.exam;
+
+public class RobotTask extends Thread {
+	private double	computationTime;
+
+	@Override
+	public void run() {
+		synchronized (this) {
+			try {
+				Thread.sleep(3000);
+				computationTime = Math.random();
+				notifyAll();
+			} catch (InterruptedException e) {
+			}
+		}
+	}
+
+	public double getComputationTime() {
+		return computationTime;
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/SomeObject.java

+package com.hascode.exam;
+
+public class SomeObject {
+	private int	x;
+
+	public SomeObject(int x) {
+		this.x = x;
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/SomeParent.java

+package com.hascode.exam;
+
+public class SomeParent {
+	public void doSomething(String test) throws IllegalArgumentException {
+	}
+
+	public void doAnotherThing(String test) throws IllegalArgumentException {
+	}
+
+	protected void doAThirdThing(String test) throws IllegalArgumentException {
+	}
+}

ocjp-preparation-samples/src/com/hascode/exam/Son.java

+package com.hascode.exam;
+
+public class Son extends Father {
+
+}

ocjp-preparation-samples/src/com/hascode/exam/Worker.java

+package com.hascode.exam;
+
+public class Worker extends Thread {
+	private final RobotTask	robot;
+
+	public Worker(final RobotTask robot) {
+		this.robot = robot;
+	}
+
+	@Override
+	public void run() {
+		System.out.println("Robot calculates ..");
+		synchronized (robot) {
+			try {
+				robot.wait();
+			} catch (InterruptedException e) {
+			}
+			System.out.println("Thread " + Thread.currentThread().getId() + " finished. result: " + robot.getComputationTime());
+		}
+	}
+}