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

Java SE 8 OCA exam: Chapter 1

Tricky questions:

  1. If the code starts from line number 1 and doesn’t have any imports then it’s save to say that code won’t compile. Don’t assume that imports are added automatically. However if there is no main() method, then we can assume that everything else is added automatically.
  2. class Chick(){

public void Chick(){} // this is not constructor}

Note: constructors don’t have return types.

3. Purpose of constructors is to initialize the fields.

Order of initialization

  1. First of all, field and instance initialisers runs first, whatever comes first
  2. Secondly, the constructor runs

public class orderOfInitialization{

string Apple=”Pear”; // this is field

{System.out.println(“this is initializer”); // instanece initializer}

static{

// this is static initializer

}

}// end of class

Data types:

There are 2 types of data in Java: a. Primitive and b. Reference

There are 8 types in Primitives:

boolean, byte(8 bit, example: 123), short(16 bit, example: 123), int(32 bit, example: 123), long(64 bit, example: 123), float(32 bit floating), double(64 bit float, example: 123.45f), double(64bit float, example: 123.456), char(16 bit Unicode)

Each numeric type uses 2 times more memory byte(8 bit), short(16) and so on.

What is the value it can hold?

byte 8 bit can hold 2^8=256, divided in 2 ranges makes it -128 to 127

Java 7 feature:

In java 7 we can add underscore for the integers to improve the readability;

int sum = 1_000_000; // this is valid

int sum = 1_0.0_0; // this is valid

int sum  = _100; // invalid

int sum = 100_;  //invalid

int sum = 100_.00 // invalid

Literals

we can specify the type and base using literals:

int a  = 0b11; // this is for binary and it equals to 3

long max = 3000000000L; // this is more than int can hold so we must add “L” to make sure compiler reads it as Long.

Reference types

A reference type refers to an object (an instance of a class). Unlike primitive types that hold their values in the memory where the variable is allocated, references do not hold the value of the object they refer to. Instead, a reference “points” to an object by storing the memory address where the object is located, a concept referred to as a pointer

String greeting = “How are you?”?

ch1

 

 

Differences between Primitive and Reference types:

First, reference types can be assigned null, which means they do not currently refer
to an object. Primitive types will give you a compiler error if you attempt to assign them
null. In this example, value cannot point to null because it is of type int:


int value = null; // DOES NOT COMPILE
String s = null;

Second, reference types can be used to call methods when they do not point to null.
Primitives do not have methods declared on them.

String reference = “hello”;
int len = reference.length();
int bad = len.length(); // DOES NOT COMPILE

Note:

int num, String value; // DOES NOT COMPILE

double d1, double d2;  // DOES NOT COMPILE

int i3; i4;  // DOES NOT COMPILE

Identifiers AKA variable names

The name must begin with a letter or the symbol $ or _.
Subsequent characters may also be numbers.
You cannot use the same name as a Java reserved word

Ex:

// OK identifiers

okidentifier
$OK2Identifier
_alsoOK1d3ntifi3r
__SStillOkbutKnotsonice$

// NOT OK identifiers

3DPointClass              // identifiers cannot begin with a number
hollywood@vine      // @ is not a letter, digit, $ or _
*$coffee                     // * is not a letter, digit, $ or _
public                         // public is a reserved word

Local variable

A local variable is a variable defined within a method. Local variables must be initialized before use.

4: public int notValid() {
5: int y = 10;
6: int x;
7: int reply = x + y; // DOES NOT COMPILE
8: return reply;
9: }

Also take note that if variable have possibility to be uninitialized like if initialization happening in the If statement then, code won’t compile.

Instance and Class Variables

Variables that are not local variables are known as instance variables or class variables.
Instance variables are also called fields.

You can tell a variable is a class variable because it has the keyword static before it.

Important:

Instance and class variables do not require you to initialize them. As soon as you declare
these variables, they are given a default value. You’ll need to memorize everything in table
1.2 except the default value of
char. To make this easier, remember that the compiler
doesn’t know what value to use and so wants the simplest type it can give the value:
null
for an object and 0/false for a primitive.

class ab{

int apple;  // instance variable

void addSum(){

int pear;

System.out.println(apple);            // will output 0

System.out.println(pear);           // code will not compile

}

}

ch1a

Understanding Variable Scope

public void eat(int piecesOfCheese) {
int bitesOfCheese = 1;
}

Note: above code has 2 local variables declared: piecesOfCheese and bitesOfCheese!

3: public void eatIfHungry(boolean hungry) {
4: if (hungry) {
5: int bitesOfCheese = 1;

6: } // bitesOfCheese goes out of scope here
7: System.out.println(bitesOfCheese);                    // DOES NOT COMPILE
8: }

16: public void eatIfHungry(boolean hungry) {
17: if (hungry) {
18: int bitesOfCheese = 1;
19: {
20: boolean teenyBit = true;
21: System.out.println(bitesOfCheese);
22: }
23: }
24: System.out.println(teenyBit); // DOES NOT COMPILE
25: }

Note:

  1. All that was for local variables. Luckily the rule for instance variables is easier: they are available as soon as they are defined and last for the entire lifetime of the object itself. The rule for class (static) variables is even easier: they go into scope when declared like the other variables types. However, they stay in scope for the entire life of the program.
  2. import aquarium.*;  // will import all the classes in aquarium folder, but it will not include the classes in sub-directories located in aquarium folder!
  3. Local variables do not get assigned default values! The
    code fails to compile if a local variable is not explicitly initialized.  However Instance variables will be assigned their default values, such as int will be 0 and String will become null. Also class static variables are given default value too.
  4.  person a = new person();

person b = a;

a=null;

At this point initial object is NOT ready for garbage collection as it has b still referencing it. However if person object is hanging without any references to it, then it’s eligible for gc. let’s say we had another line b=null, then yes, it’s eligible for gc.

 

 Garbage collection and finalize

Java allows objects to implement a method called finalize() that might get called. This
method gets called if the garbage collector tries to collect the object. If the garbage collector doesn’t run, the method doesn’t get called. If the garbage collector fails to collect the object and tries to run it again later, the method doesn’t get called a second time.

Luckily, there isn’t much to remember about finalize() for the exam. Just keep in mind that it might not get called and that it definitely won’t be called twice

Benefits of Java

  1. Object oriented
  2. Encapsulation
  3. Platform independent
  4. Robust: no memory leaks because garbage collection will clean up all the dangling references. However it’s still possible that gc will not run on some objects since it can’t reach them so there will be memory leak.
  5. Simple: no points, no method overloading(ex: overload a+b to give different result)
  6. Secure: it runs inside the JVM, this creates sandbox so that it prevents computer.

Summary:

  1. Object is an instance of class.
  2. Packages are way of organizing class files in same folder.
  3. java.lang is the package that is automatically imported
  4. Constructors create java objects.  A constructor is a method matching the class name and omitting the return type.
  5. When an object is instantiated, fields and blocks of code are initialized first. Then the constructor is run.
  6. Variables that represent fields in a class are automatically initialized to their corresponding “zero” or null value during object instantiation.
  7. Local variables must be specifically initialized. Identifiers may contain letters, numbers, $, or _. Identifiers may not begin with numbers.
  8. The finalize() method will run once for each object if/when it is first garbage collected. When no arrows point to a box (object), it is eligible for garbage collection.
  9. Access modifiers allow classes to encapsulate data.
  10. Finally, Java is secure because it runs inside a virtual machine.

Chapter 1 Test highlights:

  1. If should not necessarily have the else statement, it can function without else.
  2.  Given the following classes, which of the following can independently replace INSERT IMPORTS HERE to make the code compile? (Choose all that apply)
    package aquarium;
    public class Tank { }
    package aquarium.jellies;
    public class Jelly { }
    package visitor;
    INSERT IMPORTS HERE
    public class AquariumVisitor {
    public void admire(Jelly jelly) { } }
    C. import aquarium.jellies.Jelly;
    D. import aquarium.jellies.*;
    C, D. Option C is correct because it imports Jelly by classname. Option D is correct because it imports all the classes in the jellies package, which includes Jelly. 
  3. Given the following classes, what is the maximum number of imports that can be removed and have the code still compile?
    package aquarium; public class Water { }
    package aquarium;
    import java.lang.*;
    import java.lang.System;
    import aquarium.Water;
    import aquarium.*;
    public class Tank {
    public void print(Water water) {
    System.out.println(water); } }E. 4
    The first two imports can be removed because java.lang is automatically imported.
    The second two imports can be removed because
    Tank and Water are in the same package, making the correct answer E. If Tank and Water were in different packages, one of these two imports could be removed. In that case, the answer would be option D
  4. Given the following classes, which of the following snippets can be inserted in place of INSERT IMPORTS HERE and have the code compile? (Choose all that apply)
    package aquarium;
    public class Water {
    boolean salty = false;
    }
    package aquarium.jellies;
    public class Water {
    boolean salty = true;
    }
    package employee;
    INSERT IMPORTS HERE
    public class WaterFiller {
    Water water;
    }
    A. import aquarium.*;
    B. import aquarium.Water;
    import aquarium.jellies.*;
    C. import aquarium.*;
    import aquarium.jellies.Water;
    D. import aquarium.*;
    import aquarium.jellies.*;
    E. import aquarium.Water;
    import aquarium.jellies.Water;

F. None of these imports can make the code compile.

A, B, C. Option A is correct because it imports all the classes in the aquarium package
including
aquarium.Water. Options B and C are correct because they import Water by
classname. Since importing by classname takes precedence over wildcards, these compile. Option D is incorrect because Java doesn’t know which of the two wildcard
Water
classes to use. Option E is incorrect because you cannot specify the same classname in
two imports.

  1. 5. Which of the following legally fill in the blank so you can run the main() method from the
    command line? (Choose all that apply)
    public static void main( )
    A. String[] _names
    B. String[] 123
    C. String abc[]
    D. String _Names[]
    E. String… $n
    F. String names
    G. None of the above.

A, C, D, E. Option A is correct because it is the traditional main() method signature
and variables may begin with underscores. Options C and D are correct because the
array operator may appear after the variable name. Option E is correct because
varargs are allowed in place of an array. Option B is incorrect because variables are
not allowed to begin with a digit. Option F is incorrect because the argument must be
an array or varargs. Option F is a perfectly good method. However, it is not one that
can be run from the command line because it has the wrong parameter type.

6. Given the following class in the file /my/directory/named/A/Bird.java:
INSERT CODE HERE
public class Bird { }
Which of the following replaces INSERT CODE HERE if we compile from /my/directory?
(Choose all that apply)
A. package my.directory.named.a;
B. package my.directory.named.A;
C. package named.a;
D. package named.A;
E. package a;
F. package A;
G. Does not compile.

D. The package name represents any folders underneath the current path, which is
named.A in this case. Option B is incorrect because package names are case sensitive,
just like variable names and other identifiers.

7. Which of the following lines of code compile? (Choose all that apply)
A. int i1 = 1_234;
B. double d1 = 1_234_.0;
C. double d2 = 1_234._0;
D. double d3 = 1_234.0_;
E. double d4 = 1_234.0;
F. None of the above.

A, E. Underscores are allowed as long as they are directly between two other digits.
This means options A and E are correct. Options B and C are incorrect because the
underscore is adjacent to the decimal point. Option D is incorrect because the underscore is the last character

8. Given the following class, which of the following lines of code can replace INSERT CODE
HERE to make the code compile? (Choose all that apply)
public class Price {
public void admission() {
INSERT CODE HERE
System.out.println(amount);
} }
A. int amount = 9L;
B. int amount = 0b101;
C. int amount = 0xE;
D. double amount = 0xE;
E. double amount = 1_2_.0_0;
F. int amount = 1_2_;
G. None of the above.

B, C, D. 0b is the prefix for a binary value and is correct. 0x is the prefix for a hexadecimal value. This value can be assigned to many primitive types, including int and
double, making options C and D correct. Option A is incorrect because 9L is a long
value.
long amount = 9L would be allowed. Option E is incorrect because the underscore is immediately before the decimal. Option F is incorrect because the underscore is
the very last character.

9. Suppose we have a class named Rabbit. Which of the following statements are true?
(Choose all that apply)
1: public class Rabbit {
2: public static void main(String[] args) {
3: Rabbit one = new Rabbit();
4: Rabbit two = new Rabbit();
5: Rabbit three = one;
6: one = null;
7: Rabbit four = one;
8: three = null;
9: two = null;
10: two = new Rabbit();
11: System.gc();
12: } }

A. The Rabbit object from line 3 is first eligible for garbage collection immediately
following line 6.
B. The Rabbit object from line 3 is first eligible for garbage collection immediately
following line 8.
C. The Rabbit object from line 3 is first eligible for garbage collection immediately
following line 12.
D. The Rabbit object from line 4 is first eligible for garbage collection immediately
following line 9.
E. The Rabbit object from line 4 is first eligible for garbage collection immediately
following line 11.
F. The Rabbit object from line 4 is first eligible for garbage collection immediately
following line 12.

10. What is true about the following code? (Choose all that apply)
public class Bear {
protected void finalize() {
System.out.println(“Roar!”);
}
public static void main(String[] args) {
Bear bear = new Bear();
bear = null;
System.gc();
} }
A. finalize() is guaranteed to be called.
B. finalize() might or might not be called
C. finalize() is guaranteed not to be called.
D. Garbage collection is guaranteed to run.
E. Garbage collection might or might not run.
F. Garbage collection is guaranteed not to run.
G. The code does not compile.

B, E. Calling System.gc() suggests that Java might wish to run the garbage collector.
Java is free to ignore the request, making option E correct.
finalize() runs if an object
attempts to be garbage collected, making option B correct.

11. What does the following code output?
1: public class Salmon {
2: int count;
3: public void Salmon() {
4: count = 4;
5: }
6: public static void main(String[] args) {
7: Salmon s = new Salmon();
8: System.out.println(s.count);
9: } }
A. 0
B. 4
C. Compilation fails on line 3.
D. Compilation fails on line 4.
E. Compilation fails on line 7.
F. Compilation fails on line 8.

A. While the code on line 3 does compile, it is not a constructor because it has a return
type. It is a method that happens to have the same name as the class. When the code
runs, the default constructor is called and count has the default value (0) for an
int.

12. Which of the following are true statements? (Choose all that apply)
A. Java allows operator overloading.
B. Java code compiled on Windows can run on Linux.
C. Java has pointers to specific locations in memory.
D. Java is a procedural language.
E. Java is an object-oriented language.
F. Java is a functional programming language.

B, E. C++ has operator overloading and pointers. Java made a point of not having
either. Java does have references to objects, but these are pointing to an object that can
move around in memory. Option B is correct because Java is platform independent.
Option E is correct because Java is object oriented. While it does support some parts of
functional programming, these occur within a class.

13. Which of the following are true? (Choose all that apply)
A. javac compiles a .class file into a .java file.
B. javac compiles a .java file into a .bytecode file.
C. javac compiles a .java file into a .class file.
D. Java takes the name of the class as a parameter.
E. Java takes the name of the .bytecode file as a parameter.
F. Java takes the name of the .class file as a parameter.

C, D. Java puts source code in .java files and bytecode in .class files. It does not use
a
.bytecode file. When running a Java program, you pass just the name of the class
without the
.class extension.

Java SE 8 OCA exam certification preparation

Today I’ve started to prepare for the OCA exam for the Java SE 8 certificate. My goal is to get the certificate. Secondary goals is to find optimal ways of learning and preparing for other certifications. I’ll be using this tools to monitor my progress and enhance the efficiency of learning. Tools:

  1. A4 exercise book.
  2. Pen
  3. Time tracking via TrackingTime application.

I’ll be studying in the library using this book: Boyarsky & Selikoff Oracle Certified Associate Java SE 8 Programmer I Study Guide Exam 1Z0-808

Any time that will be spent for learning Java SE will be tracked. This will allow to calculate my learning speed.

With God’s permission I begin.

Preparations for Java 8 certifications

What to bring:

  1. ID

Topics in the exam:

  1. Java Basics
    Define the scope of variables
    Define the structure of a Java class
    Create executable Java applications with a main method; run a Java program from the command line; including console output.
    Import other Java packages to make them accessible in your code
    Compare and contrast the features and components of Java such as: platform independence, object orientation, encapsulation, etc.
  2. Working With Java Data Types
    Declare and initialize variables (including casting of primitive data types)
    Differentiate between object reference variables and primitive variables
    Know how to read or write to object fields
    Explain an Object’s Lifecycle (creation, “dereference by reassignment” and garbage collection)
    Develop code that uses wrapper classes such as Boolean, Double, and Integer.
  3. Using Operators and Decision Constructs
    Use Java operators; including parentheses to override operator precedence
    Test equality between Strings and other objects using == and equals ()
  4. Create if and if/else and ternary constructs
    Use a switch statement
    Creating and Using Arrays
    Declare, instantiate, initialize and use a one-dimensional array
    Declare, instantiate, initialize and use multi-dimensional array
  5. Using Loop Constructs
    Create and use while loops
    Create and use for loops including the enhanced for loop
    Create and use do/while loops
    Compare loop constructs
    Use break and continue
  6. Working with Methods and Encapsulation
    Create methods with arguments and return values; including overloaded methods
    Apply the static keyword to methods and fields
    Create and overload constructors; including impact on default constructors
    Apply access modifiers
    Apply encapsulation principles to a class
    Determine the effect upon object references and primitive values when they are passed into methods that change the values
  7. Working with Inheritance
    Describe inheritance and its benefits
    Develop code that demonstrates the use of polymorphism; including overriding and object type versus reference type
    Determine when casting is necessary
    Use super and this to access objects and constructors
    Use abstract classes and interfaces
  8. Handling Exceptions
    Differentiate among checked exceptions, unchecked exceptions, and Errors
    Create a try-catch block and determine how exceptions alter normal program flow
    Describe the advantages of Exception handling
    Create and invoke a method that throws an exception
    “Recognize common exception classes (such as NullPointerException, ArithmeticExcpetion, ArrayIndexOutOfBoundsException, ClassCastException)”
  9. Working with Selected classes from the Java API
    Manipulate data using the StringBuilder class and its methods
    Creating and manipulating Strings
    Create and manipulate calendar data using classes from java.time.LocalDateTime, java.time.LocalDate, java.time.LocalTime, java.time.format.DateTimeFormatter, java.time.Period
    Declare and use an ArrayList of a given type
    Write a simple Lambda expression that consumes a Lambda Predicate expression