Docsity

COMP2396 Cheat Sheet, Cheat Sheet of Computer Science

Toggle sidebar
bg1
Introduction
Procedural Programming
Emphasis: tasks
Top-down design: Break problem → tasks
Access-Data: share, vulnerable ( trace)
Object-Oriented Programming
Emphasis: data
Bottom-up design: Break problem → entities (obj)
of OOP
Modularity: obj can be written & maintained independently
Information hiding: hide obj’s internal implementation
Code re-use: class can be reused directly / by inheritance
Pluggability: Problematic obj can be replaced individually
Abstraction
Represent essential feature ( bg details)
Only necessary, common property of obj (problem dependent)
Essential in design of classes & objs
Encapsulation
Wrap up data & operation into one unit
Hide the implementations from others
Data access directly from outside an obj (information hiding)
Interact with obj only via exposed interface (public methods)
Allow changing internal implementation of an obj
X hurt the overall system
Essential in implementing class & object
Inheritance
The process by which objects of one class acquire the
properties of objects of another class
Sub-class automatically inherit all the properties of super-class
(instance var + method)
IS-A relationship (1-direction) between sub-class & super-class
Specialization of super-class (override method)
Avoid duplicate code multiple inheritance
Inheritance (Instance Variable)
overridden Hidden → both exist, see super-class’s var
(sub-class’s var have same name with super-class’s var)
Inheritance (Access Control)
Inherited: public private
(still there, X access directly, need via public getter/setter)
Access level
Access modifier
Class
Package
Sub-class
World
private
private
Y
N
N
N
default
(none)
Y
Y
N
N
protected
protected
Y
Y
Y
N
public
public
Y
Y
Y
Y
Inheritance (Method Overriding)
Same argument list Compatible return type
less accessible
Method Overloading
related to inheritance/polymorphism Same name
Different args list Can different return types/access level
Polymorphism
Take more than one form
Compiler decide if method can be call is based on ref type, not
actual obj type (super-class reference use sub-class’s method)
Garbage Collection
Heap: mem each time an obj is created go into
Allocates mem space on heap according to space that obj need
Java manage mem for you
When obj used again → eligible for garbage collection
Garbage collection is unpredictable, usually when mem is low
Java
Platform independent: Java program compiled → platform
independent byte code → executed by JVM
Architectural-neutral: Compiler generate archi-neutral obj file
→ compiled code (executable on many processors)
Portable: (becuz of the above 2)
Robust (strong): have compile + runtime error checking
Multithreaded: do tasks simultaneously
Strongly-typed: change var type
assign value to var ( same type) (int/byte/float/… → same)
Main() Method
return type Accept any num of args from cmd line
Do only 2 thing → Create a obj & call a method (most Java app)
Primitives and References
Data Types
Primitive:
Type
Value Range
boolean
true / false
char
0 – 65535
byte
-128 – 127
short
-32768 – 32767
int
-2147483648 – 2147483647
long
-huge – huge
float
varies
double
varies
floating num is treated as double
e.g. float f = 32.5f; specify this num is float
Obj references: references to objs
Type Conversion
Compiler allow assign value (wider range type) to
var (narrower range type) → may result in information loss
Type Casting tells compiler it is intended → error reporting
e.g. float f = (float) 32.5;
e.g. if(obj instanceof Snowboard) {
Snowboard sameObj = (Snowboard) obj; }
Array
Must decide size when create ( change)
Array is obj with (only 1) instance var (length) + method
State and Behavior of an Object
Methods: Parameters & Arguments
Parameters: placeholders (sth like local variables)
Arguments: actual value passed into the method when calling
Mechanism: pass-by-value
Constructor
Call: automatically when create object & before assigned to a
reference. explici tly call
Default: empty + no arguments
assumed when >1 constructors is defined
Inheritance: not inherited.
Auto call super-class’s constructor when create sub-class
object. “super()” to call explicitly
Static Method
depend on & use any instance variable
Can run without instance use non-static methods
Called using class name e.g. Math.round(3.14);
Static Variable
Shared by all instances of that class
Initialization: when the class is first loaded
each time an instance is made
before any object of that class can be created
before any static method of the class runs
Accessed using class name e.g. doub le d = Math.PI;
Can be used in static methods
Final
Variable: change after initialized default value
Must be initialized at declaration/in the constructor
Constant: e.g. public static final double PI = 3.14;
Must be initialized at declaration / in a static initializer
Method: be overwritten by sub-class
Class: be extended = sub-classes
Static initializer
Runs as soon as the class is loaded
Before: any static method can be called
any static variables can be used
e.g. public static final int abc; static { abc = 123; }
Java API
ArrayList
ArrayList<Egg> myList = new ArrayList<Egg>(); get(int index);
add(Object elem); remove(Object elem); remove(int in dex);
contains(Object elem); isEmpty(); indexOf(Object elem);
Package
In the Java API, classes are grouped into packages
Help the overall organization Provide a level of security
Provide name-scoping that helps to prevent collisions of names
Wrapper Classes
Primitive
Wrapper
boolean
Boolean
char
Character
byte
Byte
short
Short
int
Integer
long
Long
float
Float
double
Double
Number Formatting
String s = String.format("This cat weights %.2fkg", 4.3333);
"%,d" means “inserts commas and format the number as a
decimal integer”
"%.2f" means “format the number as a floating point with a
precision of 2 decimal places”
"%,.2f" means “inserts commas and format the number as a
floating point with a precision of 2 decimal places”
"%,5.2f" means “insert commas and format the number as a
floating point with a precision of 2 decimal places and with a
minimum of 5 characters, padding spaces and zeros as
appropriate”
"%h" means “format the number as a hexadecimal”
"%c" means “format the number as a character”
Abstract Classes and Interfaces
Abstract Class
Must be extended
Must be marked “abstract” if >=1 abstract method
Prevent from being instantiated, can still be reference type
e.g. abstract class Canine extends Animal { … }
Abstract Method
Must be overridden body
When useful/generic code for sub-classes
Part of the protocol for sub-class to be used in polymorphism
e.g. public abstract void eat();
Concrete class
Specific enough to be instantiated
Implemented all abstract method from super-classes/interface
Deadly Diamond of Death (DDD)
Multiple inheritance: “two super-classes” approach
Interface
100% Pure abstract class (all abstract methods)
Class implementing the interface(s) must implement all the
interfaces’ methods
e.g. public interface Pet { public abstract void play(); }
The Ultimate Superclass: Object
Object Class
Every class in Java extends the Object class
public boolean equals(Object obj):
when override, also override hashCode()
public final Class getClass():
return the runtime class of the current obj e.g. class Dog
public int hashCode():
returns a hash code value (integer) of the current obj
the Object class implements this method by converting the
internal address of the object into an integer
e.g. 2018699554
public String toString():
should always be overwritten
e.g. Dog@7852e922
GUI and Event-handling
Swing Components
javax.swing.JComponent
All components can hold other components
Add user interactive components into background components
e.g. buttons and lists e.g. frames and panels
Event Source
Swing GUI component = event source
obj that get user action and create event obj
Accept reg from listener Call event handler of listener
Event Object
An event is represented as an obj of some event class
e.g. ActionEvent, MouseEvent …
Carry data about the event back to the listener
e.g., the screen coordinates of the mouse in a MouseEvent
Listener
Implement listener interface and become listener
e.g. ActionListener → ActionEvent
Listener must reg itself with the event source to receive event
obj from the event source e.g. addActionListener()
Drawing Panel
Make a sub-class of JPanel Override paintComponent()
Whenever the frame holding the drawing panel is displayed /
refreshed, paintComponent()will be called
call this method explicitly
args to this method is a Graphics obj = the actual drawing
canvas that get slapped onto the real display, get this
Inner Class
Can use all property (instance var & methods, private) of the
outer class tied to vice-versa
Inner class obj must be tied to its outer class obj on the heap
Layout Manager
A Java obj associated with a particular component
Hierarchy of control is only 1 level
BorderLayout
Default layout manager: frame
FlowLayout
Component → laid out left→right in the order they are added
Default layout manager: panel
BoxLayout
Stack the components either vertically or horizontally
e.g. panel.setLayout(new BoxLayout(panel , BoxLayout.Y_AXIS));
Example
public class SimpleGUI {
JFrame frame;
public void go() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton colorButton = new JButton("Change Circle");
colorButton.addActionListener(new ColorListener());
frame.add(colorButton, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setVisible(true);
}
class ColorListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
frame.repaint();
}
}
}
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.ORANGE);
g.fillRect(20, 50, 100, 70);
Image image = new ImageIcon("batman.jpg").getImage();
g.drawImage(image, 3, 4, this);
}
}
Swing Components
JTextField
JTextField field = new JTextField(20); / JTextField("name");
System.out.println(field.getText()); field.selectAll();
field.setText("whatever"); field.requestFocus();
JTextArea
JTextArea text = new JTextArea(10, 20);
JScrollPane scroller = new JScrollPane(text);
text.setLineWrap(true);
scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.
VERTICAL_SCROLLBAR_ALWAYS);
scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.
HORIZONTAL_SCROLLBAR_NEVER);
panel.add(scroller);
text.append("button clicked");
JCheckBox
JCheckBox check = new JCheckBox(“Yo”);
Jlist
String[] entries = {"alpha", "beta", "gamma"};
JListlist = new JList(entries);
JMenuBar, JMenu, JMenuItem
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("MenuA");
JMenuItem menuItem = new JMenuItem("Item");
menu.add(menuItem);
menuBar.add(menu);
frame.setJMenuBar(menuBar);
menuItem.addActionListener(this);
Serialization and File I/O
Serialization
Serialized file is hard for human to read, but is easier & safer
for program to restore objs
Entire obj graph is serialized/fails (NotSerializableException)
Save the entire object graph (when 2 objects in the graph are
the same, save one)
Write Object to a File
try {
FileOutputStream fileStream = new FileOutputStream("MyGame.sav");
//If file “MyGame.sav” exist, it will be created automatically
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(ken);
os.close(); //Closing the stream at the top closes the ones
underneath (FileOutputStream)
} catch (FileNotFoundException / IOException e) { … }
Restore Object to a File
try {
FileInputStream fileStream = new FileInputStream("MyGame.sav");
//get an exception if file “MyGame.sav” exist
ObjectInputStream os = new ObjectInputStream(fileStream);
GameCharacter ken = (GameCharacter) os.readObject();
// Read objs in the same order in which they are written
os.close(); } catch (FileNotFoundException / IOException e) {…}
Writing to a Text File
try {
FileWriter writer = new FileWriter("Test.txt");
//Normal way
FileWriter fileWriter = new FileWriter("Test.txt");
//Buffered Reader
BufferedWriter writer = new BufferedWriter(fileWriter);
//Buffered Reader
writer.write("This is a plain text file");
writer.close(); } catch (Exception e) { … }
Reading from a Text File
Replace “Writer” with “Reader”
BufferedWriter
FileWriter write each thing passed to file everytime→efficient
Chain BufferedWriter(chain stream) to FileWriter, it will hold
all the stuff writen to it until it is full → write to the file
Can still send data before full e.g. flush()
ActionListener
ActionPerformed()
MouseListener
mouseClicked()
mousePressed()
mouseReleased()
mouseEntered()
mouseExited()
pf2

Partial preview of the text

Download COMP2396 Cheat Sheet and more Cheat Sheet Computer Science in PDF only on Docsity!

Introduction Procedural Programming Emphasis: tasks Top-down design: Break problem → tasks Access-Data: share, vulnerable ( trace) Object-Oriented Programming Emphasis: data Bottom-up design: Break problem → entities (obj)  of OOP Modularity: obj can be written & maintained independently Information hiding: hide obj’s internal implementation Code re-use: class can be reused directly / by inheritance Pluggability: Problematic obj can be replaced individually Abstraction Represent essential feature ( bg details) Only necessary, common property of obj (problem dependent) Essential in design of classes & objs Encapsulation Wrap up data & operation into one unit Hide the implementations from others Data  access directly from outside an obj (information hiding) Interact with obj only via exposed interface (public methods) Allow changing internal implementation of an obj X hurt the overall system Essential in implementing class & object Inheritance The process by which objects of one class acquire the properties of objects of another class Sub-class automatically inherit all the properties of super-class (instance var + method) IS-A relationship (1-direction) between sub-class & super-class Specialization of super-class (override method) Avoid duplicate code  multiple inheritance Inheritance (Instance Variable)  overridden Hidden → both exist,  see super-class’s var (sub-class’s var have same name with super-class’s var) Inheritance (Access Control) Inherited: public private (still there, X access directly, need via public getter/setter) Access level Access modifier Class Package Sub-class World private private Y N N N default (none) Y Y N N protected protected Y Y Y N public public Y Y Y Y Inheritance (Method Overriding) Same argument list Compatible return type  less accessible Method Overloading  related to inheritance/polymorphism Same name Different args list Can different return types/access level Polymorphism Take more than one form Compiler decide if method can be call is based on ref type, not actual obj type (super-class reference  use sub-class’s method)

Garbage Collection Heap: mem each time an obj is created go into Allocates mem space on heap according to space that obj need Java manage mem for you When obj  used again → eligible for garbage collection Garbage collection is unpredictable, usually when mem is low Java Platform independent: Java program compiled → platform independent byte code → executed by JVM Architectural-neutral: Compiler generate archi-neutral obj file → compiled code (executable on many processors) Portable: (becuz of the above 2) Robust (strong): have compile + runtime error checking Multithreaded: do tasks simultaneously Strongly-typed:  change var type  assign value to var ( same type) (int/byte/float/… → same) Main() Method  return type Accept any num of args from cmd line Do only 2 thing → Create a obj & call a method (most Java app) Primitives and References Data Types Primitive: Type Bit Depth Value Range boolean JVM-specific true / false char 16 bits 0 – 65535 byte 8 bits - 128 – 127 short 16 bits - 32768 – 32767 int 32 bits - 2147483648 – 2147483647 long 64 bits - huge – huge float 32 bits varies double 64 bits varies floating num is treated as double e.g. float f = 32.5f; specify this num is float Obj references: references to objs Type Conversion Compiler  allow assign value (wider range type) to var (narrower range type) → may result in information loss Type Casting tells compiler it is intended →  error reporting e.g. float f = (float) 32.5; e.g. if(obj instanceof Snowboard) { Snowboard sameObj = (Snowboard) obj; } Array Must decide size when create ( change) Array is obj with (only 1) instance var (length) + method State and Behavior of an Object Methods: Parameters & Arguments Parameters: placeholders (sth like local variables) Arguments: actual value passed into the method when calling Mechanism: pass-by-value Constructor Call: automatically when create object & before assigned to a reference.  explicitly call Default: empty + no arguments  assumed when >1 constructors is defined Inheritance: not inherited. Auto call super-class’s constructor when create sub-class object. “super()” to call explicitly Static Method  depend on & use any instance variable Can run without instance  use non-static methods Called using class name e.g. Math.round(3.14); Static Variable Shared by all instances of that class Initialization: when the class is first loaded  each time an instance is made before any object of that class can be created before any static method of the class runs Accessed using class name e.g. double d = Math.PI; Can be used in static methods Final Variable:  change after initialized  default value Must be initialized at declaration/in the constructor Constant: e.g. public static final double PI = 3.14; Must be initialized at declaration / in a static initializer Method:  be overwritten by sub-class Class:  be extended =  sub-classes Static initializer Runs as soon as the class is loaded Before: any static method can be called any static variables can be used e.g. public static final int abc; static { abc = 123; } Java API ArrayList ArrayList myList = new ArrayList(); get(int index); add(Object elem); remove(Object elem); remove(int index); contains(Object elem); isEmpty(); indexOf(Object elem); Package In the Java API, classes are grouped into packages Help the overall organization Provide a level of security Provide name-scoping that helps to prevent collisions of names Wrapper Classes Primitive Wrapper boolean Boolean char Character byte Byte short Short int Integer long Long float Float double Double Number Formatting String s = String.format("This cat weights %.2fkg", 4.3333); "%,d" means “inserts commas and format the number as a decimal integer” "%.2f" means “format the number as a floating point with a precision of 2 decimal places” "%,.2f" means “inserts commas and format the number as a floating point with a precision of 2 decimal places” "%,5.2f" means “insert commas and format the number as a floating point with a precision of 2 decimal places and with a minimum of 5 characters, padding spaces and zeros as appropriate” "%h" means “format the number as a hexadecimal” "%c" means “format the number as a character” Abstract Classes and Interfaces Abstract Class Must be extended Must be marked “abstract” if >=1 abstract method Prevent from being instantiated, can still be reference type e.g. abstract class Canine extends Animal { … } Abstract Method Must be overridden  body When  useful/generic code for sub-classes Part of the protocol for sub-class to be used in polymorphism e.g. public abstract void eat(); Concrete class Specific enough to be instantiated Implemented all abstract method from super-classes/interface Deadly Diamond of Death (DDD) Multiple inheritance: “two super-classes” approach Interface 100% Pure abstract class (all abstract methods) Class implementing the interface(s) must implement all the interfaces’ methods e.g. public interface Pet { public abstract void play(); } The Ultimate Superclass: Object Object Class Every class in Java extends the Object class public boolean equals(Object obj): when override, also override hashCode() public final Class getClass(): return the runtime class of the current obj e.g. class Dog public int hashCode(): returns a hash code value (integer) of the current obj the Object class implements this method by converting the internal address of the object into an integer e.g. 2018699554 public String toString(): should always be overwritten e.g. Dog@7852e GUI and Event-handling Swing Components javax.swing.JComponent All components can hold other components Add user interactive components into background components e.g. buttons and lists e.g. frames and panels Event Source Swing GUI component = event source obj that get user action and create event obj Accept reg from listener Call event handler of listener Event Object An event is represented as an obj of some event class e.g. ActionEvent, MouseEvent … Carry data about the event back to the listener e.g., the screen coordinates of the mouse in a MouseEvent Listener Implement listener interface and become listener e.g. ActionListener → ActionEvent Listener must reg itself with the event source to receive event obj from the event source e.g. addActionListener() Drawing Panel Make a sub-class of JPanel Override paintComponent() Whenever the frame holding the drawing panel is displayed / refreshed, paintComponent()will be called  call this method explicitly args to this method is a Graphics obj = the actual drawing canvas that get slapped onto the real display,  get this Inner Class Can use all property (instance var & methods,  private) of the outer class tied to vice-versa Inner class obj must be tied to its outer class obj on the heap Layout Manager A Java obj associated with a particular component Hierarchy of control is only 1 level BorderLayout Default layout manager: frame FlowLayout Component → laid out left→right in the order they are added Default layout manager: panel BoxLayout Stack the components either vertically or horizontally e.g. panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); Example public class SimpleGUI { JFrame frame; public void go() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); JButton colorButton = new JButton("Change Circle"); colorButton.addActionListener(new ColorListener()); frame.add(colorButton, BorderLayout. CENTER ); frame.setSize(300, 300); frame.setVisible(true); } class ColorListener implements ActionListener { public void actionPerformed(ActionEvent event) { frame.repaint(); } } } class MyDrawPanel extends JPanel { public void paintComponent(Graphics g) { g.setColor(Color. ORANGE ); g.fillRect(20, 50, 100, 70); Image image = new ImageIcon("batman.jpg").getImage(); g.drawImage(image, 3, 4, this); } } Swing Components JTextField JTextField field = new JTextField(20); / JTextField("name"); System.out.println(field.getText()); field.selectAll(); field.setText("whatever"); field.requestFocus(); JTextArea JTextArea text = new JTextArea(10, 20); JScrollPane scroller = new JScrollPane(text); text.setLineWrap(true); scroller.setVerticalScrollBarPolicy(ScrollPaneConstants. VERTICAL_SCROLLBAR_ALWAYS); scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants. HORIZONTAL_SCROLLBAR_NEVER); panel.add(scroller); text.append("button clicked"); JCheckBox JCheckBox check = new JCheckBox(“Yo”); Jlist String[] entries = {"alpha", "beta", "gamma"}; JListlist = new JList(entries); JMenuBar, JMenu, JMenuItem JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("MenuA"); JMenuItem menuItem = new JMenuItem("Item"); menu.add(menuItem); menuBar.add(menu); frame.setJMenuBar(menuBar); menuItem.addActionListener(this); Serialization and File I/O Serialization Serialized file is hard for human to read, but is easier & safer for program to restore objs Entire obj graph is serialized/fails (NotSerializableException) Save the entire object graph (when 2 objects in the graph are the same, save one) Write Object to a File try { FileOutputStream fileStream = new FileOutputStream("MyGame.sav"); //If file “MyGame.sav”  exist, it will be created automatically ObjectOutputStream os = new ObjectOutputStream(fileStream); os.writeObject(ken); os.close(); //Closing the stream at the top closes the ones underneath (FileOutputStream) } catch (FileNotFoundException / IOException e) { … } Restore Object to a File try { FileInputStream fileStream = new FileInputStream("MyGame.sav"); //get an exception if file “MyGame.sav”  exist ObjectInputStream os = new ObjectInputStream(fileStream); GameCharacter ken = (GameCharacter) os.readObject(); // Read objs in the same order in which they are written os.close(); } catch (FileNotFoundException / IOException e) {…} Writing to a Text File try { FileWriter writer = new FileWriter("Test.txt"); //Normal way FileWriter fileWriter = new FileWriter("Test.txt"); //Buffered Reader BufferedWriter writer = new BufferedWriter(fileWriter); //Buffered Reader writer.write("This is a plain text file"); writer.close(); } catch (Exception e) { … } Reading from a Text File Replace “Writer” with “Reader” BufferedWriter FileWriter write each thing passed to file everytime→efficient Chain BufferedWriter(chain stream) to FileWriter, it will hold all the stuff writen to it until it is full → write to the file Can still send data before full e.g. flush() ActionListener ActionPerformed() MouseListener mouseClicked() mousePressed() mouseReleased() mouseEntered() mouseExited()

Connection Streams & Chain Streams Connection Stream: connection to source/destination (e.g. file, network socket) low-level method for serialization (e.g. bytes → destination) Chain Streams: works only if chained to another stream higher-level methods for serialization (e.g. obj → o/ stream) Flexibility: mix & match streams Serializable Interface Marker/tag interface becuz  method to implement If any super-class is serializable, subclass is also serializable Transient Instance Variables Some obj depend on runtime-specific info → shud  save e.g. network connections, threads, file obj … Skipped by the serialization process Given default values when deserialized e.g. transient String currentID; Deserialization data is read from the stream JVM decide the obj’s class type by serialized obj’s stored info If  find/load the class, throw exception & deserialization fail New obj is created on the heap, but constructor  run If the obj has a non-serializable super-class, the no-argument constructor for that class will run, along with any constructors above it Instance var of the obj are given value from serialized state Version Control Each time an obj is serialized, it is ‘stamped’ with a serialVersionUID (about the class structure) Different serialVersionUID when the class has been modified serialVersionUID is compared when deserialized  match → exception Assign a value → keep the same serialVersionUID e.g. private static final long serialVersionUID = 63…; Changes to a class that can hurt deserialization Changes to a class that are usually OK Delete an instance var Add new instance var to the class (existing objs will deserialize with default values for the instance var they didn’t have when they were serialized) Change the declared type of an instance var Change the access level of an instance var Change a non-transient instance variable to transient Change an instance var from transient to non- transient (previously-serialized objs will have default value for the previously-transient var) Move a class up or down the inheritance hierarchy Add/Remove classes to the inheritance tree Change a class (anywhere in the obj graph) from serializable to non-serializable Change an instance var to static Networking and Multi-threading Client-Server Model Client A connects to the server Server make a connection & add client A to the list of parti Client A send a message to server Server distribute the message to ALL parti (including Client A) Socket Connection Socket (java.net.Socket class) is an obj that represents a connection b/t 2 app which may/ run on 2 distinct machines TCP Port  16 - bit unsigned number assigned to a specific server app 1 program running on 1 TCP port only >1 program → bind → java.net.BindException Reserved: 0 to 1023 e.g. HTTP(80), Telnet(23), FTP(20) Available: 1024 – 65535 Reading Data from a Socket Writing Data from a Socket Multi-threading A thread can be considered as a line of execution. Has its own call stack → store method invocations and local var The main thread create additional (worker) threads to handle tasks in parallel e.g. Runnable threadJob = new MyRunnable(); Thread myThread = new Thread(threadJob); myThread.start();) Runnable Interface A Runnable object is to a Thread object what a job is to a worker only 1 method e.g. run(); States of a Thread Thread Scheduler  guarantee about scheduling &  API on the scheduler →  control Sleep Help threads take turns by putting them to sleep periodically Force it to leave the running state → let other thread to run  wake up before the specified duration (milliseconds) Go to runnable state when wake up e.g. try { Thread.sleep(2000); } catch (Exception e) {…} Concurrency Problem When >=2 threads have access to the same object on the heap Result in a race condition → may cause data corruption Synchronization Guarantee that the thread (with key) can wake up and finish the method before any other thread can access e.g. private synchronized void makeWithdrawal(int amount) { ... } Object’s Lock Every Java obj has a lock with a single key A thread can enter one of the synchronized method only if it has the obj’s key If an obj has >1 synchronized method, there is still only 1 key Deadlock Problem When two threads are holding a key the other thread wants → forever wait Java has no mechanism to handle deadlock Exception Handling Exception Method can throw an exception when something fails at runtime An exception is an obj of type Exception/any of its sub-classes When a method throws an exception, that method is popped off the stack immediately, and the exception is thrown to the next method down the stack Handling Exceptions try/catch block Compiler  care how, but only that exception is handled Code below the catch block continues (no matter exception is thrown) Finally Block When try/catch block complete → finally block runs → then method continue Even if try/catch block has a return statement, the finally block still run Unchecked Exceptions RuntimeExceptions (& sub-classes) are not checked by the compiler  check a method declares that it throws a RuntimeException or not caller have try/catch block or not Mostly from code logic e.g. casting a reference into an incompatible type Checked Exceptions All exceptions ( RuntimeException & sub-classes) are checked by compiler Method that might throw a checked exception must announce it with a throws- exception declaration Ducking Declare the method will throw exceptions rather than handle it by try/catch Ducker pop off the stack directly and exception is thrown to the next method Exception Rules  have a catch or finally block without a try block  put code between the try block and the catch block try block must be followed by either catch/finally block, or both try block with only a finally block = ducker (follow above rules for ducker) Multiple Exceptions Method can throw >1 exceptions (declare all the checked exception thrown) >=2 exceptions have common super-class → method can declare/catch just the super-class Life and Death of an Object Stack Set aside as a scratch space for a thread of execution Store method invocations and local var Last-In-First-Out (LIFO) Heap Set aside for dynamic allocation Garbage-collectible Where all obj live Instance Variable Live inside the obj they belong to → also live on the heap Constructor Super-class constructors must finish before its sub-class constructor super() must be 1st statement this(): call a constructor from another overloaded constructor in the same class only be used in constructor either super()/this(), both Simple Chat Server import java.io.; import java.net.; import java.util.; public class SimpleChatServer { ArrayList clientOutputStreams; public static void main(String[] args) { SimpleChatServer server = new SimpleChatServer(); server.go(); } public void go() { clientOutputStreams = new ArrayList(); try { ServerSocket serverSocket = new ServerSocket(5000); while (true) { Socket clientSocket = serverSocket.accept(); PrintWriter writer = new PrintWriter(clientSocket.getOutputStream()); clientOutputStreams.add(writer); // creates a new thread to handle this new client Thread t = new Thread(new ClientHandler(clientSocket)); t.start();} } catch (Exception ex) { ex.printStackTrace(); } } // go public class ClientHandler implements Runnable { //inner class BufferedReader reader; Socket sock; public ClientHandler(Socket clientSocket) { try { sock = clientSocket; InputStreamReader isReader = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(isReader); } catch (Exception ex) { ex.printStackTrace(); } } public void run() { String message; try { while ((message = reader.readLine()) != null) { System. out .println("read " + message); broadcasts(message); } } catch (Exception ex) { ex.printStackTrace(); } } } // ClientHandler public void broadcasts(String message) { for (PrintWriter writer : clientOutputStreams) { try { writer.println(message); writer.flush(); } catch (Exception ex) { ex.printStackTrace(); } } } // broadcasts } Simple Chat Client import java.io.; import java.net.; import javax.swing.; import java.awt.; import java.awt.event.; public class SimpleChatClient { JTextArea incoming; //for showing messages JTextField outgoing; //for user inputs BufferedReader reader; //for receiving messages PrintWriter writer; //for sending messages Socket sock; //socket connection to the server public static void main(String[] args) { SimpleChatClient client = new SimpleChatClient(); client.go(); } public void go() { try {sock = new Socket("127.0.0.1", 5000); //sets up network connection InputStreamReader streamReader = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(streamReader); writer = new PrintWriter(sock.getOutputStream()); System. out .println("networking established"); } catch (Exception ex) { ex.printStackTrace(); } //builds the GUI JFrame frame = new JFrame("Simple Chat Client"); frame.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); //set up textarea to show incoming msg incoming = new JTextArea(15, 50); incoming.setLineWrap(true); incoming.setWrapStyleWord(true); incoming.setEditable(false); JScrollPane qScroller = new JScrollPane(incoming); qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants. VERTICAL_SCROLLBAR_ALWAYS ); qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants. HORIZONTAL_SCROLLBAR_NEVER ); //sets up a text field for getting user inputs outgoing = new JTextField(20); // sets up a "Send" button JButton sendButton = new JButton("Send"); sendButton.addActionListener(new SendButtonListener()); //layouts all the components on a panel JPanel panel = new JPanel(); panel.add(qScroller); panel.add(outgoing); panel.add(sendButton); //adds the panel to the frame frame.add(panel, BorderLayout. CENTER ); frame.setSize(640, 320); frame.setVisible(true); //makes the frame visible // starts a new thread to receive msg from the server Thread readerThread = new Thread(new IncomingReader()); readerThread.start(); } //go //inner class public class SendButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { try {//sends the text in the text field to the server writer.println(outgoing.getText()); writer.flush(); } catch (Exception ex) { ex.printStackTrace(); } outgoing.setText(""); outgoing.requestFocus(); //reset text field } } //SendButtonListener // inner class public class IncomingReader implements Runnable { public void run() { String message; try {// reads incoming msg from the server while ((message = reader.readLine()) != null) { System. out .println("read " + message); //appends incoming msg to text area incoming.append(message + "\n"); } } catch (Exception ex) { ex.printStackTrace(); } } } // IncomingReader } // SimpleChatClient