Java OCAJP

By Mikhail Niedre

Exam Topics

Java Basics

Define the scope of variables

Variables

Variables

The Java programming language defines the following kinds of variables:

Instance Variables

Instance Variables

public class InstanceVariables {	
	private int i;	
	public void print() { System.out.println(i); }
	public static void main(String[] args) {
		new InstanceVariables().print(); // 0
	}
}

Class Variables

Constants

class Employee{
   // DEPARTMENT is a constant
   public static final String DEPARTMENT = "Development";
}

Local Variables

public int wrongLocalInit(int p) {
    int i; // right way: // int i = 0;
    if (p < 5)
        i += 5; // The local variable i may not have been initialized
    return i;
}

Method Parameters

Define the scope of variables

Define the scope of variables

Define the structure of a Java class

Define the structure of a Java class

Define the structure of a Java class

Box obj; //объявление ссылки на объект
// obj = null;
obj = new Box(); // резервирование памяти для объекта
// и присвоение переменной obj ссылки на этот объект
// Box() - конструктор класса Box

Create executable Java applications with a main method

Import other Java packages to make them accessible in your code

Working With Java Data Types

Working With Java Data Types

Declaring a Variable

public static void main(String[] argv) {
    int a, b, c; // declares three ints, a, b, and c.
    int d = 3, e, f = 5; // declares three more ints, initializing d and f.
    byte z = 2; // initializes z.
    double pi = 3.14; // declares an approximation of pi.
    char x = 'x'; // the variable x has the value 'x'.
}

Using Operators and Decision Constructs

Arrays

Arrays

Declare, instantiate, initialize and use:

One-dimensional arrays

Multi-dimensional arrays

ArrayList

ArrayList

List arr = ArrayList();
arr.size();
arr.contains(100);
arr.remove("asd");

Using Loop Constructs

Working with Methods and Encapsulation

Methods and Encapsulation

Create methods

static keyword (for methods and fields)

Method overloading

Method overloading

Constructors

Constructor overloading

Access modifiers

Encapsulation principles

Pass by Value

Working with Inheritance

Use abstract classes and interfaces

Use abstract classes and interfaces

Use abstract classes and interfaces

interface Shape {
	void Draw(); // public by default
}
class Circle implements Shape {
	void Draw() {// Error: by default method not public 
// Cannot reduce the visibility of the inherited method from Shape
		System.out.println("Drawing Circle here");
	}
}

Use abstract classes and interfaces

public interface CarConstants {

      static final String ENGINE = "mechanical"; // public by default
      static public final String WHEEL  = "round";
      
}

Use abstract classes and interfaces

interface IBox {
	public void setSize(int size);
}
public class Rectangle implements IBox {
	private int size;
	public void setSize(int size) { this.size = size; }
	public static void main(String[] args) {
        // myBox contains the methods/fields ONLY from IBox
		IBox myBox = new Rectangle(); myBox.setSize(10);
	}
}

Use abstract classes and interfaces

Use abstract classes and interfaces

Handling Exceptions

Exceptions

Differentiate among checked exceptions, RuntimeExceptions and Errors

Create a try-catch block and determine how exceptions alter normal program flow

Describe what exceptions are used for in Java

Invoke a method that throws an exception

Конструкция throws перечисляет типы исключений, которые метод может передавать.

import java.io.IOException;
import java.text.ParseException;

public class ThrowsExceptionExample {
	public static void main(String[] args) throws IOException, 
		ParseException {
	}
}

Любое исключение, которое создается и передается внутри метода, должно быть указано в его описании после ключевого слова throws.

public class ThrowExceptionExample {
	public static void main(String[] args) {
		//throw new Exception(); // Error: Unhandled exception type Exception
	}
}

Исключение может быть объявлено в описании функции, но не вызываться в ее теле.

public class AccountExceptionExample {
	public void withdraw() throws Exception {
		// no errors
	}
	public static void main(String[] args) 
		throws Exception {
		new AccountExceptionExample().withdraw();
	}
}

Recognize common exception classes and categories

Examples

Declaring a Variables

The Java programming language defines the following kinds of variables:

public class Variables {
	private int instance_var = 1; //instance variable
	public static int CLASS_VAR = 2; //class variable
	public void method(String[] parameters) { //parameter
		int local_var = 3; //local variable
	}
}

Variables

A local variable shadows an instance variable.

class TwoScopes {
	int a = 10;
	public TwoScopes() {
		int a = 5; // hiding (shadowing)
		System.out.println(a); // 5
		System.out.println(this.a); // 10
	}
}
public class TwoScopesExamples {
	public static void main(String[] args) {
		new TwoScopes();
	}
}

Variables

Instance variable shadows the inherited variable from it's parent classes.

class Base {
	public String greeting = "Hello";
}
class Sub extends Base {
	public String greeting = "Good Bye"; // hiding the inherited version
	public String getGreeting() { return greeting; }
}
public class VariableOverridingTest {
	public static void main(String[] args) {
		Base obj = new Sub(); System.out.println(obj.greeting); // "Hello"
		obj.greeting = "How are you";
		System.out.println(obj.greeting); // "How are you"
		System.out.println(obj.getGreeting()); // "Good Bye"
	}
}

Arrays

An array is a container object that holds a fixed number of values of a single type

// declares an array of integers
int[] anArray;
// this form is discouraged
float anArrayOfFloats[];

// will be created an eleven objects
String[] s = new String[10];

Arrays

The length of an array is established when the array is created. After creation, its length is fixed.

// allocates memory for 10 integers
int[] anArray = new int[10];
// Note that arrays have a length 
// field not a length() method.
for(int j = 0; j < anArray.length; j++) {
	anArray[j] = j;
}

Arrays

Each element in an array is accessed by its numerical index.

int i = 0;
long j = 0;
String s[] = { "a", "b", "c", "d" }
String c1[] = s[i]; // ok
String c2[] = s[j]; // compile error!

Data types default values

Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false

Hiding & Overriding

class Base {
	public String greeting = "Hello";
	public String getGreeting() { return greeting; }
}

class Sub extends Base {
    // greeting (Base)
	public String greeting = "Good Bye"; // greeting (Sub)
	@Override
	public String getGreeting() { return greeting; 
	// return super.greeting; // hidded
	}
}

public class VariableOverridingTest {
	public static void main(String[] args) {
		Base obj1 = new Base();
		Base obj2 = new Sub();
		System.out.println(obj1.getGreeting()); // "Hello"
		System.out.println(obj2.getGreeting()); // "Good Bye"
	}
}

Method overloading

If a few methods of an one class have the same name but signatures that are not override-equivalent, then the method name is said to be overloaded.

public class Shape {	
	/** display Square area */
	static void displayArea(int a) {
		System.out.println(a*a);
	}
	/** display Triangle area */
	static void displayArea(int b, int h) {
		System.out.println((b*h)/2);
	}	 
	public static void main(String[] args) {
		int a = 3, b = 4, c = 5;
		displayArea(a);
		displayArea(b, c);
	}
}

Method overloading

Method overloading is one of the ways that Java implements polymorphism.

public class OverloadingExample {
	public static void print(Object foo) {
		System.out.println("Object");
	}
	public static void print(Integer foo) {
		System.out.println("Integer");
	}
	public static void main(String[] args) {
		Object foo = new Integer(42);
		print(foo);
		Object bar = new Object();
		print(bar);
	}
}

Method overloading

When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call.

public class OverloadingExample {
	public static void main(String[] args) {
		print("asd");
		print(10);
	}
	public static void print(int i) {
		System.out.println("int: " + i);
	}	
	public static void print(String s) {
		System.out.println("String: " + s);
	}
}

Method overloading

You can have two methods with the same arguments and different return types only if one of the methods is inherited and the return types are compatible.

class A { 
    Object foo() { System.out.println("A.foo()");
        return new Object(); 
    } 
}
class B extends A { 
    String foo() { System.out.println("B.foo()");
        return new String(); 
    } 
}
public class OverloadingExample2 {
	public static void main(String[] args) {
		Object foo1 = new A().foo();
		Object foo2 = new B().foo();
	}
}

Method overloading

A difference in return type only is not sufficient to constitute an overload and is illegal.

public class OverloadingExample3 {
	private static int sum = 0;
	public static void main(String[] args) {
		System.out.println(sum(1,2));
	}	
	public static int sum(int i, int j) { 
        return (i + j); 
    }
	public static void sum(int i, int j) { 
        sum = i + j; 
    }	
}

Method overloading

Overloaded methods may call one another simply by providing a normal method call with an appropriately formed argument list.

public class OverloadingExample7 {
	public static void main(String[] args) {
		Object a = "asd"; print(a);
		a = 12; print(a);
	}
	public static void print(Object o) {
		if (o instanceof String) print((String) o);
		if (o instanceof Integer) print((Integer) o);
	}	
	private static void print(String s) {
		System.out.println("String: " + s);
	}	
	private static void print(Integer i) {
		System.out.println("Integer: " + i);
	}
}