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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s