Introductory Java Programming

final revision of past exam papers.

--objects & inheritance--

1. Java objects and class

Class: the description of a group of objects

Object: a particular member of a class

An object is defined by a class, the class defines the attributes and operations exposed by one or more related objects.

A class only exists at compile time while an object only exists at runtime.

2. Polymorphism: using a single definition (superclass) with different types (subclass).

Treat subclass object as superclass object: 1) Person p = new Student(); 2) Arrays that contain both person and student.

3. public String toString(){}

4. Static & final

Initializations: Initialization of static variables happens before any object of the class is created, which is not applied to final variables.

Final variables can be initialized at compile time or at run time. Final variables must either be initialized when declared or in the constructor.(static final: when declared/ static initializer block)

Modifications: the modification of the value of static variables will affect state of any instance belonging to the same class. The modification of the final variables will cause an error because it’s not allowed to modify a final variable.

methods: the static methods can only reference static variables. Static method can be accessed without instance of class. The final methods cannot be overridden.

5. We cannot reduce the visibility of the inherited method from superclass. [注意是否声明public]

6. Recursive algorithms

two parts: 1) the so called base case (this is the simplest case of a problem, whose solution is known) 2) the recursive call (this is the more complex case, where a call is made to the same method).

7. Two ways of comparing objects: 1. The objects implement the Comparable interface. -> natural ordering 2. A Comparator object is used to compare the two objects.-> only one form of sorting. Multiple forms: multiple comparators

--variables & collections--

8. int[]array = {1,2,3,4,5};

/ int[]array = new int[] {1,2,3,4,5};

9. Array & ArrayList: 1) ArrayLists can vary in length, but arrays cannot. 2) ArrayLists have a richer API than arrays. (add, remove, iterator)3) Array can store primitive type and objects, ArrayList can only store objects. 4) To assign an object in a regular array, you must assign it to a specific index, but with an ArrayList you needn’t

10. String myString = new String("Hello") à object, on the heap

using string literal (e.g., String str = "Welcome") à goes on the string pool

11. An object is alive as long as there are live references to it, the reference for object item is assigned to another object (goes out of scope e.g. end of method / explicitly set to NULL)at Line 10, so it is eligible for garbage collection at Line 10.

12. Wrapper class: Integer iWrapped = new Integer(100);

int unWrapped = iWrapped.intValue();

13. Maps: Map<String, String>petSounds = new HashMap<String,String>(); petSounds.put("cat", "Meow"); petSounds.put("mouse", "Squeak"); String val = (String)petSounds.get("dog");

--files--

14. java.io.File: No exception is thrown if file does not exist

File(String pathname): creates file with specified pathname

Creating an object from File Class does not create any file in the disk. Rather, the File object simply refers to the paths that is specified when creating the File object. Use file.exists() to check whether the file exists.

FileReader: A java.io.FileNotFoundException will occur if you attempt to create a FileReader with a nonexistent file.

FileWriter: If the file doesn’t exist, a new file will be created.

15. To read a file:

import java.io.*;

public class LineCounter{

public static void main(String[] args) {

        String fileName = args[0];

                    FileReader fileReader = null;

                    BufferedReader bufferedReader = null;

        try{

            fileReader = new FileReader(fileName);

           bufferedReader = new BufferedReader(fileReader);

            while(bufferedReader.readLine() != null){

                String oneLine = bufferedReader.readLine();

            }catch (FileNotFoundException e){

                                       System.out.println(“Could not find ”+fileName);

                                       System.exit(1);

} catch(IOException e){

            System.out.println(e);

            System.exit(1);

}finally{

         try{

            bufferedReader.close();

            fileReader.close();

         }catch(IOException e){

            System.out.println(e);

            System.exit(1);

        }

    }

}

16. Write to a file:

import java.io*;

public class CountWriter {

public static void main(String[] args) {

File myFile = new File("count.txt");

if (myFile.exists()) {

System.out.println("File already exists.");

System.exit(1); }

try{

FileWriter output = new FileWriter(myFile); à create a file

for (int i=1; i<5; i++)

         output.write(i + “\n”);

output.close();

}

Catch (IOException ex) {ex.printStackTrace();}

}

}

17. Javadoc: javadoc -d docs Example.java

@author (classes and interfaces only, required)

@version (classes and interfaces only, required)

@param (methods and constructors only)

@return (methods only)

Javadoc is a formal description (or API) of your Java code; it means someone who wants to use your code does not need to read the code, but can still understand what your code does

--GUI--

18. Basic GUI:

3 main concepts: Component: An object that the user can see on the screen and can also interact with. Container: A component that can hold other components. Event: An action triggered by the user (e.g. pressing a key, click a mouse button)

19. Add the widget to the frame

myFrame.getContentPane().add(myButton);

20. action + source → event (click + button -> change text)

Listener Interface: the bridge between the listener (the user code) and the event source (e.g. the button).

Event source: object that can turn user actions (e.g. click a mouse, close a window) into events.

finishbt.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                            }

                   });

21. Layout:

Layout Manager: An interface that defines methods for positioning and sizing objects within a container.

• FlowLayout(int align, int hgap, int vgap) (default layout for panel)

• GridLayout(int rows, int cols, int hgap, int vgap)

BorderLayout(int hgap, int vgap) (default layout for frame)

--Exceptions--

22. public class MyException extends Exception{

public MyException(){super(“Error!”);}

}

23. Exceptions: Exception in thread “main”java.lang.ArrayIndexOutOfBoundsException: Index 15 out of bounds for length 10;

24. Try-catch when read files:

An I/O stream can ‘break’ for many reasons, e.g. corrupted/missing file, damaged network, so many Java methods and classes for handling I/O streams declare that they may generate errors at runtime, also known as exceptions. try and catch code blocks allow such errors to be elegantly handled.

25. Throwable exception: Throwable String getMessage(); void printStackTrace(); ->recovery.

Try-catch vs throws-throw: detect & handle exceptions vs declare & throw exceptions.

Sometimes, you don’t want to catch exceptions, but want client code to handle them

26. Assertions: are used to ensure program correctness and avoid logic errors.

assert i==10; / assert (sum>10 && sum<500): “sum is” + sum -> detailed message(primitive / object)

Enabling assertions forces the statement assert(xxx) xxx; to be run. If false, it triggers an AssertionError (which is a sub-class of Error) to be thrown

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值