Java
Exam Notes
This page contains notes generated while studying
for the exam. The idea (at the time) was to note all the issues which appeared
to crop up in various mock exams which caused me to doubt my understanding
of Java. It also acted as a list of review topics and "things I must remember".
The following are in no particular order.
Collection Framework
Set cannot contain duplicate elements
List is an ordered collection
Map maps keys to values – duplicate keys not allowed.
new Vector(x, y) ---- x = init capacity,
y = capacity increment
Inner Classes:
Inner classes (not defined in a method) have access
to all class and instance variables, regardless of access qualifier
(ie, it works for private, static, protected, etc).
Inner classes defined inside a method, have access to all class
variables regardless of access qualifier. However, access to method parameters
and method local variables is possible only if they are declared as final.
Variables inside inner classes cannot be static unless the inner class
itself is static.
Inner classes can be declared as private, normal classes cannot.
The inner class can actually inherit from the outer class.
Class Hierarchies
Sibling classes cannot be assigned to each other, even with
an explicit cast. This will cause a compile error.
For example…
class Parent{}
class Derived1 extends Parent{}
class Derived2 extends Parent
{}
Parent p = new Parent();
Derived1 d1 = new Derived1();
Derived2 d2 = new Derived2()
d1 = d2;
Casting down a hierarchy is possible with an explicit cast
(it will compile). However, a ClassCastException will be thrown at run-time
(RuntimeException subclass – not catchable!)
For example…
d1 = (Derived1) p;
The following will compile:
public class TestApplication
{
public static void main
(String args[]){
CellPhone c = new CellPhone();
c.emergency();
}
}
class Phone{
final void dial911(){}
}
class CellPhone extends Phone{
void emergency(){
dial911();
}
}
In other words, CellPhone has direct access to the non-private methods
(final or otherwise) in the parent class (here dial911()).
An abstract method can’t be declared as static.
When declaring a method abstract, there is no {} (eg, abstract void
Test();)
Creating Arrays
The following are valid array declarations…
int []a[] = new int[10][10];
int a[][] = new int [10][10];
int []a = {1,2,3};
The following are NOT valid:
int a[10][10] = new
int [][];
int [3] a = {1,2,3};
Wrapper Classes
Wrapper Classes (Integer, Boolean, Character, etc) are final
and can’t be subclassed.
String and StringBuffer are also final.
Threads
Wait(), notify() and notifyAll() are defined in the Object
class.
These can only be called from synchronised code.
The following will stop a thread from executing:
-
sleep()
-
yield()
-
stop()
-
wait()
The following won’t stop a thread:
wait() returns InterruptedException (needs to be in a try block).
yield() and sleep() are static (can be called by Thread.sleep()).
Exceptions
When an exception is thrown, the finally clause is executed.
Any code outside the try clause is not executed.
A try block always needs a catch or a finally block (either one, but
not none).
If an exception is caught in a catch block, it is considered handled,
and execution continues after the try block.
Interfaces
Interfaces don’t have constructors – can’t instantiated an
interface.
The "this" keyword cannot be used without a corresponding instance
of an object.
It is possible to call other constructors or a class by simply using
"this(xxx)" (where xxx is the arg constructor in question):
For example:
class aClass{
aClass(){}
aClass(int a) {}
aClass(String s, int a){
this(a);
}
}
Here, "this(a)" calls the aClass(int a) constructor. Similarly, calling
"this()" will call the default constructor. The same applies to "super(xxx)"
when calling parent constructors.
The instanceof operator will cause a compile time error if
the compiler can prove that the check is meaningless (ie, there is no inheritence).
If the instanceof operator refers to an interface, it returns true if
the interface is implemented.
The key word is "instanceof", not "instanceOf"
Printing a String as follows, will simply print out the letters
"null" (ie, if the string is not assigned a value):
String s;
System.out.println(s);
Access qualifiers can appear in any order.
public static void main(String
[] args)
is the same as
static public …..
The following will print out the 4 char string "true":
boolean b = true;
System.out.println(b);
Strings
All methods for String use indexes from zero.
String s = "abcdecfghi";
System.out.println(s.charAt(4));
displays "e"
However,
String s = "abcdecfghi";
System.out.println(s.substring(2,4));
displays "cd"
The following compiles and displays "eddie"
if ("abcdecfghi".startsWith("abc"))
System.out.println("eddie");
String does not have an append() method.
StringBuffer does.
None of the String methods work with StringBuffers (so s.concat(StringBuffer)
will cause a compile error)
However,
1. String s = "abcde";
2. StringBuffer s1 = new StringBuffer("abcde");
3. if (s.equals(s1))
4. s1 = null;
5. if (s1.equals(s))
6. s = null;
Line 4 won’t execute because String.equals() will return true if and only
if the argument is not null and is a String object that represents the
same sequence of characters as this object.
Line 6 won’t execute because StringBuffer doesn’t override equals()
(ie, for any reference values x and y, this method returns true if and
only if x and y refer to the same object (x==y has the value true)).
The following compiles:
float f = 412; //promotes
int to float automatically - OK
The following doesn’t compile:
float f = 412.0; //412.0
is a double -> no auto demotion to float
The following displays….
double d1 = -0.5;
System.out.println("Ceil d1 =
" + Math.ceil(d1));
System.out.println("floor d1
= " + Math.floor(d1));
Ceil d1 = -0.0
floor d1 = -1.0
ie, 0.0 is treated different from –0.0.
Boolean b = new Boolean("true");
Allocates a Boolean object representing the value true
if the string argument is not null and is equal, ignoring case,
to the string "true". Otherwise, allocate a Boolean object representing
the value false.
ceil() and floor() return doubles
round() returns integers (int for float, long for double)
ceil() and round() go higher (round(-4.5) = -4)
floor() goes lower.
&, | and ^ will work with booleans
Constructors
A call is automatically inserted in a derived class constructor,
to call the default (no-args) base class constructor. Therefore in a hierarchy,
an explicit default constructor must be present in the next highest class
(see Bruce Eckels "Thinking in Java" page 224).
However, if an explicit call is make to super(..) (ie, a parent constructor),
then the implied call to the default constructor is not needed (and a no-args
default constructor in the parent is not required).
Constructors can’t be final, native, static, synchronised or abstract.
The class hierarchy is called from the base class down.
GUI Components
When placing components in Layout Managers, the following applies:
Stretchable: Button, Label, TextField
Non-Stretchable : Checkbox
Container Default Layout Manager
Frame = BorderLayout
Applet = FlowLayout
Panel = FlowLayout
Dialog = BorderLayout
Window = BorderLayout
Strings
CASE 1
String s1 = "abcd";
String s2 = "abcd";
if (s1==s2)
System.out.println("s1==s2");
//this
prints
if (s1.equals(s2))
System.out.println("s1.equals(s2)");
//this
prints
CASE 2
String s1 = new String("abcd");
String s2 = "abcd";
if (s1==s2)
System.out.println("s1==s2");
//
Doesn’t print
if (s1.equals(s2))
System.out.println("s1.equals(s2)");
//this
prints
CASE 3
String s1 = new String("abcd");
String s2 = new String("abcd");
if (s1==s2)
System.out.println("s1==s2");
//Doesn’t
print
if (s1.equals(s2))
System.out.println("s1.equals(s2)");
//this
prints
The following will generate a compile error…
StringBuffer s1 = "abcd";
All the Number classes (Integer, Boolean, etc) override equals();
StringBuffer does NOT override the equals() method,
so it will do a "shallow" compare (ie, compares object references).
String s1 = "aaa";
s1.concat("bbb");
System.out.println(s1);
This prints out "aaa", since strings are immutable and s1 is
always s1.
Also,
String s = new String("abcdefgh");
s.replace('d', 'q');
System.out.println(s);
displays "abcdefgh", for the same reasons.
Consider the following:
File Tree.java
public class Tree{
protected age;
}
File Forest.java
public class Forest{
public static void main(String
[] args){
Tree t = new Tree();
System.out.println("Age = " t.age);
}
}
This will compile. Both classes are in the default package,
and so have access to all non-private members.
Consider the following:
class Acc{
public static void main(String
[] args){
First s = new Second();
System.out.println(s.var);
System.out.println(s.method);
}
}
class First{
int var = 1;
int method(){ return var;}
}
class Second extends First{
int var = 2;
int method(){return var;}
}
The type of object reference determines the variable, the type of underlying
object determines the method.
The above displays:
1
2
The signature for the finalize() method is:
protected void finalize()
throws Throwable
String s = "abc";
int x = 3;
String s2;
s2 = s1 + x;
This will compile fine, and give s2 = "abc3";
NOTES From Roberts/Heller
Chapters 1 and 2
Valid variables start with LETTER, $ or _.
~ (bitwise invert) only works on integers (not "char")
* and / works on "char" type (but result is promoted to int)
all comparisons with NaN return FALSE;
Modulo and Reduction of Right-hand Operator
With binary operators (+, -, *, /, >>, <<, >>>, etc) the operands
are promoted to "int" (see page 47)
It is legal to compare different types (eg float and char), but not
legal to assign.
The line "a = x ? b : c" is "if (x), a = b, else a =c"
The second part of a && or || operation may not be executed
(short-circuit logical operators)
System.out.println((x > 3) ? 99.00: 9) will display "9.0" [ x gets promoted
to float for comparison]
Consider the following:
String val = null;
int x = Integer.parseVal(val);
This will throw a NullPointerException in the parseInt() method.
Chapter 3
The decreasing levels of privacy are: PRIVATE -> FRIENDLY ->
PROTECTED -> PUBLIC
If an object reference is final, the reference can’t change, but the
object can.
A class that has an abstract method must be declared abstract.
It is best to use the class name to access a static member (see page
82).
Static initialiser code is executed in the order it appears.
A class can not be declared as private or protected.
Chapter 4
interface members (variables or methods) are public (can’t be declared
as static, protected, private, final, synchronised).
It is legal to cast an interface to a class.
Important – see Q8 page 121 – casting down the tree but the object reference
OK!
Class->Interface conversion is OK
Interface->Class conversion is NOT OK (needs an explicit cast, then
a ClassCastException will be thrown).
Chapter 5
break statements cause the loop in question to terminate completely.
continue causes the loop in question to cease the current iteration
(flow restarts at the bottom of the loop)
All exceptions are subclasses of the class java.lang.Throwable
The finally clause is always executed (even if there is no exception).
Checked Exceptions must be declared in the method declaration
or caught in a catch block. RuntimeException and Error are unchecked exceptions,
and don’t have to be declared (but can be caught).
Examples of unchecked exceptions – ArithmeticException, NullPointerException,
NumberFormatException
main() can declare thrown exceptions in its declaration
A method which is overridden can only throw exceptions declared in the
parent, or any subclass of exception declared in the parent. You can’t
add in new exceptions.
Chapter 6
Overloaded methods use the method name and parameter list (the
return type is not relevant/used by the compiler to distinguish overloaded
methods).
Over-riding methods must have the exact signature (name, parameter list,
return type).
See Q7 page 186. Important in relation to subclassing constructors (if
there is no explicit call to the default constructor, the compiler implicitly
inserts one).
Chapter 7
Threads - 2 Options:
// implements Runnable
Thread a = new Thread(new Thread_A());
a.start();
// extends Thread
Thread_B b = new Thread_B();
b.start();
Chapter 9
Component |
Event Types
Generated |
Button |
Action |
Canvas |
Mouse, MouseMotion, Key |
Check Boxes |
Item |
Choice |
Item |
List |
Item (on selection of item), Action
on double-click |
Scroll pane |
Mouse, MouseMotion |
Scrollbar |
Adjustment |
Text Field/Text Area |
Text, Action (on ENTER key press) |
For lists, addItem has been deprecated. Now, to add an item
to a list, use
List l = new List(3,
true);
l.add("qqqqq");
Menu bars and pull-down menus only appear in Frames.
Only Frames can contain a MenuBar.
Chapter 12
The following components have no default appearances and show up as
empty rectangles (unless they are subclassed and given their own paint()
methods).
-
Applet
-
Canvas
-
Frame
-
Panel
g.setColor() only affects the following drawing operation (not
what has been drawn already).
Font availability is platform dependant. The only ones you can count
on are "Serif", "Sans Serif", "Monospaced".
To set a font, use:
Font f = new Font("Serif",
Font.BOLD, 24);
g.setFont(f);
drawPolygon() and fillPolygon() both take int [] as the x and
y points.
Polylines cannot be closer or filled – they’re simply a run of line
segments.
repaint() schedules a call to update(Graphics g)
update(Graphics g) clears the component to it’s background colour and
calls paint(Graphics g)
Over-riding update() to simply do a paint() means the background
is not re-drawn (can accumulate operations – eg mouse clicks).
Chapter 13
CODE, WIDTH, HEIGHT tags are mandatory. Order is insignificant.
CODE and CODEBASE tags are case sensitive, and must include the .class
extension.
PARAM tag is case insensitive. Missing parameter causes getParameter()
to return null.
getParameter() returns a string
Multiple JARs can be downloaded using a comma separated list in the
ARCHIVE tag (eg ARCHIVE = "a.jar, b.jar").
Chapter 14
File Class
A File class can represent a file or directory (both which
may or may not exist).
Creating a File instance does not create a file on the harddisk.
The directory separator ("\" or "/") will work regardless of the platform,
without throwing an exception.
delete() will delete the file off the disk.
mkdir() will create a directory on disk
renameTo() will rename the file.
RandomAccessFile Class
incompatible with stream/reader/writer model
needs to use a mode ("r" or "rw") for read only, or read/write
IOException thrown if "r" used, and file doesn’t exist.
Supports reading/writing of all primitive types (eg, readint(), writeFloat()).
All methods throw IOException.
Streams/Readers/Writers
Streams deal in bytes.
Readers/Writers deal in unicode.
Low-level Streams – FileInputStream, FileOutputStream (byte
reads/writes – no primative)
BufferStreams – BufferInputStream – sits between low-level and high
level streams – reduces I/O overhead
High-Level Filter Stream – DataInputStream – can only chain to low-level
streams (primative reads/writes)
Example of use:
FileInputStream fis
= new FileInputStream("c:\eddie");
BufferedInputStream bis = new
BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
Readers/Writers
Same as equivalent Streams (eg, BufferedReader, FileInputReader,
etc)
deal in unicode
doesn’t have primitive read/write calls (eg, no writeInt())
Only has reading/writing of char’s
Do you have a Java Problem?
Ask It in The Java
Forum
Java Books
Java Certification,
Programming, JavaBean and Object Oriented Reference Books
Return to : Java
Programming Hints and Tips
All the site contents are Copyright © www.erpgreat.com
and the content authors. All rights reserved.
All product names are trademarks of their respective
companies.
The site www.erpgreat.com is not affiliated with or endorsed
by any company listed at this site.
Every effort is made to ensure the content integrity.
Information used on this site is at your own risk.
The content on this site may not be reproduced
or redistributed without the express written permission of
www.erpgreat.com or the content authors.
|