Java Tips
Object-Oriented Programming
- No explicit cast needed for upcasting, but explicit cast needed for downcasting.
- Defining your class as implementing an interface marks objects of that class as an instance of that interface.
- An abstract method cannot (obviously) be final.
- An abstract method cannot be static because static methods cannot be overridden.
- An instance method can be both protected and abstract. A static method can be protected.
- Before Java runtime clones an object, it checks to see if the object’s class implements the Cloneable interface. If it does, the clone() method returns a clone of the object. If not, the clone() method throws a CloneNotSupportedException.
- The clone method is protected, so an object can only request a clone of another object which is either in the same package or which it inherits from. (i.e. standard meaning of protected)
- The JVM does not call an object’s constructor when you clone the object.
- Classes can be modified from their default state using any of the three keywords: public, abstract, and final. So, can’t have a static class, only static methods.
- A final variable is a constant, and a final method cannot be overridden.
- A synchronised method can belong to an object or to a class.
- Only one public class per file.
- package statement must come first in file and must be followed by any import statements.
- An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. Java letters include _ and $. Digits include 0..9.
- The JVM does not call an object’s constructor when an object is cloned.
- Constructors never return a value. If you do specify a return value, the JVM will interpret your intended constructor as a method.
- If a class contains no constructor declarations, then a default constructor that takes no arguments is supplied. This default constructor invokes the no-args superclass constructor, i.e. calls super();
- If, in a constructor, you do not make a direct call to super or this (with or without args) [note: must be on the first line] then super(no args) will first be invoked then any code in the constructor will be executed. See constructors.jpr project.
- A call to this in a constructor must also be on the first line. Note: can’t have an explicit call to super followed by a call to this in a constructor - only one direct call to another constructor is allowed.
- As soon as you lose the reference to an object, that object becomes eligible for garbage collection.
- Setting your object reference to null makes it a candidate for garbage collection.
- You can directly invoke the garbage collector by getting an object which represents the current runtime and invoking that object’s gc() method (see p.95 of Exam Guide).
- Can’t predict when garbage collection will occur, but it does run whenever memory gets low.
- If you want to perform some task when your object is about to be garbage collected, you can override the java.lang.Object method called finalize(). This method is declared as protected, does not return a value, and throws a Throwable object, i.e. protected void finalize() throws Throwable.
- Always invoke the superclass’s finalize() method if you override finalize().
- The JVM only invokes finalize() once per object. Since this is the case, do not resurrect an object in finalize as when the object is finalized again its finalize() method will not be called. Instead you should create a clone of the object if you must bring the object back to life.
- Remember that Java passes method parameters by value and not by reference. Obviously then, anything that happens to a primitive data type inside a method does not affect the original value in the calling code. Also, any reassignment of object references inside a method has no effect on the objects passed in.
- Ranges for primitive data types are as follows:-
| Data Type | Range of Values | |
| byte | | |
| short | | |
| int | | |
| long | | |
| float | | |
| double | | |
| char | | |
| boolean | | |
- To specify an octal (base 8) number, put a leading ‘0’ in front of i
- To specify a hexadecimal (base 16) number, put a leading ‘0x’ in front of it.
- By default, integer values are of type int. However, you can force an integer value to be a long by placing an ‘L’ after it.
- By default, floating point values are of type double. However, you can force a floating-point value to be a float by placing an ‘F’ after it.
- Java sets each element in an array to its default value when it is created. Default object value is null, default integer value is 0, default boolean value is false, default floating point value is 0.0, default char value is ‘\u0000’.
- Arrays are objects allocated at runtime, so you can use a variable to set their length.
- First element in an array is at index 0 and last element is at length-1. length is a special array variable (not a method, so don’t need round brackets after it).
- Can only use curly braces in array initialisation when array is actually declared, i.e. can’t declare the array on one line then initialise it with curly braces on line below.
- ASCII characters are all found in the range ‘\u0000’ to ‘\u00ff’
- The default value for any class variable or instance variable declared as a char is ‘\u0000’.
Operators
- >> is right shift keep the sign, >>> is right shift don’t keep the sign.
- & and | can be used with both integral and boolean types. If used with integers the result is integral. If used with booleans, both operands are evaluated, even when the result of the operation can be determined after evaluating only the left operand.
- && and || are used with boolean operands only. The right operand is not evaluated if the result of the operation can be determined after evaluating only the left operand.
- The equals() method (defined at the ‘highest’ level as a method of Object) is used to test the value of an object. The == operator is used to test the object references themselves.
- By default, equals() returns true only if the objects reside in the same memory location, i.e. if the object references are equal. So, by default, equals() and == do the same things. This will be the case for all classes that do not override equals().
- String, Wrappers (including Integer, Long, Float, Double, Character and Boolean), BitSet, Date and File classes all override equals() so that the value true is returned if the values are equal.
- The + and += operators are overloaded for Strings.
- Dividing an integer by 0 is illegal and would cause Java to throw an ArithmeticException. Floating point numbers have values for infinity and not-a-number, so using arithmetic operators on floating point numbers never results in an exception.
Control Flow
- A loop counter is usually an integer, however it could also be a floating point number - incrementing by 1.0
- Breaking to a label means that the loop at the label is terminated. Any outer loop will keep iterating.
- In contrast, a continue to a label continues execution with the next iteration of the labelled loop.
- The expression for an if and while statement must be a Boolean.
- The expression in a switch statement must be an int or a char.
- A default statement in a switch is optional.
- A case block will fall through to the case block which follows it, unless the last statement in a case block is a throw, return or break.
- As with if statements, for and while loops, it is possible to nest switch statements.
- Any line of code can be labelled BUT can only do a labelled continue to a loop, and can only do a labelled break to a loop or to an enclosing statement.
Exceptions
- It is possible to have multiple catch blocks in a try-catch-finally. The finally block is optional.
- A catch block must always be associated with a try block, i.e. can’t have a catch block by itself or with a finally block.
- A finally block must always be associated with a try block, i.e. can’t have a finally block by itself or with a finally block.
- With multiple catch blocks, the type of exception caught must progress from the most specific exception that you wish to catch to the superclasses for these exceptions. (Makes sense!)
- Methods must declare any exception which they throw.
- Invoking a method which declares it throws exceptions is not possible unless either the code is placed in a try-catch, or the calling method declares that it throws the exceptions, i.e. checked exceptions must be caught or rethrown. If the try-catch approach is used, then the try-catch must cope with all of the exceptions which a method declares it throws.
- You can list more than one exception in the throws clause if you separate them with commas.
- RuntimeException and its subclasses are unchecked exceptions.
- Unchecked exceptions do not have to be caught.
- All Errors are unchecked.
- You should never throw an unchecked exception in your own code, even though the code will compile.
- You cannot use a try block on its own. It must be accompanied by a following catch or finally (or both).
- Code in a finally block will always be executed, whether an exception is thrown or not and whether any exception thrown is caught or not. Only terminating the program will stop the finally code from being executed.
- A method can only throw those exceptions listed in its throws clause, or subclasses of those exceptions.
- A method can throw any unchecked exception, even if it is not declared in its throws clause.
- When you override a method, you must list those exceptions that the override code might throw. You can list only those exceptions, or subclasses of those exceptions, that are defined in the method definition you are inheriting from, i.e. you cannot add new exception types to those you inherit. You can choose to throw a subset of those exceptions listed in the method’s superclass, however, a subclass further down the hierarchy cannot then re-list the exceptions dropped above it.
Methods
- If you define more than one method with the same name in the same class, Java must be able to determine which method to invoke based on the number and types of parameters defined for that method.
- The compiler will complain if you have two methods with identical signatures exception for the return type and/or the exceptions thrown, i.e. can’t overload based on return type and/or exceptions thrown.
- Determining which methods will be invoked with integer params - see p.195 of the Exam Guide.
- It is possible to declare an inherited method abstract.
- Obviously, it is not possible to override a final method.
- A subclass may make an inherited method synchronized, or it may leave off the synchronized keyword so that its version is not synchronized. If a method in a subclass is not synchronized but the method in the superclass is, the thread obtains the monitor for the object when it enters the superclass’s method.
- It is possible to declare an inherited method as abstract, but then there is no way to get to the behaviour in the hierarchy above the abstract declaration.
- Return types must match the overriden method in the superclass exactly. The parameter types must match those in the superclass exactly, i.e. in the same order. If this is not the case, then the superclass’s method is not overridden. Compiler will not complain, however, unless exactly the same signature except for return type (or exceptions thrown - see earlier).
- You cannot make a method in a subclass more private than it is defined in the superclass, ‘though you can make it more public.
- Coercion of arguments only happens with overloading, not overriding.
- It is perfectly legal to have two different instance variables with the same name if they are defined in different classes where one class inherits from the other.
- Which variable is accessed depends on the type of object reference which the variable was declared to hold. Which method gets invoked depends on the underlying object. See p.106 Q1 & p.201 of Exam Guide.
- A native method does not have a body, or even a set of braces, e.g. public native void method();
- A native method cannot be abstract.
- A native method can throw exceptions.
Math and String Classes
- ceil() returns the next highest integer (expressed as a double)
| Method call | Returns |
| ceil(9.01) | |
| ceil(-0.1) | |
| ceil(100) | |
- round() returns the closest integer (expressed as an int if the parameter was a float, or a long if the parameter was a double)
| Method call | Returns |
| round(9.01) | |
| round(9.5) | |
| round(-9.5) | |
| round(-0.1) | |
| round(100) | |
- random() returns a random number, a double, between 0.0 and 1.0
- sqrt() takes a double and returns a double. If the argument is NaN or <0,>
- sin(), cos() and tan() all take a double and return a double.
- All objects respond to toString(), which you can override to return a String representation of your object.
- String objects have the following methods: length(), toUpperCase(), toLowerCase(), equals(), equalsIgnoreCase(), charAt(), indexOf(), lastIndexOf(), substring(), toString() and trim().
- There are four versions of indexOf()
| Arguments | Results |
| (int ch) - works if you put a char in! | Finds the first occurrence of this character |
| (int ch, int fromIndex) | Finds the first occurrence of this character starting from fromIndex |
| (String substring) | Finds the start of this substring |
| (String substring, int fromIndex) | Finds the start of this substring searching from fromIndex |
- There are four versions lastIndexOf() - as above table but, in each method, finding the last index rather than the first index.
- First character in a String is at position 0, last character is at position length()-1
- There are two versions of substring()
| Arguments | Results |
| (int startIndex) | Returns a substring starting with startIndex and extending to the end of the String |
| (int startIndex, int endIndex) | Returns a substring starting with startIndex and extending to (but not including) endIndex |
- For a StrintoString() returns itself - the same object reference (obviously pointing to the same object) that was used to invoke the method.
- trim() returns a new String object that cuts off any leading and trailing whitespace for the String for which it was invoked.
- Java considers "whitespace" to be any character with a code less than or equal to ‘\u0020’ which is the space character.
No comments:
Post a Comment