Java Revision
Block 1
Basic Java
-
how to use command line
-
step1: complete a java file that named “xxx.java”
-
step2: use “javac” command to compile
1
...>aDict>javac -d example/bin example/hello.java
then a java file in “…/aDict/example” called “hello.java” is compiled and saved in “…/aDict/example/bin/example”
Note: “example” is a package
-
step3: use “java” command to run
1
...>aDict>java -cp example/bin example.hello
then “hello.java” runs.
-
-
Java comments
1
2
3
4
5
6
7
8
9
10// single line comment
/*
many line comments
*/
/**
* This is a javadoc comment
* use "javadoc" cmd to generate a javadoc file that offers an API documentation.
*/ -
main method
1
2
3
4
5
6public class hello{
public static void main(String[] srgs){
System.out.println("hello");
System.out.println(args[0]);//throws an exception when there is no argument.
}//a pair of curly brackets means a code block
} -
variables & primitive type
-
type cast
-
Operator Precedence
-
important statements
if-else, while, do-while, for, switch-case, break, continue
Object-Oriented
-
Object
a thing. is neither an attribute, nor an operation.
- exists at compile time
-
Class
define objects containing attributes and operations
- exists at runtime.
-
Object vs Class
- class is the template of objects
- objects are instances of the class
-
Constructor
- same name as the class name
- no return type
- no-argument constructor is provided if no constructor is given
- constructor can be overridden
- if you give a constructor with arguments, then no no-argument constructor will be provided
-
Encapsulation
hiding data, secure, reusable
-
Access Modifiers
- public: all can access only if importing them
- protected: package member & subclasses of it
- “default”: package member
- private: class only
-
Accessor & Mutator
getter & setter
-
Instance variable & Local variable
- Instance variable: initialised to the default value(0, 0.0, false, null)
- Local variable: no initialisation. If it is used with no value, there will be an error.
- method parameters can be seen as local variables. Notice that method parameters are always initialised.
-
reuse
1
2
3
4
5
6
7
8
9private double radius;
public circle(double radius){
this.setRadius(radius);
}
public void setRadius(double radius){
this.radius=radius;
} -
Overloading
- same name
- different parameters
- signature: name + type of parameter + parameters
Block 2
Arrays
-
create an array
1
2
3
4
5
6
7
8
9
10
11int[] nums= new int[5];
int[] nums2= {0,1,2,3,4};
int[] nums3= new int[]{1,2,3,4,5};
Object[] objects= new Objects[5];
System.out.println(nums[0]);
System.out.println(nums[5]);//ArrayIndexOutOfBounds
for(int i=0;i<nums.length;i++){
System.out.println(nums[i]);
} -
copy arrays
- loop
- System.arraycopy() method
- clone method
-
vs ArrayList
ArrayList: a resizable array
- ArrayList doesn’t need to know its size-- resizable
- you can use add method to assign an object without provide index
- parameterised: you need give the type of the objects to be stored
-
API
Java library
- main packages in JDK: java.lang, java.util, java.io, java.awt
- Math is in java.lang
- ArrayList, Scanner , Random are in java.util
Inheritance
-
overriding
- same name as superclass method name
- same parameters as superclass’
- private, final, static methods can not be overridden
-
Access Modifiers
- private are not inherited
-
super
invoke variables, methods and constructors in superclass
Polymorphism
an object variable can refer to multiple actual types(upcasting)
- you can use it in generics. eg. ArrayList<>
- you can also use it when passing an argument
- when there is an overriding method, invoking it instead of the method in superclass
- Only variables in superclass can be invoked. static methods are also like this.
- downcasting
Abstract class
an class with abstract methods
- abstract method: no implement
- abstract class cannot be initialisation
- can not be modified by private, final or static
- if there is no abstract method, a class can also be declared “abstract”
- can have constructors
Object
the mega class that all classes extend it
-
equals
not only comparing references
-
toString
-
hashCode
-
getClass
Block 3
Interface
-
vs abstract class
- differences:
- no instant variables, only constant(public final static)
- all methods must be abstract except default and static
- a kind of multiple inheritance
- similarities:
- no initialization
- can contain constants
- both have abstract methods
- differences:
-
name conflicts
-
same methods:
- different parameters: overloading
- differ by return type: error
- identical: keep one
-
same constants:
- contain both: use “Interface. variable” to refer to them
-
-
default & static
-
default:
- give one implement method which can be overridden. --> when call the method which has the same name with other methods, use “Interface. super. method” to invoke it.
- no private, no final, no static
- has to be overridden when there are more than 1 default method with the same name
-
static:
- similar to default, but cannot be overridden.
- invoke just like the way constants do
-
Garbage Collection
-
Heap & Stack
- Stack: Method at the top is always the method being executed
- Instance variables & Local variables -> declared in a class & declared in a method/ method parameters
- Object & Object reference
- Object reference: refers to an object. non-primitive
-
Constructor Chaining
- a new object is created, all constructors in its heritance tree must be run.
- if no super() constructor is given, compiler will provide one.
- super() /this() should be the first statement in the constructor
- super() and this() cannot be invoked at the same time
-
Life of objects and variables
-
object: depends only on the reference variable referring to it
- memory for object is allocated at runtime dynamically.
- if there is no alive reference variable referring to the object, the object will be eligible for GC.
- get rid of references: reference goes out of scope, assigned to another object or set to null
-
local variable: lives only within the method that declared it
- in scope: within the method that declared it. A variable can only be used when it is in scope.
-
instance variable: live for as long as objects they belong to live
-
Numbers
-
final
- no change, no overriding, no inheritance
- variables: must either be initialized when declared or in the constructor
-
static
-
static modifier: declare a class variable or class method
-
use class name to refer to them
-
variables:
- static variables are created when class is created
- all objects of the same class have the same static variables
- non-initialized static variables will have default value
-
methods:
- static method is available when the class is created
- all objects of the same class have the same copy of methods
- static methods can only reference static variables
-
-
Math
- no instance variables
- cannot make an instance of class –private constructor
- eg. Math. min(), Math. max(), Math. cos()…
1
System.out.println(Math.round(-0.5) + " " + Math.round(0.5));
output: “0 1”
-
Initialization
- static: before any object of the class is created. when the variable is declared, or in a static initializer(static block)
-
Random
-
Wrapper class
- used when a variable of a primitive type need to be treated as an object
-
final class
-
wrapping:
1
Integer a = new Integer(10);
-
unwrapping
1
int una = a.intValue();
-
autoboxing: automatic wrapping
-
usage:
- method arguments
- return values
- boolean expressions
- operations
- assignments
-
parse methods
- parseInt(), parseDouble(), .booleanValue()
-
Recursion
- base case
- call itself
Strings
-
Strings are immutable
-
String Pool
-
where String literals are put
- GC doesn’t cleanup the String Pool
-
-
String Buffer & String Builder
-
used for variable strings
- String Builder: not synchronous
-
-
StringTokenizer
-
breaks string into several pieces
-
default delimiter: space, tab, new line, carriage return
-
if you set a delimiter parameter “au”, “a” and “u” are two separate delimiters.
-
token: the substring that a string splits into.
-
delimiter: the character that used to separate a string
-
-
-
Scanner
- useDelimiter(String str) will take whole str as a delimiter which is different from split
-
Format Specifier
Block 4
GUI
-
what is GUI?
- Method for interacting with a computer
- Widgets: Things you can put in a window(Component)
-
3 main concepts?
- Component: the thing user interacts with
- Container: the thing holds all components(Containers may contain containers)
- Event: the action user triggers
-
how to create a basic GUI?
extending the “JFrame” class is more common
eg1.
1
2
3
4
5
6
7JFrame aFrame= new JFrame("a Title");
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setTitle("Some Name");
JButton aButton= new JButton("Click!");
aFrame.getContentPane().add(aButton);
aFrame.setSize(100,100);
aFrame.setVisible(true);eg2.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUIex1 implements ActionListener {
JButton myButton;
public static void main(String[] args) {
GUIex1 a=new GUIex1();
a.createAGUI();
}
public void createAGUI(){
JFrame jFrame=new JFrame("aGUI");
jFrame.setSize(300,300);
myButton=new JButton("Hello");
myButton.addActionListener(this);
jFrame.add(myButton);
jFrame.setLocationRelativeTo(null);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==myButton) {
if(myButton.getText()=="Hello"){
myButton.setText("Bye");
}else {
myButton.setText("Hello");
}
}
}
} -
write an event handler
1
2
3
4
5
6public class MyClass implements ActionListener {
someComponent.addActionListener(instanceOfMyClass);
public void actionPerformed(ActionEvent e) {
// code that reacts to the action ...
}
} -
Layout manager
allow to format components on the screen
- FlowLayOut
- When you add components to the screen, they flow left to right (centered), based on the order added and the width of the screen.
- If the screen is resized, the components’ flow will change based on the new width and height.
- GridLayOutt
- arranges components in rows or columns.
- BorderLayOut
- divides the screen into five fields. You can places containers or components at these fields.
- JFrame default: BorderLayOut
- JPanel default: FlowLayOut
- FlowLayOut
Exception Handling
handle unusual conditions
-
Exception Class Hierarchy
Throwable{ Exception{ IOException, InterruptedException, RuntimeException{ ClassCastException, NullPointerException, …}}}
-
try/catch, finally
1
2
3
4
5
6
7
8
9
10
11
12
13try{
//codes--protect statements
//(1)may throw Exception1
//(2)may throw Exception2
//(3)may throw Exception3
//(4)
}catch(Exception1 e){
//codes--report and recover the exception
}catch(Exception2 e){
//
}finally{
//codes--regardless of an exception is thrown
}-
if (2) throws an exception, (3)(4) will be skipped.
the program will execute the second catch clause, and “finally” will be executed as well.
-
if no one throws an exception, catch clauses will be skipped.
“finally” will be executed.
-
if codes in try block throws an exception that not declared in catch field, JVM will stop the execution.
-
Exception2 cannot be a subclass of Exception1
-
-
Exception class
- your own exception must extend “Exception”
-
throws/throw
- “throws” means a method wants client code to handle them. when there is a checked exception, “throws” tells user must handle this exception.
- “throw” means the code throw an exception in this case
-
Stack Trace Messages
-
RuntimeException
- unchecked type-- not be checked by compiler
- eg. NullPointerException, IndexOutOfBoundsException, ArithmeticException
-
Assertions
expression that must be true
1
2assert i==1;
assert (a>0) : "a<=0";//if expression is false, an exception will be thrown with an message-
cmd:
-ea: enable your program to run with assertions
-da: disable your program from running with assertions
-
assert throws AssertionError(extends Error)
-
File I/O
saving data permanently.
-
I/O
input/output-- bring in/ send out, reading/ writing
-
Streams
connection to source or destination of data
-
byte
machine-formatted data
- InputStream
- OutputStream
-
character
human-readable data
- Reader
- Writer
-
-
Read a text file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import java.io.*
String aFile= "hello.txt";
String contents="";
try{
FileReader fileReader = new FileReader(aFile);//a lot of methods in these two class has checked exception to be thrown.
BufferedReader bufferedReader = new BufferedReader(fileReader);//efficient, useful methods
String aLine = bufferedReader.readLine();
while (aLine != null) {
contents = contents + aLine;
aLine = bufferedReader.readLine();
}
bufferedReader.close();
fileReader.close();
}catch (IOException e) {
System.out.println("Errors occured");
System.exit(1);
} -
Write a text file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20import java.io.*
String[] str=new String[3];
for(int i=0;i<str.length;i++){
str[i]=""+i;
}
File file=new File("hello.txt");
try{
FileWriter fileWriter=new FileWriter(file);
BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);
for (int i=0;i< str.length;i++){
bufferedWriter.write(str[i]);
bufferedWriter.newLine();
}
bufferedWriter.close();
fileWriter.close();
}catch (IOException e){y
System.out.println("there is an error");
System.exit(1);
}
Collections & Sorting
collection of data
-
Set/ List/ Map
- Set: no duplicate elements
- List: elements can be accessed by position
- Map: no duplicate keys, each key has only one value
-
Enumerations
-
Iterator
- boolean hasNext()
- Object next()
-
2-dimensional Arrays
-
how to create a 2D arrays
1
2
3
4int[][] matrix1=new int[3][3];
//int[][] matrix2=new int[][]; illegal
int[][] matrix3=new int[3][];// column can be omitted
Object[][] matrix4=new Object[3][3]// an matrix of objects
-
-
sorting
- bubble sort
-
comparable
- int compareTo(Object)
- 0 --equal
- <0 --less
- >0 --greater
- int compareTo(Object)