Must read: Java interfaces

http://www.javaworld.com/article/3171300/java-language/java-101-interfaces-in-java.html

When client code interacts with names, it will invoke those methods that are declared by List, and which are implemented by ArrayList.

Advertisements

Action time: Let’s start some project

Dear readers and me, I’ve decided that I should start developing my own application. Only this action can justify my accumulation of knowledge. Therefore, let’s decide on couple things:

  1. Frontend: jQuery, AJAX and JavaScript
  2. Backend: Spring framework

As for app idea, I’ve decided that I will be making clone of project which I’m working on now. But I won’t reuse any materials from it, only the knowledge I’ve acquired. I want my project to be opensource so all the codes will be available on my GitHub account. The link I will put once I got anything to show.

Thank you.

Java SE 8 OCA exam: Chapter 5

This is one of the most important chapters as it’s covers the principles of the OOP.

Note:

1. As you know, a Java fle can have many classes but at most one public class. In fact, it
may have no
public class at all. One feature of using the default package private modifier
is that you can define many classes within the same Java file

2.  The rules for applying class access modifiers are identical for interfaces. There can be at
most one
public class or interface in a Java file. Like classes, top-level interfaces can also
be declared with the
public or default modifiers.

3.  In Java, all classes inherit from a single class, java.lang.Object.  Furthermore, java.lang.Object is the only class that doesn’t have any parent classes. When we create new class it will automatically add extends java.lang.Object even thought it’s invisible:
public class Zoo {
}
public class Zoo extends java.lang.Object {
}

4.

Like the this() command that you saw in Chapter 4, the super() command may only
be used as the frst statement of the constructor. For example, the following two class defnitions will not compile:
public class Zoo {
public Zoo() {
System.out.println(“Zoo created”);
super(); // DOES NOT COMPILE
}
}

5. Super tricky. If the subclass has auto constructor it will call it’s super class constructor first, which may be also auto generated. However, when child’s auto constructor is calling the super class’s constructor AND super class’s constructor already have constructor with different signature (ex. public Father(int a)) then the child’s constructor will not compile. Because it’s superclass’s constructor becomes undefined. JAVA WTF?

Introducing Class Inheritance

Inheritance is the process by which the new child subclass automatically includes any
public or protected primitives, objects, or methods defined in the parent class.

Java supports single inheritance, by which a class may inherit from only one direct parent class.

Java also supports multiple levels of inheritance, by which one class may extend
another class, which in turn extends another class. You can extend a class any number of
times, allowing each descendant to gain access to its ancestor’s members.

Java does allow one exception to the single inheritance rule: classes may implement multiple interfaces, as you’ll see later in this chapter.

It is possible in Java to prevent a class from being extended by marking the class with
the
final modifer. If you try to defne a class that inherits from a final class, the compiler
will throw an error and not compile.

Java allows only one public class per file.

For the OCA exam, you should only be familiar with public and default
package-level class access modifiers, because these are the only ones that
can be applied to top-level classes within a Java file. The
protected and
private modifiers can only be applied to inner classes, which are classes
that are defined within other classes, but this is well out of scope for the
OCA exam.

Defining Constructors

In Java, the first statement of every constructor is either a call to another constructor
within the class, using
this(), or a call to a constructor in the direct parent class, using super().

Following three class and constructor definitions are equivalent, because the compiler will automatically convert them all to the last example:

public class Donkey {
}
public class Donkey {
public Donkey() {
}
}
public class Donkey {
public Donkey() {
super();
}
}

In this example no constructor is defned within the Elephant class, so the compiler tries
to insert a default no-argument constructor with a
super() call, as it did in the Donkey
example. The compiler stops, though, when it realizes there is no parent constructor that
takes no arguments. 

public class Mammal {
public Mammal(int age) {
}
}
public class Elephant extends Mammal { // DOES NOT COMPILE
}

In this example, we must explicitly defne at least one constructor, as
in the following code:

public class Mammal {
public Mammal(int age) {
}
}
public class Elephant extends Mammal {
public Elephant() { // DOES NOT COMPILE
}
}

This code still doesn’t compile, though, because the compiler tries to insert the noargument super() as the frst statement of the constructor in the Elephant class, and there
is no such constructor in the parent class. We can fx this, though, by adding a call to a parent constructor that takes a fxed argument:
public class Mammal {
public Mammal(int age) {
}
}
public class Elephant extends Mammal {
public Elephant() {
super(10);
}
}
This code will compile because we have added a constructor with an explicit call to a
parent constructor. Note that the class
Elephant now has a no-argument constructor even
though its parent class
Mammal doesn’t. Subclasses may defne no-argument constructors
even if their parent classes do not, provided the constructor of the child maps to a parent
constructor via an explicit call of the
super() command.
You should be wary of any exam question in which the parent class defnes a constructor
that takes arguments and doesn’t defne a no-argument constructor. Be sure to check that
the code compiles before answering a question about it.

***Reviewing Constructor Rules

Let’s review the rules we covered in this section.
Constructor Definition Rules:
1. The first statement of every constructor is a call to another constructor within the class
using
this(), or a call to a constructor in the direct parent class using super().
2. The super() call may not be used after the first statement of the constructor.

3. If no super() call is declared in a constructor, Java will insert a no-argument super()
as the first statement of the constructor.
4. If the parent doesn’t have a no-argument constructor and the child doesn’t define any
constructors, the compiler will throw an error and try to insert a default no-argument
constructor into the child class.
5. If the parent doesn’t have a no-argument constructor, the compiler requires an explicit
call to a parent constructor in each child constructor.
Make sure you understand these rules; the exam will often provide code that breaks one
or many of these rules and therefore doesn’t compile.

 

Java SE 8 OCA exam: Chapter 4

As the previous optimization attempt went well, where I studied for chapter 6, I would like to do the same for chapter 4. In this attempt, I will get specific parts of chapter 4, that will be useful for chapter 5, and once I understand the concepts, I will switch to chapter 5.

Applying Access Modifiers

You already saw that there are four access modifiers: public, private, protected, and
default access. We are going to discuss them in order from most restrictive to least restrictive:
private: Only accessible within the same class
default (package private) access: private and other classes in the same package
protected: default access and child classes
public: protected and classes in the other packages

Private Access

Private access is easy. Only code in the same class can call private methods or access
private fields.

Java SE 8 OCA exam: Chapter 6

I’ve decided to optimize my exam preparation by stuffing smaller chapters in times where I would normally rest. This chapter 6 is excellent candidate since it’s short and easy to understand.

Notes:

1.Pay special attention to code that calls a method on a null or that references an invalid array or ArrayList index. If you spot this, you know the correct answer is that the
code throws an exception.

2. On the exam, you will see two types of code that result in an exception. The frst is code
that’s wrong. For example:
String[] animals = new String[0];
System.out.println(animals[0]);

This code throws an ArrayIndexOutOfBoundsException. That means questions about
exceptions can be hidden in questions that appear to be about something else.

The second way for code to result in an exception is to explicitly request Java to throw
one. Java lets you write statements like these:
throw new Exception();
throw new Exception(“Ow! I fell.”);
throw new RuntimeException();
throw new RuntimeException(“Ow! I fell.”);

3.  To review catching multiple exceptions, remember that at most one catch block will run
and it will be the first
catch block that can handle it.

4.  Even though the topic of reading files is on the OCP exam, the OCA exam
may ask you about exception handling with those classes. This is actually a
gift. When you see such a question, you know the problem has to be about
basic Java syntax or exception handling!

5. For the exam, we’ll need to recognize which type of an exception it is and whether it’s thrown by the JVM or a programmer.
6.  If a try statement has multiple catch blocks, at most one catch block can run. Java
looks for an exception that can be caught by each
catch block in the order they appear, and
the frst match is run. Then execution continues after the
try statement. If both catch and
finally throw an exception, the one from finally gets thrown.

7. Note, NumberFormatException example is when we try to convert string to int. ex. Integer.parseInt(“abc”);

8.  When a method overrides a method in a superclass or interface, it is not allowed to add
checked exceptions. It is allowed to declare fewer exceptions or declare a subclass of a
declared exception. Methods declare exceptions with the keyword
throws.

9.  Identify whether an exception is thrown by the programmer or the JVM. Illegal
ArgumentException
and NumberFormatException are commonly thrown by the programmer. Most of the other runtime exceptions are typically thrown by the JVM

10.  Recognize when to use throw versus throws. The throw keyword is used when you actually want to throw an exception—for example, throw new RuntimeException(). The
throws keyword is used in a method declaration

11. If the method has exception that was not caught, that method will exit, but you must remember just before exiting the method, it will run the finally block.

12.

public void run() {
System.out.print(“1”);
try {
System.out.print(“2”);
name.toString();
System.out.print(“3”);
} catch (NullPointerException e) {
System.out.print(“4”);

}
System.out.print(“5”);
}

public static void main(String[] arg) {
Substitute jerry = new Substitute();
jerry.run();
System.out.print(“6”);}

Output is: 12456

13. Methods can return exception object

public Exception myExc(){
Exception e = new Exception();
return e;
}   // will compile and return some exception

14.

Which of the following can be inserted in the blank to make the code compile? (Choose all
that apply)
public static void main(String[] args) {
try {
System.out.println(“work real hard”);
} catch (______ e) {
} catch (RuntimeException e) {
}
}
A. Exception
B. IOException
C. IllegalArgumentException
D. RuntimeException
E. StackOverflowError
F. None of the above.

C, E. Option C is allowed because it is a more specific type than RuntimeException.
Option E is allowed because it isn’t in the same inheritance tree as RuntimeException. It’s not a good idea to catch either of these. Option B is not allowed because the
method called inside the try block doesn’t declare an IOException to be thrown. The
compiler realizes that IOException would be an unreachable catch block. Option D
is not allowed because the same exception can’t be specified in two different catch
blocks. Finally, option A is not allowed because it’s more general than RuntimeException and would make that block unreachable.

15. What does the output of the following contain? (Choose all that apply)

12: public static void main(String[] args) {
13: System.out.print(“a”);
14: try {
15: System.out.print(“b”);
16: throw new IllegalArgumentException();
17: } catch (IllegalArgumentException e) {
18: System.out.print(“c”);
19: throw new RuntimeException(“1”);
20: } catch (RuntimeException e) {
21: System.out.print(“d”);
22: throw new RuntimeException(“2”);
23: } finally {
24: System.out.print(“e”);
25: throw new RuntimeException(“3”);
26: }
27: }
A. abce
B. abde
C. An exception with the message set to “1”
D. An exception with the message set to “2”
E. An exception with the message set to “3”
F. Nothing; the code does not compile.

A, E. The code begins normally and prints a on line 13, followed by b on line 15. On
line 16, it throws an exception that’s caught on line 17. Remember, only the most specific matching catch is run. Line 18 prints c, and then line 19 throws another exception. Regardless, the finally block runs, printing e. Since the finally block also
throws an exception, that’s the one printed.

ch6.PNG

ch6b.PNG

Checked vs Unchecked(Runtime) exceptions

Unchecked exceptions:

  • represent defects in the program (bugs) – often invalid arguments passed to a non-private method.  “Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program’s logic and cannot be reasonably recovered from at run time.”
  • are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, orIllegalStateException
  • a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)

Checked exceptions:

  • represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
  • are subclasses of Exception
  • a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)

Throwing an exception

 

ch6a.PNG

Try – Catch – Finally

Try always must have EITHER Catch or Finally. It can also have both of them.

Also Try must have { }

Finally will always run if it’s present

System.exit

There is one exception to “the finally block always runs after the catch block” rule:
Java defines a method that you call as
System.exit(0);. The integer parameter is the
error code that gets returned.
System.exit tells Java, “Stop. End the program right now.
Do not pass go. Do not collect $200.” When
System.exit is called in the try or catch
block, finally does not run.

Catching Various Types of Exceptions

OCA exam can defne basic exceptions to show you the hierarchy. You only
need to do two things with this information. First, you must be able to recognize if the
exception is a checked or an unchecked exception. Second, you need to determine if any of
the exceptions are subclasses of the others
 (aka Unreachable exceptions problem)

class AnimalsOutForAWalk extends RuntimeException { }
class ExhibitClosed extends RuntimeException { }
class ExhibitClosedForLunch extends ExhibitClosed { }

Unreachable exceptions

A rule exists for the order of the catch blocks. Java looks at them in the order they
appear. If it is impossible for one of the
catch blocks to be executed, a compiler error
about unreachable code occurs. This happens when a superclass is caught before a subclass.
Remember, we warned you to pay attention to any subclass exceptions.

public void visitMonkeys() {
try {
seeAnimal();
} catch (ExhibitClosed e) {
System.out.print(“not today”);
} catch (ExhibitClosedForLunch e) { // DOES NOT COMPILE because ExhibitClosed is superclass of ExhibitClosedForLunch
System.out.print(“try back later”);
}
}

However if subclass comes first then only superclass, then code will compile. The reason is that in the example above the ExhibitClosedForLunch is not reachable, because it’s subclass of ExhibitClosed

Same case below. ExhibitClosed extends RuntimeException, meaning RuntimeException will throw the exception and ExhibitClosed is not reachable.

public void visitSnakes() {
try {
seeAnimal();
} catch (RuntimeException e) {
System.out.print(“runtime exception”);
} catch (ExhibitClosed e) {// DOES NOT COMPILE
System.out.print(“not today”);
} catch (Exception e) {
System.out.print(“exception”);
}
}

Throwing a Second Exception

Line 27 throws an exception, which is caught on line 28. The catch block then throws
an exception on line 29. If there were no
finally block, the exception from line 29 would
be thrown. However, the finally block runs after the try block. Since the finally block
throws an exception of its own on line 31, this one gets thrown. The exception from the
catch block gets forgotten about.

26: try {
27: throw new RuntimeException();
28: } catch (RuntimeException e) {
29: throw new RuntimeException();
30: } finally {
31: throw new Exception();
32: }

30: public String exceptions() {
31: String result = “”;
32: String v = null;
33: try {
34: try {
35: result += “before”;
36: v.length();
37: result += “after”;
38: } catch (NullPointerException e) {
39: result += “catch”;
40: throw new RuntimeException();
41: } finally {
42: result += “finally”;
43: throw new Exception();
44: }
45: } catch (Exception e) {
46: result += “done”;
47: }
48: return result;
49: }

The correct answer is before catch finally done. Everything is normal up until line
35, when
“before” is added. Line 36 throws a NullPointerException. Line 37 is skipped
as Java goes straight to the
catch block. Line 38 does catch the exception, and “catch” is
added on line 39. Then line 40 throws a
RuntimeException. The finally block runs after
the
catch regardless of whether an exception is thrown; it adds “finally” to result. At this
point, we have completed the inner
try statement that ran on lines 34–44. The outer catch
block then sees an exception was thrown and catches it on line 45; it adds “done” to result.

Recognizing Common Exception Types

There are 3 types of exceptions in Java: runtime exceptions, checked exceptions, and errors.

Runtime Exceptions

Runtime exceptions extend RuntimeException. Remember if the superclass preceeds the subclass in catch blocks then subclass becomes unreachable.

ArithmeticException Thrown by the JVM when code attempts to divide by zero
ArrayIndexOutOfBoundsException Thrown by the JVM when code uses an illegal
index to access an array

ex: 

int[] countsOfMoose = new int[3];
System.out.println(countsOfMoose[-1]);

ClassCastException Thrown by the JVM when an attempt is made to cast an exception to a subclass of which it is not an instance

String type = “moose”;
Integer number = (Integer) type; // DOES NOT COMPILE

String type = “moose”;
Object obj = type;
Integer number = (Integer) obj;

IllegalArgumentException Thrown by the programmer to indicate that a method has
been passed an illegal or inappropriate argument. Since it’s thrown by programmer, good way of looking at is, is to think of this exception as a guidance for good values, when the programmer sees the exception log.

public static void setNumberEggs(int numberEggs) {
if (numberEggs < 0)
throw new IllegalArgumentException(
“# eggs must not be negative”);
this.numberEggs = numberEggs;
}

Output:

Exception in thread “main” java.lang.IllegalArgumentException: # eggs must not
be negative

NullPointerException Thrown by the JVM when there is a null reference where an
object is required

String name;
public void printLength() throws NullPointerException {
System.out.println(name.length());
}

Exception in thread “main” java.lang.NullPointerException

NumberFormatException Thrown by the programmer when an attempt is made to convert a string to a numeric type but the string doesn’t have an appropriate format

NumberFormatException is a subclass of IllegalArgumentException!

Integer.parseInt(“abc”);
The output looks like this:
Exception in thread “main” java.lang.NumberFormatException: For input string:
“abc

Checked Exceptions

Checked exceptions have Exception in their hierarchy but not RuntimeException. They
must be handled or declared. They can be thrown by the programmer or by the JVM.
Common runtime exceptions include the following:

FileNotFoundException Thrown programmatically when code tries to reference a fle
that does not exist
IOException Thrown programmatically when there’s a problem reading or writing a fle

Also keep in mind that FileNotFoundException is a subclass of IOException, although the exam will remind you of that fact if it comes up.

Errors

Errors extend the Error class. They are thrown by the JVM and should not be handled or
declared. Errors are rare, but you might see these:
ExceptionInInitializerError Thrown by the JVM when a static initializer throws
an exception and doesn’t handle it

static {
int[] countsOfMoose = new int[3];
int num = countsOfMoose[-1];
}
public static void main(String[] args) { }

Exception in thread “main” java.lang.ExceptionInInitializerError
Caused by: java.lang.ArrayIndexOutOfBoundsException: -1

StackOverflowError Thrown by the JVM when a method calls itself too many times
(this is called
infnite recursion because the method typically calls itself without end)

public static void doNotCodeThis(int num) {
doNotCodeThis(1);
}
The output contains this line:
Exception in thread “main” java.lang.StackOverflowError
NoClassDefFoundError Thrown by the JVM when a class that the code uses is available
at compile time but not runtime

This error won’t show up in code on the exam—you just need to know that it is an error.
NoClassDefFoundError occurs when Java can’t fnd the class at runtime.

Calling Methods That Throw Exceptions

class NoMoreCarrotsException extends Exception {}
public class Bunny {
public static void main(String[] args) {
eatCarrot();// DOES NOT COMPILE because missing exception handling for the method //that throws NoMoreCarrotsException
}
private static void eatCarrot() throws NoMoreCarrotsException {
}
}

The problem is that NoMoreCarrotsException is a checked exception. Checked exceptions must be handled or declared. The code would compile if we changed the main()
method to either of these:
public static void main(String[] args)
throws NoMoreCarrotsException {// declare exception
eatCarrot();
}
public static void main(String[] args) {
try {
eatCarrot();
} catch (NoMoreCarrotsException e ) {// handle exception
System.out.print(“sad rabbit”);
}
}

You might have noticed that eatCarrot() didn’t actually throw an exception; it just
declared that it could. This is enough for the compiler to require the caller to handle or
declare the exception

public void bad() {
try {
eatCarrot();
} catch (NoMoreCarrotsException e ) {// DOES NOT COMPILE because eatCarrot does not //throw any exceptions and catch block is actually unreachable
System.out.print(“sad rabbit”);
}
}
public void good() throws NoMoreCarrotsException {
eatCarrot();
}
private static void eatCarrot() { }
   // note that this method does not throw any exception

Java knows that eatCarrot() can’t throw a checked exception—which means there’s no
way for the
catch block in bad() to be reached. In comparison, good() is free to declare
other exceptions.

Subclasses

Note: Subclasses when they want to override the superclass method, they can’t add checked exceptions, but overriden method can throw runtime exceptions. Also if superclass’s method throws some checked exception, overriden method in subclass actually can throw checked exception that is inherited from checked exception thrown by the superclass’s method. Sounds super difficult but I will give examples.

class CanNotHopException extends Exception { }
class Hopper {
public void hop() { }
}
class Bunny extends Hopper {
public void hop() throws CanNotHopException { } // DOES NOT COMPILE because    

// superclass’s method doen’t throw checked exception.
}

class Hopper {
public void hop() throws CanNotHopException { }
}
class Bunny extends Hopper {
public void hop() { }     // compiles because overriden method doesn’t throw the exception
}

class Hopper {
public void hop() throws Exception { }
}
class Bunny extends Hopper {
public void hop() throws CanNotHopException { }     // this is allowed because CanNOtHopException is inherited from Exception
}

class Hopper {
public void hop() { }
}

class Bunny extends Hopper {
public void hop() throws IllegalStateException { }    // compiles, because only runtime //exceptions can be added to overriden methods
}

When a class overrides a method from a  superclass or implements a method from an interface, it’s not allowed to add new checked exceptions to the method signature. For example, this code isn’t allowed:

 

Printing an Exception

There are three ways to print an exception.  You can let Java print it out, print just the message, or print where the stack trace comes from.


This example shows all three approaches:
5: public static void main(String[] args) {
6: try {
7: hop();
8: } catch (Exception e) {
9: System.out.println(e);
10: System.out.println(e.getMessage());  // this will only print “cannot hop”
11: e.printStackTrace();                                  // will show exception and line where it happens
12: }
13: }
14: private static void hop() {
15: throw new RuntimeException(“cannot hop”);
16: }
This code results in the following output:
java.lang.RuntimeException: cannot hop
cannot hop
java.lang.RuntimeException: cannot hop
at trycatch.Handling.hop(Handling.java:15)
at trycatch.Handling.main(Handling.java:7)

The stack trace is usually the most helpful one because it shows where the exception
occurred in each method that it passed through.

Exception Swallowing

Because checked exceptions require you to handle or declare them, there is a temptation
to catch them so they “go away.” But doing so can cause problems. In the following code,
there’s a problem reading in the file:

 

public static void main(String[] args) {
String textInFile = null;
try {
readInFile();
} catch (IOException e) {
// ignore exception               // since nothing happens here, exception is considered to be swallowed. good idea would be to add e.printStackTrace()
}
// imagine many lines of code here
System.out.println(textInFile.replace(” “, “”));
}
private static void readInFile() throws IOException {
throw new IOException();
}
The code results in a NullPointerException. Java doesn’t tell you anything about the
original
IOException because it was handled. Granted, it was handled poorly, but it was
handled.
When writing your own code, print out a stack trace or at least a message when catching
an exception.

 

Chapter 3 Test highlights:

 

1. Which of the following statements are true? (Choose all that apply)
A. Runtime exceptions are the same thing as checked exceptions.
B. Runtime exceptions are the same thing as unchecked exceptions.
C. You can declare only checked exceptions.
D. You can declare only unchecked exceptions.
E. You can handle only Exception subclasses.

B. Runtime exceptions are also known as unchecked exceptions. They are allowed
to be declared, but they don’t have to be. Checked exceptions must be handled or
declared. Legally, you can handle java.lang.Error subclasses, but it’s not a good idea.

5. Which of the following exceptions are thrown by the JVM? (Choose all that apply)
A. ArrayIndexOutOfBoundsException
B. ExceptionInInitializerError
C. java.io.IOException
D. NullPointerException
E. NumberFormatException

A, B, D. java.io.IOException is thrown by many methods in the java.io package,
but it is always thrown programmatically. The same is true for NumberFormatException; it is thrown programmatically by the wrapper classes of java.lang. The other
three exceptions are all thrown by the JVM when the corresponding problem arises.

7. What is printed besides the stack trace caused by the NullPointerException from line 16?
1: public class DoSomething {
2: public void go() {
3: System.out.print(“A”);
4: try {
5: stop();
6: } catch (ArithmeticException e) {
7: System.out.print(“B”);
8: } finally {
9: System.out.print(“C”);
10: }
11: System.out.print(“D”);
12: }
13: public void stop() {
14: System.out.print(“E”);
15: Object x = null;
16: x.toString();
17: System.out.print(“F”);
18: }
19: public static void main(String[] args) {
20: new DoSomething().go();
21: }
22: }
A. AE
B. AEBCD
C. AEC
D. AECD
E. No output appears other than the stack trace.

C. The main() method invokes go and A is printed on line 3. The stop method is
invoked and E is printed on line 14. Line 16 throws a NullPointerException, so stop
immediately ends and line 17 doesn’t execute. The exception isn’t caught in go, so the
go method ends as well, but not before its finally block executes and C is printed on
line 9. Because main() doesn’t catch the exception, the stack trace displays and no further output occurs, so AEC was the output printed before the stack trace.

9. What is the output of the following program?
1: public class Laptop {
2: public void start() {
3: try {
4: System.out.print(“Starting up “);
5: throw new Exception();
6: } catch (Exception e) {
7: System.out.print(“Problem “);
8: System.exit(0);
9: } finally {
10: System.out.print(“Shutting down “);
11: }
12: }
13: public static void main(String[] args) {
14: new Laptop().start();
15: } }
A. Starting up
B. Starting up Problem
C. Starting up Problem Shutting down
D. Starting up Shutting down
E. The code does not compile.
F. An uncaught exception is thrown

B. The main() method invokes start on a new Laptop object. Line 4 prints Starting
up; then line 5 throws an Exception. Line 6 catches the exception, line 7 prints
Problem, and then line 8 calls System.exit, which terminates the JVM. The finally
block does not execute because the JVM is no longer running.

11. What is the output of the following program?
1: public class Cat {
2: public String name;
3: public void parseName() {
4: System.out.print(“1”);
5: try {
6: System.out.print(“2”);
7: int x = Integer.parseInt(name);
8: System.out.print(“3”);
9: } catch (NullPointerException e) {
10: System.out.print(“4”);
11: }
12: System.out.print(“5”);
13: }
14: public static void main(String[] args) {
15: Cat leo = new Cat();
16: leo.name = “Leo”;
17: leo.parseName();
18: System.out.print(“6”);
19: }
20: }
A. 12, followed by a stack trace for a NumberFormatException
B. 124, followed by a stack trace for a NumberFormatException
C. 12456
D. 12456
E. 1256, followed by a stack trace for a NumberFormatException
F. The code does not compile.
G. An uncaught exception is thrown.

A. The parseName method is invoked on a new Cat object. Line 4 prints 1. The try
block is entered, and line 6 prints 2. Line 7 throws a NumberFormatException. It isn’t
caught, so parseName ends. main() doesn’t catch the exception either, so the program
terminates and the stack trace for the NumberFormatException is printed.

12. What is printed by the following? (Choose all that apply)
1: public class Mouse {
2: public String name;
3: public void run() {
4: System.out.print(“1”);
5: try {
6: System.out.print(“2”);
7: name.toString();
8: System.out.print(“3”);
9: } catch (NullPointerException e) {
10: System.out.print(“4”);
11: throw e;
12: }
13: System.out.print(“5”);
14: }
15: public static void main(String[] args) {
16: Mouse jerry = new Mouse();
17: jerry.run();
18: System.out.print(“6”);
19: } }
A. 1
B. 2
C. 3
D. 4
E. 5
F. 6
G. The stack trace for a NullPointerException

A, B, D, G. The main() method invokes run on a new Mouse object. Line 4 prints 1 and
line 6 prints 2, so options A and B are correct. Line 7 throws a NullPointerException,
which causes line 8 to be skipped, so C is incorrect. The exception is caught on line 9
and line 10 prints 4, so option D is correct. Line 11 throws the exception again, which
causes run() to immediately end, so line 13 doesn’t execute and option E is incorrect.
The main() method doesn’t catch the exception either, so line 18 doesn’t execute and
option F is incorrect. The uncaught NullPointerException causes the stack trace to be
printed, so option G is correct.

13. Which of the following statements are true? (Choose all that apply)
A. You can declare a method with Exception as the return type.
B. You can declare any subclass of Error in the throws part of a method declaration.
C. You can declare any subclass of Exception in the throws part of a method
declaration.
D. You can declare any subclass of Object in the throws part of a method declaration.
E. You can declare any subclass of RuntimeException in the throws part of a method
declaration.

A, B, C, E. Classes listed in the throws part of a method declaration must extend
java.lang.Throwable. This includes Error, Exception, and RuntimeException. Arbitrary classes such as String can’t go there. Any Java type, including Exception, can
be declared as the return type. However, this will simply return the object rather than
throw an exception.

14. Which of the following can be inserted on line 8 to make this code compile? (Choose all
that apply)
7: public void ohNo() throws IOException {
8: // INSERT CODE HERE
9: }
A. System.out.println(“it’s ok”);
B. throw new Exception();
C. throw new IllegalArgumentException();
D. throw new java.io.IOException();
E. throw new RuntimeException();

A, C, D, E. A method that declares an exception isn’t required to throw one, making
option A correct. Runtime exceptions can be thrown in any method, making options
C and E correct. Option D matches the exception type declared and so is also correct.
Option B is incorrect because a broader exception is not allowed.

17. Which of the following can be inserted into Lion to make this code compile? (Choose all
that apply)
class HasSoreThroatException extends Exception {}
class TiredException extends RuntimeException {}
interface Roar {
void roar() throws HasSoreThroatException;
}
class Lion implements Roar {// INSERT CODE HERE
}
A. public void roar(){}
B. public void roar() throws Exception{}
C. public void roar() throws HasSoreThroatException{}
D. public void roar() throws IllegalArgumentException{}
E. public void roar() throws TiredException{}

A, C, D, E. The method is allowed to throw no exceptions at all, making option A correct. It is also allowed to throw runtime exceptions, making options D and E correct.
Option C is also correct since it matches the signature in the interface.

18. Which of the following are true? (Choose all that apply)
A. Checked exceptions are allowed to be handled or declared.
B. Checked exceptions are required to be handled or declared.
C. Errors are allowed to be handled or declared.
D. Errors are required to be handled or declared.
E. Runtime exceptions are allowed to be handled or declared.
F. Runtime exceptions are required to be handled or declared.

A, B, C, E. Checked exceptions are required to be handled or declared. Runtime
exceptions are allowed to be handled or declared. Errors are allowed to be handled or
declared, but this is bad practice.

19. Which of the following can be inserted in the blank to make the code compile? (Choose all
that apply)
public static void main(String[] args) {
try {
System.out.println(“work real hard”);
} catch (______ e) {
} catch (RuntimeException e) {
}
}
A. Exception
B. IOException
C. IllegalArgumentException
D. RuntimeException
E. StackOverflowError
F. None of the above.

C, E. Option C is allowed because it is a more specific type than RuntimeException.
Option E is allowed because it isn’t in the same inheritance tree as RuntimeException. It’s not a good idea to catch either of these. Option B is not allowed because the
method called inside the try block doesn’t declare an IOException to be thrown. The
compiler realizes that IOException would be an unreachable catch block. Option D
is not allowed because the same exception can’t be specified in two different catch
blocks. Finally, option A is not allowed because it’s more general than RuntimeException and would make that block unreachable.

20. What does the output of the following contain? (Choose all that apply)
12: public static void main(String[] args) {
13: System.out.print(“a”);
14: try {
15: System.out.print(“b”);
16: throw new IllegalArgumentException();
17: } catch (IllegalArgumentException e) {
18: System.out.print(“c”);
19: throw new RuntimeException(“1”);
20: } catch (RuntimeException e) {
21: System.out.print(“d”);
22: throw new RuntimeException(“2”);
23: } finally {
24: System.out.print(“e”);
25: throw new RuntimeException(“3”);
26: }
27: }
A. abce
B. abde
C. An exception with the message set to “1”
D. An exception with the message set to “2”
E. An exception with the message set to “3”
F. Nothing; the code does not compile.

A, E. The code begins normally and prints a on line 13, followed by b on line 15. On
line 16, it throws an exception that’s caught on line 17. Remember, only the most specific matching catch is run. Line 18 prints c, and then line 19 throws another exception. Regardless, the finally block runs, printing e. Since the finally block also
throws an exception, that’s the one printed.

 

 

 

 

Java SE 8 OCA exam: Chapter 2

Note:

1.Binary operations such as +,-,*,/,% will always convert both of the variables to to Int!

2.  Compound Assignment Operators (ex: y*=z or x+=b) will cast the values to the one which is on the left most.

3. But remember that if left hand side of equation is bigger in terms of data type then, it will be cast implicitly.

ex.:

short a=1;
short b=2;
double c=a+b;             // Compiles, because of implicit conversion

4.

short a=1;
short b=2;
short c=a+b;             // Doesn’t compile, because need to cast resulting int from addition must be cast to short adding casting so it becomes: short c=(short)(a+b)

 

Tricky questions:

1. What is the data type of x + y?
double x = 39.21;
float y = 2.1;

This is actually a trick question, as this code will not compile! As you may remember
from Chapter 1, floating-point literals are assumed to be
double, unless postfxed with
an
f, as in 2.1f. If the value was set properly to 2.1f, then the promotion would be
similar to the last example, with both operands being promoted to a
double, and the
result would be a
double value

2.  Keep an eye out for questions on the exam that use the logical complement
operator or numeric values with
boolean expressions or variables. Unlike
some other programming languages, in Java
1 and true are not related in
any way, just as
0 and false are not related

3.  2147483647 is limit for int so adding any more value than that will convert it to negative value

System.out.print(2147483647+1);               // -2147483648

4.

short x = 10;
short y = 3;
short z = x * y; // DOES NOT COMPILE

If you remember, short values are automatically promoted to int when applying any arithmetic operator, with the resulting value being of type int. Trying to set a short variable to an int results in a compiler error, as Java thinks
you are trying to implicitly convert from a larger data type to a smaller one.

short x = 10;
short y = 3;
short z = (short)(x * y);

By performing this explicit cast of a larger value into a smaller data type, you are
instructing the compiler to ignore its default behavior.

5.

long x = 5;
long y = (x=3);
System.out.println(x); // Outputs 3
System.out.println(y); // Also, outputs 3

6.

double a=3.2;
int b=5;
b+=a;  // b will be equal to 8, because when a converted to int, it loses some of precision

7.

Be wary of short-circuit behavior on the exam, as questions are known to alter a variable on the right-hand side of the expression that may never be reached. For example, what
is the output of the following code?
int x = 6;
boolean y = (x >= 6) || (++x <= 7);
System.out.println(x);
Because x >= 6 is true, the increment operator on the right-hand side of the expression
is never evaluated, so the output is
6.

8.  In Java 1 does not mean true and 0 does not mean false and vice versa.

int x = 1;
if(x) { // DOES NOT COMPILE

}

9.

int x = 1;
if(x = 5) { // DOES NOT COMPILE

}

10.
System.out.println((y > 5) ? 21 : “Zebra”);
int animal = (y < 91) ? 9 : “Horse”; // DOES NOT COMPILE

11.

int y = 1;
int z = 1;
final int x = y<10 ? y++ : z++;
System.out.println(y+”,”+z); // Outputs 2,1

12.

int dayOfWeek = 6;
switch (dayOfWeek) {
case 0:
System.out.println(“Sunday”);
default:
System.out.println(“Weekday”);
// case 17:
// System.out.println(“WHATTTT???”);
// break;
case 6:
System.out.println(“Saturday”);
case 7:
System.out.println(“Weee!”);
}

// Output
// Saturday
// Weee!

13.

The case statement value must also be a literal, enum constant, or final constant
variable.

private int getSortOrder(String firstName, final String lastName) {
String middleName = “Patricia”;
final String suffix = “JR”;
int id = 0;
switch(firstName) {
case “Test”:
return 52;

case middleName: // DOES NOT COMPILE

id = 5;
break;
case suffix:
id = 0;
break;
case lastName: // DOES NOT COMPILE
id = 8;
break;
case 5: // DOES NOT COMPILE
id = 7;
break;
case ‘J’: // DOES NOT COMPILE
id = 10;
break;
case java.time.DayOfWeek.SUNDAY: // DOES NOT COMPILE
id=15;
break;
}
return id;
}

The frst case statement compiles without issue using a String literal and is a good
example of how a
return statement, like a break statement, can be used to exit the switch
statement early. The second case statement does not compile because middleName is not a final variable, despite having a known value at this particular line of execution. The third
case statement compiles without issue because suffix is a final constant variable.
In the fourth
case statement, despite lastName being final, it is not constant as it is
passed to the function; therefore, this line does not compile as well. Finally, the last three
case statements don’t compile because none of them have a matching type of String; the
last one is an
enum value.

14.

a. int x = 0;
for(long y = 0, z = 4; x < 5 && y < 10; x++, y++) {
System.out.print(y + ” “);
}
System.out.print(x);
  // will compile

b.

for(long y = 0, int x = 4; x < 5 && y<10; x++, y++) { // DOES NOT COMPILE
System.out.print(x + ” “);
}
  // will not compile because y and x are different data types

15.

String[] names = new String[3];
for(int name : names) { // DOES NOT COMPILE
System.out.print(name + ” “);
}

// to fix change int to String

16.

List<Integer> myList = new ArrayList<>();
myList.add(5);
myList.add(7);
myList.add(1);
for(int numberInList:myList){
System.out.println(numberInList);
}

// this will compile and work, because myList is Iterable

17.

The switch statement is the only one that supports a variety of data types, including String variables as of Java 7 . If and other statements only support boolean.

 

Casting Primitive Values

Casting primitives is required any time you are going from a larger numerical data
type to a smaller numerical data type, or converting from a floating-point number to an
integral value.


int x = (int)1.0;
short y = (short)1921222;              // Stored as 20678

int z = (int)9l;
long t = 192301398193810323L

Compound Assignment Operators

long x = 10;
int y = 5;
y = y * x; // DOES NOT COMPILE
 because can’t convert long to int

long x = 10;
int y = 5;
y *= x;
     // will compile

Relational Operators

We now move on to relational operators, which compare two expressions and return a
boolean value. If the two numeric operands are not of the same data type, the
smaller one is promoted in the manner as previously discussed.

int x = 10, y = 20, z = 10;
System.out.println(x < y); // Outputs true
System.out.println(x <= y); // Outputs true
System.out.println(x >= z); // Outputs true
System.out.println(x > z); // Outputs false

ch2

Difference between logical operators and conditional operators(short circuit operator)

Logical operators are: &, | and ^(xor)

Conditional operators are: &&, ||

The difference is that Conditional operators(aka short circuit operators) will not execute all the statements if the left most or left conditions are true ex:

boolean x = true || (y < 4);

Logical operators can be applied to numbers as well for boolean data.

A more common example of where short-circuit operators are used is checking for null
objects before performing an operation, such as this:
if(x != null && x.getValue() < 5) {
// Do something
}

In this example, if x was null, then the short-circuit prevents a NullPointerException
from ever being thrown, since the evaluation of x.getValue() < 5 is never reached.

Alternatively, if we used a logical &, then both sides would always be evaluated and when x
was null this would throw an exception:
if(x != null & x.getValue() < 5) { // Throws an exception if x is null
// Do something
}

Equality Operators

The equality operators are used in one of three scenarios:


1. Comparing two numeric primitive types. If the numeric values are of different data
types, the values are automatically promoted as previously described. For example,
5 == 5.00 returns true since the left side is promoted to a double.
2. Comparing two boolean values.
3. Comparing two objects, including null and String values.

File x = new File(“myFile.txt”);
File y = new File(“myFile.txt”);
File z = x;
System.out.println(x == y); // Outputs false
System.out.println(x == z); // Outputs true

Overflow and Underflow

Overflow is when a number is so large that it will no longer fit
within the data type, so the system “wraps around” to the next lowest value and counts
up from there.

Underflow ex.:

int underflowExample = -2147483648;

System.out.println(“Underflow: “+ (underflowExample – 1));   //     Underflow:  2147483647

Overflow ex.:

int overflowExample = 2147483647;

System.out.println(“Overflow: “+ (overflowExample + 1)); // Overflow: -2147483648

 

Ternary Operator

booleanExpression ? expression1 : expression2

Switch

Data types supported by switch statements include the following:
int and Integer
byte and Byte
short and Short
char and Character
int and Integer
String
enum values
For the exam, we recommend you memorize this list. Note that
boolean and long, and
their associated wrapper classes, are not supported by
switch statements

int dayOfWeek = 5;
switch(dayOfWeek) {
case 0:
System.out.println(“Sunday”);
default:
System.out.println(“Weekday”);
case 6:
System.out.println(“Saturday”);
break;
}

// Will output Weekday
//Saturday  Because default does not have break statement

Basically everything after default will execute, IF default doesn’t have break, and it will run next statements until it reaches break.

When evaluating switch statements on the exam, always consider that multiple branches may be visited in a single execution

 

Enhanced For loop (aka For-each)

ch2a.PNG

The for-each loop declaration is composed of an initialization section and an object to
be iterated over. The right-hand side of the
for-each loop statement must be a built-in Java array or an object whose class implements java.lang.Iterable, which includes most of
the Java
Collections framework.

Continue and Break optional labels

ch2b.PNG

Chapter 2 Test highlights:

2. What data type (or types) will allow the following code snippet to compile? (Choose all that
apply)
byte x = 5;
byte y = 10;
_____ z = x + y;
A. int
B. long
C. boolean
D. double
E. short
F. byte

A, B, D. The value x + y is automatically promoted to int, so int and data types that
can be promoted automatically from
int will work. Options A, B, D are such data
types. Option C will not work because
boolean is not a numeric data type. Options E
and F will not work without an explicit cast to a smaller data type.

4. What change would allow the following code snippet to compile? (Choose all that apply)
3: long x = 10;
4: int y = 2 * x;
A. No change; it compiles as is.
B. Cast x on line 4 to int.
C. Change the data type of x on line 3 to short.
D. Cast 2 * x on line 4 to int.
E. Change the data type of y on line 4 to short.
F. Change the data type of y on line 4 to long

B, C, D, F. The code will not compile as is, so option A is not correct. The value 2 * x
is automatically promoted to long and cannot be automatically stored in y, which is
in an
int value. Options B, C, and D solve this problem by reducing the long value to
int. Option E does not solve the problem and actually makes it worse by attempting
to place the value in a smaller data type. Option F solves the problem by increasing the
data type of the assignment so that
long is allowed

8. What is the output of the following code snippet?
3: boolean x = true, z = true;
4: int y = 20;
5: x = (y != 10) ^ (z=false);
6: System.out.println(x+”, “+y+”, “+z);
A. true, 10, true
B. true, 20, false
C. false, 20, true
D. false, 20, false
E. false, 20, true
F. The code will not compile because of line 5.

B. This example is tricky because of the second assignment operator embedded in line
5. The expression
(z=false) assigns the value false to z and returns false for the
entire expression. Since
y does not equal 10, the left-hand side returns true; therefore,
the exclusive or (
^) of the entire expression assigned to x is true. The output reflects
these assignments, with no change to
y, so option B is the only correct answer. The
code compiles and runs without issue, so option F is not correct.

9. How many times will the following code print “Hello World”?
3: for(int i=0; i<10 ; ) {
4: i = i++;
5: System.out.println(“Hello World”);
6: }
A. 9
B. 10
C. 11
D. The code will not compile because of line 3.
E. The code will not compile because of line 5.
F. The code contains an infinite loop and does not terminate

F. In this example, the update statement of the for loop is missing, which is fine as the
statement is optional, so option D is incorrect. The expression inside the loop increments
i but then assigns i the old value. Therefore, i ends the loop with the same value
that it starts with: 0. The loop will repeat infinitely, outputting the same statement over
and over again because
i remains 0 after every iteration of the loop.

13.
What is the output of the following code snippet?
3: int x1 = 50, x2 = 75;
4: boolean b = x1 >= x2;
5: if(b = true) System.out.println(“Success”);
6: else System.out.println(“Failure”);
A. Success
B. Failure
C. The code will not compile because of line 4.
D. The code will not compile because of line 5.

A. The code compiles successfully, so options C and D are incorrect. The value of b
after line 4 is false. However, the if-then statement on line 5 contains an assignment,
not a comparison. The variable
b is assigned true on line 3, and the assignment operator returns true, so line 5 executes and displays Success, so the answer is option A.

15.
3: int x = 1, y = 15;
4: while x < 10
5: y––;
6: x++;
7: System.out.println(x+”, “+y);
A. 10, 5
B. 10, 6
C. 11, 5
D. The code will not compile because of line 3.
E. The code will not compile because of line 4.
F. The code contains an infinite loop and does not terminate

E. This is actually a much simpler problem than it appears to be. The while statement
on line 4 is missing parentheses, so the code will not compile, and option E is the correct answer. If the parentheses were added, though, option F would be the correct
answer since the loop does not use curly braces to include
x++ and the boolean expression never changes. Finally, if curly braces were added around both expressions, the
output would be
10, 6 and option B would be correct.

16.
3: do {
4: int y = 1;
5: System.out.print(y++ + ” “);
6: } while(y <= 10);
A. 1 2 3 4 5 6 7 8 9
B. 1 2 3 4 5 6 7 8 9 10
C. 1 2 3 4 5 6 7 8 9 10 11
D. The code will not compile because of line 6.
E. The code contains an infinite loop and does not terminate.

D. The variable y is declared within the body of the do-while statement, so it is out of
scope on line 6. Line 6 generates a compiler error, so option D is the correct answer.

18.
What is the output of the following code snippet?
3: int count = 0;
4: ROW_LOOP: for(int row = 1; row <=3; row++)
5: for(int col = 1; col <=2 ; col++) {
6: if(row * col % 2 == 0) continue ROW_LOOP;
7: count++;
8: }
9: System.out.println(count);
A. 1
B. 2
C. 3
D. 4
E. 6
F. The code will not compile because of line 6

B. The expression on line 5 is true when row * col is an even number. On the first
iteration,
row = 1 and col = 1, so the expression on line 6 is false, the continue is
skipped, and
count is incremented to 1. On the second iteration, row = 1 and
col = 2, so the expression on line 6 is true and the continue ends the outer loop with
count still at 1. On the third iteration, row = 2 and col = 1, so the expression on line
6 is
true and the continue ends the outer loop with count still at 1. On the fourth
iteration,
row = 3 and col = 1, so the expression on line 6 is false, the continue is
skipped, and
count is incremented to 2. Finally, on the fifth and final iteration, row
= 3
and col = 2, so the expression on line 6 is true and the continue ends the outer
loop with
count still at 2. The result of 2 is displayed, so the answer is option B

19.
What is the result of the following code snippet?
3: int m = 9, n = 1, x = 0;
4: while(m > n) {
5: m–;
6: n += 2;
7: x += m + n;
8: }
9: System.out.println(x);
A. 11
B. 13
C. 23
D. 36
E. 50
F. The code will not compile because of line 7

D. Prior to the first iteration, m = 9, n = 1, and x = 0. After the iteration of the first
loop,
m is updated to 8, n to 3, and x to the sum of the new values for m + n, 0 + 11 =
11
. After the iteration of the second loop, m is updated to 7, n to 5, and x to the sum
of the new values for
m + n, 11 + 12 = 23. After the iteration of the third loop, m is
updated to
6, n to 7, and x to the sum of the new values for m + n, 23 + 13 = 36. On
the fourth iteration of the loop,
m > n evaluates to false, as 6 < 7 is not true. The
loop ends and the most recent value of
x, 36, is output, so the correct answer is option
D

Programming: Silly mistakes

This post will capture all the silly mistakes I’ve done so that I won’t repeat them again.

 

  1. While trying to add objects to the object’s list I had issue where all the elements(aka objects) were actually last object that I’ve added.

Code snippet with error:

List&lt;String&gt; characterImage = new ArrayList&lt;String&gt;();
for (int i = 0; i &lt; numberOfCharacters; i++) {
    Character ch = new Character(characterImage);
    for (int j = 0; j &lt; numberOfRows; j++) {
       characterImage.add(sc.next());
 }
 characters.add(ch);
 }

The correct solution should look like this:

List;String&gt; characterImage;
 for (int i = 0; i &lt; numberOfCharacters; i++) {
    characterImage = new ArrayList&lt;String&gt;();
    Character ch = new Character(characterImage);
    for (int j = 0; j &lt; numberOfRows; j++) {
       characterImage.add(sc.next());
 }
 characters.add(ch);
 }

Obvious error, was that characterImage list haven’t been re-created for new object of Character, meaning we’ve been adding same list latest elements to the Character object.