Java code

My Study Notes for Java SE 7 Programmer I(OCA) Exam

After completing the Java SE 7 Programmer I(OCA) Exam Prep Seminar, I took a self-test online to test my knowledge. Based on my results, particularly the mistakes I made, here are my notes on things you definitely need to know to pass the Java SE 7 Programmer I exam. See my preparation for Java SE 7 Programer I(OCA) exam article for more details on how I prepared.

Firstly, check you understand the assumptions published in the Exam Topics page provided by Oracle.

This page is not intended to teach you Java or enable you to cram for the exam. It makes the assumption you’re already a Java programmer and just need to brush up on a few things you’d normally use documentation for. It’s about having a list of important things to know in the exam.

Note: I accept no liability for any inaccuracy or mistakes in this document. If you find any errors, please let me know so I can correct it!

Java Basics

  • Variable scope
    • Class scope
      • Non-static variables defined in a class are accessible within the class methods without using the class or instance name or “this”.
      • Static variables
    • Method scope
      • Variables declared in the method and arguments of the method are only available within the method.
      • If an argument of the method has the same name as a class variable, the method’s version will be used rather than the class version.
      • If a variable with the same name as a class variable is declared in the method, the method’s version will be used rather than the class version.
    • Block scope
      • A variable declared in a block of code will only be available in that block of code.
      • Variables may be declared anywhere in a block or method but will only be valid after the declaration.
      • Variables declared in a block will be accessible inside a new nested scope under the scope they were declared in.
      • You cannot declare a variable in an inner block scope with the same name as a variable in the outer block scope.
    • Variables are created only when their scope is entered.
    • Variables are destroyed when their scope is left.
  • Class structure
  • Executable applications
    • A Java class is made executable from the command line by creating a main method using the declaration: public static void main(String args[])
      • A main method that returns a value will compile but will produce an error when executed
    • First command line argument is args[0].
  • Import Java packages
    • Import package member using import package.member
    • Import complete package using the wildcard character
    • Java compiler automatically imports the java.lang package and the current package
    • If more than one package you have imported contains the same member name, you must refer to it using the member’s fully qualified name.

Java Data Types

  • Declare and initialise variables
    • Declared using syntax: type identifier
    • Multiple variable of the same type may be declared in the same statement, separating the identifiers with commas.
    • Variables may be declared and initialised on the same line.
    • Multiple variables of the same type may be declared and initialised on the same line, by putting a comma after the value of each variable and then supplying the next identifier.
    • Variables may be dynamically initialised with any valid expression at time of declaration.
  • Object reference variables
    • When instantiating an instance of a class, we declare a reference variable and then allocate a new instance of the class to the reference
    • Class name and arguments specify the constructor to be used
  • Primitive variables
    • 8 Primitive types:
      • byte – 8 bits signed
      • short – 16 bits signed
      • int – 32 bits signed
      • long – 64 bits signed
      • float – 32 bits single precision
      • double – 64 bits double precision
      • char – 16 bits unicode
      • boolean – true or false – not 0 or 1
  • Integer literals:
    • Whole number value is an integer literal, assumed to be decimal
    • Octal values denoted by a leading 0
    • Hexadecimal values denoted by a leading 0x
    • Binary values denoted by leading 0b – beginning with JDK 7
    • No error produced when assigning an integer literal that is within the range of the type
    • To specify a long literal append an L(upper-case or lower-case) to the end of the literal
    • Underscores may be embedded in integer literals
  • Floating-point literals:
    • Default is double precision
    • To specify float, append F to the literal
    • To specify double, append D to the literal
    • Scientific notation uses a floating point number plus suffix indicated by E followed by a decimal number with is the power of 10 to which the number is multiplied.
    • Hexadecimal floating point literals may be used with prefix 0x, but scientific notation then uses P rather than E.
    • Underscores may be embedded in floating-point literals
  • Character literals:
    • Enclosed in single quotes(‘)
  • Read and write object fields
    • Inside the class just use the field name.
    • Outside the class use the instance name, dot operator and field name.
  • Object lifecycle
    • Variables are created when their scope is entered and destroyed when their scope is exited.
    • Objects will be eligible for garbage collection when there is no reference pointing to them.
  • Call object methods
    • Within the class just use the method name.
    • Outside the class use the instance name, dot operator, method name and required arguments.
  • StringBuilder class see tutorial
    • Identical to StringBuffer, is faster, but is not synchronized so is not thread-safe
    • Represents growable and modifiable character sequences
    • Provides utility functions for characters or substrings to be inserted into or appended onto a string.
    • Use append() to add more characters to the string
    • Use charAt() to get the character at a particular index – throws IndexOutOfBounds exception if index is invalid.
    • Use length() to get length of string
    • Use substring(int index) to return all characters from index to end of string or substring(int start, int end) to return characters between start and end inclusive.
  • Strings
    • Strings are immutable – cannot be changed once created
    • A string object is automatically created for every string literal
    • The + operator may be used to concatenate strings
    • To compare two strings use the equals() or equalsIgnoreCase() methods of the String class
    • Use the compareTo() or compareToIgnoreCase() method to compare whether a string comes before or after another string in dictionary order.
    • Use length() to get length of string
    • String methods that return a new String object may be used with the assignment operator to replace the an existing String object.
    • String methods that “modify the string” don’t actually modify the string, but return a modified copy of the String.

Operators and Decision Structures

  • Operators
  • Parentheses
    • Raises the precedence of operations inside them
    • May be used to alter the precedence or clarify the meaning of the expression
  • Object and string equality
    • == determines if the variable references refer to the same object
    • .equals compares the contents of the two objects
  • If/else statements
    • May contain just one statement or a block
    • May be nested, but the if-else-if ladder structure is preferred
  • Switch statements
    • Statements in a switch case must be labeled with one or more case or default labels.
    • break statement branches execution to first statement after switch block
    • break may be omitted from a case in order to have execution fall through to the next case’s statements
    • Prior to JDK 7 only byte, short, int or char expressions may be used in a switch.
    • In JDK 7 and above String may be used.
    • switch is more efficient than if’s, but may only test equality of contents of expression

Arrays

  • One-dimensional arrays
    • Braces may follow the type or the variable name.
    • Array memory must be allocated using the new keyword and size must be specified in braces after the type
  • Multi-dimensional arrays
    • Braces may follow the type or the variable name.
    • When specifying the size of a multi-dimensional array only the first dimension size needs to be specified. The second dimension size may be allocated manually for each index of the first dimension.
    • It is possible to create uneven or irregular multi-dimensional arrays – a triangular multi-dimensional array even!
  • java.util.Arrays has utility static methods for manipulating arrays
  • Arrays are objects and all methods of class Object may be invoked on an array.
  • ArrayList
    • Supports dynamic arrays which can grow when needed.
    • Automatically enlarged when needed.
    • May be shrunk when objects are removed.
    • Declared in form: ArrayList<type> var = new ArrayList<type>()
    • Contents may be returned using default toString() method.
    • Can be converted to an array using toArray() method. Needed for use with an enhanced-for loop.
    • Use get(index) method to access a value.
    • Use add(element) to append to list
    • Use add(index, element) to insert in a list – index must be less than the size() of the ArrayList.
    • Use remove(index) to remove from ArrayList.
    • Use remove(object) to remove the first occurrence of object from the ArrayList.
    • Use clear() to remove all elements from the arraylist.

Loops

  • While loops
    • Only run if controlling expression is true
    • May not run at all if expression is false when execution reaches the loop
    • Does not require a body if the controlling expression can handle all required functionality
  • For loops
    • General form: for(initialisation; condition; iteration)
    • Commas allow multiple initialisation and iteration statements
    • Initialisation and/or iteration statements may be absent
    • All three parts may be empty for an infinite loop
  • Enhanced for loops
    • General form: for(type variable : collection)
    • Iterates through a collection and places the current value in the variable
    • May be used for multi-dimensional arrays using nesting
  • Do/while loops
    • Always runs once, subsequent runs will occur if the controlling expression is true at the end of the first iteration.
    • Decrement/Increment may be included in the controlling expression as a pre-fix decrement/increment preceding the comparison
  • Break and continue
    • break terminates the loop and execution continues with the first statement after the loop
    • continue terminates the current loop iteration and execution continues with the next loop iteration
    • break label breaks out of the named block of code
    • continue label ends the current iteration of the block label and triggers the next iteration to begin
    • break may only be used within a switch block’s case or default labels or in a loop.
    • continue may only be used in a loop.

Methods and Encapsulation

  • Method arguments and return values
    • A method may accept values into variables which are known as parameters
    • A method that accepts parameters is passed arguments(variables or literals) when it is called
    • Void methods do not return values or include a return statement.
    • Non-void methods must return a value via the return statement.
    • The last parameter of a method may be a varargs parameter which may accept an arbitary number of values. The syntax is: type… array_name
  • Static keyword
    • Static variables are essentially global variables
    • Static methods can only directly call other static methods
    • Static methods can only directly access static data
    • Static methods cannot use this or super – it will cause a compilation error
    • Static members can be accessed before an instance of its class is created and without reference to an object.
    • Inside their class static members can be used without specifying the name of the class.
    • Outside their class static members can be used by specifying the class name followed by the dot operator and member name.
  • Overloaded methods
    • Overloaded method use the number and types of arguments to determine which version of the overloaded method to call.
    • Return type are not used to determine which overloaded method to call.
  • Default and user-defined constructors
    • If no user-defined constructors are provided for a class, the compiler will supply a default no argument constructor
  • Create and overload constructors
    • If a class will be inherited, a no argument constructor should be supplied.
  • Access modifiers
    • public
      • Can be accessed by any other code
    • private
      • Can only be accessed by other methods in its class
    • protected
      • Applies only with inheritance
    • default
      • Also known as package-private
      • Accessible from all classes within its package
  • Encapsulation
    • Declare variables of a class private
    • Provide public setter and getter methods
  • Call by reference vs call by value
    • Primitives types are passed by value – the method has a copy of the primitive and can’t change the original variable
    • Object types are passed by reference – the method can change the original object

Inheritance

  • Implementing inheritance
    • Java implements single inheritance
    • On instantiation of a subclass, the no-arg constructor of the superclass will be executed prior to the subclass constructor running
    • Subclass cannot access those members of a superclass that have been declared private
    • Declaring a method as final means it cannot be overriden by a subclass – a compile-time error will occur
    • Declaring a class as final means it cannot be inherited.
      • A class cannot be abstract and final
  • Polymorphism
    • Subclasses of a class can implement their own unique behaviour but share common functionality with the superclass
    • Achieved by overriding superclass methods to provide unique behaviour in the subclass, while also adding additional unique methods specific to the subclass
  • Reference type vs object type
    • A reference variable may be declared to be of a type that is a superclass of the actual object type
    • Reference type determines which members of the object are accessible
    • Only those members declared in the reference type will be accessible, so some members of actual object type may not be accessible
  • Casting
    • Where a superclass has been used as reference type, the object may be cast to the actual type to access members that are not part of the reference type
  • Super
    • May be used to call the constructor of a superclass – the signature will determine which constructor
    • May be used to refer to a method or instance variable in the superclass
  • This
    • this is a reference to the current object
    • this() can be used to invoke an overloaded constructor
    • this may be used to refer to a redefined instance member variable from a method.
  • Interfaces
    • An interface is a a reference type, like a class, that can only contain constants, method signatures, default methods, static methods and nested types.
    • Cannot be initialised
    • Are designed to be implemented by classes or extended by other interfaces
    • A class based on the interface uses the implements keyword to declare this.
  • Abstract classes and interfaces
    • Abstract classes cannot be initialised
    • Abstract classes are able to be subclassed, with subclasses inheriting the methods provide by the abstract class
    • An abstract class may implement an interface

Exceptions