Java Basics: Variable Scope
Java Basics: Variable Scope
Java Basics: Variable Scope
Variable scope
o 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
o 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.
o 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.
o Variables are created only when their scope is entered.
o Variables are destroyed when their scope is left.
Class structure
o Static members belong to class, not instance
Can be used to keep track of how many instances of a class have been
created
o Constants declared with “static final” modifiers
Cannot be reassigned, compile-time error will occur
o Access level modifiers
public
world accessible
protected
subclass and package accessible
package-private
default for no modifier
package accessible
private
only accessible within class
Executable applications
o 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
o First command line argument is args[0].
Import Java packages
o Import package member using import package.member
o Import complete package using the wildcard character
o Java compiler automatically imports the java.lang package and the current
package
o 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.
Arrays
One-dimensional arrays
o Braces may follow the type or the variable name.
o Array memory must be allocated using the new keyword and size must be
specified in braces after the type
Multi-dimensional arrays
o Braces may follow the type or the variable name.
o 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.
o 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
o Supports dynamic arrays which can grow when needed.
o Automatically enlarged when needed.
o May be shrunk when objects are removed.
o Declared in form: ArrayList<type> var = new ArrayList<type>()
o Contents may be returned using default toString() method.
o Can be converted to an array using toArray() method. Needed for use with an
enhanced-for loop.
o Use get(index) method to access a value.
o Use add(element) to append to list
o Use add(index, element) to insert in a list – index must be less than the size() of
the ArrayList.
o Use remove(index) to remove from ArrayList.
o Use remove(object) to remove the first occurrence of object from the ArrayList.
o Use clear() to remove all elements from the arraylist.
Loops
While loops
o Only run if controlling expression is true
o May not run at all if expression is false when execution reaches the loop
o Does not require a body if the controlling expression can handle all required
functionality
For loops
o General form: for(initialisation; condition; iteration)
o Commas allow multiple initialisation and iteration statements
o Initialisation and/or iteration statements may be absent
o All three parts may be empty for an infinite loop
Enhanced for loops
o General form: for(type variable : collection)
o Iterates through a collection and places the current value in the variable
o May be used for multi-dimensional arrays using nesting
Do/while loops
o Always runs once, subsequent runs will occur if the controlling expression is true
at the end of the first iteration.
o Decrement/Increment may be included in the controlling expression as a pre-fix
decrement/increment preceding the comparison
Break and continue
o break terminates the loop and execution continues with the first statement after
the loop
o continue terminates the current loop iteration and execution continues with the
next loop iteration
o break label breaks out of the named block of code
o continue label ends the current iteration of the block label and triggers the next
iteration to begin
o break may only be used within a switch block’s case or default labels or in a loop.
o continue may only be used in a loop.
Inheritance
Implementing inheritance
o Java implements single inheritance
o On instantiation of a subclass, the no-arg constructor of the superclass will be
executed prior to the subclass constructor running
o Subclass cannot access those members of a superclass that have been declared
private
o Declaring a method as final means it cannot be overriden by a subclass – a
compile-time error will occur
o Declaring a class as final means it cannot be inherited.
A class cannot be abstract and final
Polymorphism
o Subclasses of a class can implement their own unique behaviour but
share common functionality with the superclass
o 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
o A reference variable may be declared to be of a type that is a superclass of the
actual object type
o Reference type determines which members of the object are accessible
o Only those members declared in the reference type will be accessible, so some
members of actual object type may not be accessible
Casting
o 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
o May be used to call the constructor of a superclass – the signature will determine
which constructor
o May be used to refer to a method or instance variable in the superclass
This
o this is a reference to the current object
o this() can be used to invoke an overloaded constructor
o this may be used to refer to a redefined instance member variable from a method.
Interfaces
o An interface is a a reference type, like a class, that can only contain constants,
method signatures, default methods, static methods and nested types.
o Cannot be initialised
o Are designed to be implemented by classes or extended by other interfaces
o A class based on the interface uses the implements keyword to declare this.
Abstract classes and interfaces
o Abstract classes cannot be initialised
o Abstract classes are able to be subclassed, with subclasses inheriting the methods
provide by the abstract class
o An abstract class may implement an interface
Exceptions
Checked exceptions
All exceptions and errors are subclasses of Throwable.
o Throwable defines a method getMessage() which returns a string with details
of the exception or error
o Throwable defines a method printStackTrace() which prints a stack trace of the
exception or error to the console.
Exceptions other than subclasses of RuntimeException, Error
o RuntimeExceptions
Subclasses of RuntimeException are unchecked by the compiler
Common RuntimeException subclasses:
ArithmeticException
IndexOutOfBoundsException
IllegalArgumentException
NoSuchElementException
NullPointerException
o Errors
Subclasses of Error are unchecked by the compiler
Not expected to be caught under normal circumstances by your program.
Indicates errors with the run-time environment
Created in response to catastrophic failures that cannot be handled by your
program
Common Error subclasses:
IOError
o Common checked exceptions:
IOException
Try-catch blocks
o Try
Encloses a block of code that might throw an exception
o Catch
Catch blocks must catch exception subclasses before any of their
superclasses.
Subclass catch blocks would not be reached if superclass catch
blocks came first. Unreachable code in Java causes a compile
error.
Multiple exceptions can be handled by the same catch block by using the
pipe operator |
Execution never returns to the try block
o Finally
Code in the finally block is always executed after the try block completes
Uses of exceptions
o Definition: An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program’s instructions.
o When an exception is thrown the runtime system searches down the call stack
looking for an appropriate handler.
Using a method that throws an exception
o Must catch or re-throw the exception
o Common exception classes and categories
o A method that can cause an exception it doesn’t handle must declare it in the
method definition using the throws clause.