Notes - Introduction To Java
Notes - Introduction To Java
Siddharth Shukla
December 13, 2014
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
i n t e r f a c e Instrument {
// compile time c o n s t a n t s
i n t i = 5 ; // s t a t i c and f i n a l
// no method d e f i n i t i o n s a l l o w e d
v o i d p l a y ( ) ; // methods a r e a u t o m a t i c a l l y p u b l i c
S t r i n g what ( ) ;
void adjust ( ) ;
}
// I n n e r c l a s s
public c l a s s Parcel1 {
c l a s s Contents {
private int i = 11;
public int value () { return i ; }
}
class Destination {
private String label ;
D e s t i n a t i o n ( S t r i n g whereTo ) {
l a b e l = whereTo ;
}
String readLabel () { return l a b e l ; }
}
}
For iterating over the collections, we need to inherit from class Iterable. Collections framework also allows for bulk
operations such as containAll, addAll, removeAll, clear (also works on Map), putAll (Map) etc for acting on entire
collection as a whole.
Generics are javas way of eliminating unsafe casts and help make the code clearer and safer.
Arrays are expensive to insert and remove in the middle while linked lists are inexpensive. Red-Black trees are
used to sort TreeSet. WeakHashMap Removes key/value pairs when the only reference to the key is the one from
the hash table entry. LinkedHashMap and LinkedHashSet remember the order in which the items were added.
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
33
34
35
36
37
38
39
40
41
p u b l i c i n t e r f a c e C o l l e c t i o n <E> e x t e n d s I t e r a b l e <E> {
b o o l e a n add (E o ) ;
b o o l e a n addAll ( C o l l e c t i o n c ) ;
void c l e a r ( ) ;
b o o l e a n c o n t a i n s ( Object o ) ;
boolean containsAll ( C o l l e c t i o n c ) ;
b o o l e a n e q u a l s ( Object o ) ;
b o o l e a n isEmpty ( ) ;
Iterator iterator () ;
b o o l e a n remove ( Object o ) ;
b o o l e a n removeAll ( C o l l e c t i o n c ) ;
boolean r e t a i n A l l ( C o l l e c t i o n c ) ;
int size () ;
}
public interface Iterable {
Iterator iterator ();
}
public interface Iterator {
b o o l e a n hasNext ( )
E next ( )
v o i d remove ( )
}
p u b l i c L i s t I t e r a t o r <E> e x t e n d s I t e r a t o r <E> {
v o i d add (E o )
b o o l e a n hasNext ( )
boolean hasPrevious ( )
E next ( )
i n t nextIndex ( )
E previous ()
int previousIndex ()
v o i d remove ( )
v o i d s e t (E o )
}
p u b l i c i n t e r f a c e Map<K, V> {
void c l e a r ( )
b o o l e a n c o n t a i n s K e y ( Object key )
b o o l e a n c o n t a i n s V a l u e ( Object v a l u e )
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
Set entrySet ( )
b o o l e a n e q u a l s ( Object o )
V g e t ( Object key )
i n t hashCode ( )
b o o l e a n isEmpty ( )
Set keySet ( )
V put (K key , V v a l u e )
v o i d p u t A l l (Map t )
V remove ( Object key )
int size ()
Collection values ()
}
\\ G e n e r i c s
s t a t i c v o i d e x p u r g a t e ( C o l l e c t i o n <S t r i n g > c ) {
f o r ( I t e r a t o r <S t r i n g > i = c . i t e r a t o r ( ) ; i . hasNext ( ) ; )
i f ( i . next ( ) . l e n g t h ( ) == 4 )
i . remove ( ) ;
}
\\ L i n k e d L i s t
L i s t <S t r i n g > s t a f f = new L i n k e d L i s t <S t r i n g > ( ) ; // L i n k e d L i s t implements L i s t
s t a f f . add ( Amy ) ; // L i n k e d L i s t add method adds t o t h e end o f t h e c o l l e c t i o n
s t a f f . add ( Bob ) ;
s t a f f . add ( C a r l ) ;
Iterator iter = staff . iterator ();
S t r i n g f i r s t = i t e r . next ( ) ; // v i s i t f i r s t e l e m e n t
S t r i n g s e c o nd = i t e r . next ( ) ; // v i s i t s e c o n d e l e m e n t
i t e r . remove ( ) ; // remove l a s t v i s i t e d e l e m e n t
\\ T r e e S e t
S o r t e d S e t <S t r i n g > s o r t e r = new TreeSet<S t r i n g > ( ) ; // T r e e S e t implements S o r t e d S e t s o r t e r . add (
s o r t e r . add ( Amy ) ;
s o r t e r . add ( C a r l ) ;
for ( String s : sorter )
System . out . p r i n t l n ( s ) ;
p u b l i c i n t e r f a c e Comparable<T> {
i n t compareTo (T o t h e r ) ; / / r e t u r n s 0 i f same , n e g a t i v e i f l e s s and p o s i t i v e i f more .
}
Java I/O
Data is lost when a local variable goes out of scope or when the program terminates. Data maintained in files is
termed as persistent data. Java I/O provides communication with devices such as files, console, networks, memory
blocks, etc. There are various types of communication such as sequential, random-access, binary, char, lines, words,
objects, etc. Usually, two types of streams are byte-oriented (binary) and character-oriented (text). For reading,
InputStream. For writing, OutputStream. System.in is an instance of the BufferedInputStream class. System.out
is an instance of PrintStream class. Streams read and write 8-bit values to/from various data sources. Java I/O
system is based on these four classes.
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
// Copy one f i l e i n t o a n o t h e r
p u b l i c s t a t i c v o i d main ( S t r i n g [ ] argv ) throws IOException {
FileInputStream in = n u ll ;
FileOutputStream out = n u l l ;
try {
i n = new F i l e I n p u t S t r e a m ( x a n a d u . t x t ) ;
out = new FileOutputStream ( O u t a g a i n . t x t ) ;
int c ;
w h i l e ( ( c = i n . r e a d ( ) ) != 1)
out . w r i t e ( c ) ;
}
finally {
i f ( i n != n u l l )
in . close ( ) ;
i f ( out != n u l l )
out . c l o s e ( ) ;
}
}
// For b i n a r y f i l e s
F i l e I n p u t S t r e a m f i n = new F i l e I n p u t S t r e a m ( employee . dat ) ;
// For Unicode
F i l e W r i t e r out = new F i l e W r i t e r ( output . t x t ) ;
F i l e R e a d e r i n = new F i l e R e a d e r ( i n p u t . t x t ) ;
i n . r e a d L i n e ( ) ; out . p r i n t l n ( s t r i n g t ) ;
Concurrency
Each independent task is called a thread. Multithreading is the practice of running more than one thread at the
same time. Two types of multitasking are Preemptive Multitasking (OS interrupts programs without consulting
with them to release the CPU), and Cooperative Multitasking (Programs interrupted when they are willing to yield
control). Two ways to implement threads are implementing the runnable interface (recommended) and inheriting
form thread class (not recommended).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Runnable
c l a s s MyRunnable implements Runnable {
p u b l i c v o i d run ( ) {
// t a s k code
}
}
c l a s s BallRunnable implements Runnable {
...
p u b l i c v o i d run ( ) {
try {
f o r ( i n t i = 1 ; i <= STEPS ; i ++) {
b a l l . move ( component . getBounds ( ) ) ;
component . r e p a i n t ( ) ;
Thread . s l e e p (DELAY) ;
}
}
c a t c h ( I n t e r r u p t e d E x c e p t i o n e ) {}
}
}
22
23
24
25
26
B a l l b = new B a l l ( ) ;
p a n e l . add ( b ) ;
Runnable r = new BallRunnable ( b , p a n e l ) ;
Thread t = new Thread ( r ) ;
t . start ();
Networking
Basic Networking concepts:
Client-Server model: Synchronous : Clients wait for response before they proceed with their computation.
Asynchronous : Clients proceed with computations as the response is returned by server. Idea : Allow
bilateral information exchange between nodes (a server and a client). Client initiates the dialog with the
server, while the server waits and listens for client connections.
Peer-to-Peer: Every peer provides client and server functionality. Ideally, avoids centralised components.
Ability to establish new topologies dynamically. Requires control and coordination logic on each node.
Ports and Sockets: Ports and sockets are abstract concepts that allow the programmer to use communication
links. Port is a logical connection to a computer that is identified by a 2 byte number (0-65545). Sockets
are software abstractions used to represent the terminals of a connection between two machines. 0-1023 :
well-known ports, 1024-49151 : not assigned but must be registered, and 49152-65535: neither assigned not
registered.
IP adresses: IPv4 : represent machines in quad notation with an address made up of 4 8-bit numbers,
separated by dots (i.e. 127.0.0.1). These numbers are in the range (0-255). IPv6 replaces IPv4 and uses
128-bit numbers. Hence, it provides way more addresses than possible with IPv4.
(package java.net) In Java, networking concepts have been abstracted away from the programmer. It allows handling
of multiple connections concurrently thanks to built-in multithreading. Socket objects : Create a socket to connect
to the other machine, then get back InputStream and OutputStream from the socket. Two stream based socket
classes in java.net package are : Socket (used by clients to initiate connection, requires IP address and Port number
of the remote machine to construct) and ServerSocket (used by server to listen for incoming connections, returns
established socket via accept() method). For serving multiple clients, take the resulting Socket object from accept()
and make a new thread and call accept again to wait for new connections.
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
finally{
s . close ();
}
}
}
\\ Making a c o n n e c t i o n : c l i e n t
c l a s s ServeOneJabber implements Runnable {
p r i v a t e Socket socket ;
p rivat e BufferedReader in ;
p r i v a t e P r i n t W r i t e r out ;
p u b l i c ServeOneJabber ( S o c k e t s ) throws IOException {
socket = s ;
i n = new B u f f e r e d R e a d e r ( new InputStreamReader ( s o c k e t . g e t I n p u t S t r e a m ( ) ) ) ;
out = new P r i n t W r i t e r ( new B u f f e r e d W r i t e r ( new OutputStreamWriter (
s o c k e t . getOutputStream ( ) ) ) , t r u e ) ;
s t a r t ( ) ; // C a l l s run ( )
}
p u b l i c v o i d run ( ) {
try {
while ( true ) {
String s t r = in . readLine ( ) ;
i f ( s t r . e q u a l s ( END ) ) break ;
out . p r i n t l n ( s t r ) ;
}
}
c a t c h ( IOException e ) {
System . e r r . p r i n t l n ( IO E x c e p t i o n ) ;
}
finally {
try {
socket . close ( ) ;
}
c a t c h ( IOException e ) {
System . e r r . p r i n t l n ( S o c k e t not c l o s e d ) ;
}
}
}
}
Event Handling
Event processing route : Event (mouse click) Hardware OS Windowing System Application. Events have
a source object (object that generate the event e.g. buttons, scrollbars, etc.) and a handler object(listener : object
that listens and responds to events from certain sources). Events originate in the source object and are handled
in the handler objects. i.e. Source object fires events to handler object. Event sources can be any objects (GUI
component, hardware device, NON-GUI component, Remote process, etc.). Binding of source and handlers is done
at runtime by passing a reference to the handler to a registration method in the source. A single event can be
sent to multiple handlers and this is known as Multicasting. Multiplexing is when a handler receives events from
multiple sources.
Each AWT listener interface with more than one method comes with an Adapter class. The Adapter class implements all the interface methods using do- nothing functions. Extend the Adapter class and specify desired reactions
to some event types in the class by overriding some methods.
Two types of events:
Semantic events: Express what the user is doing. For instance, Clicking a button. Examples : ActionEvent
(Button click, menu selection, Carriage Return pressed, etc.), ItemEvent (user made a selection from a set of
checkboxes or list, etc.), AdjustmentEvent(user adjusted a scrollbar), etc..
Low-Level events: Low level events that make semantic events possible. For instance, mouse movement, key
presses, etc. Examples: KeyEvent (key press), MouseEvent (press, release, move, drag, etc.), FocusEvent
(component got focus or lost focus), WindowEvent (window state changed), etc.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// R e g i s t e r i n g L i s t e n e r o b j e c t s with s o u r c e o b j e c t s
eventSourceObject . addEventListener ( eventListenerObject ) ;
// Example w/ L i s t e n e r implementaion
// U s u s a l l y , t h e l i s t e n e r c l a s s i s p l a c e d w i t h i n t h e p a n e l c l a s s
c l a s s ButtonPanel e x t e n d s JPanel {
c l a s s C o l o r A c t i o n implements A c t i o n L i s t e n e r {
p u b l i c ColorAction ( Color c ){
backGroundColor = c ;
}
p u b l i c v o i d a c t i o n P e r f o r m e d ( ActionEvent e v e n t ) {
s e t B a c k g r o u n d C o l o r ( backgroundColor ) ;
}
p r i v a t e C o l o r backgroundColor ;
}
C o l o r A c t i o n y e l l o w A c t i o n = new C o l o r A c t i o n ( C o l o r .YELLOW) ;
C o l o r A c t i o n b l u e A c t i o n = new C o l o r A c t i o n ( C o l o r .BLUE ) ;
10
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
C o l o r A c t i o n r e d A c t i o n = new C o l o r A c t i o n ( C o l o r .RED) ;
yellowButton . addActionListener ( yellowAction ) ;
blueButton . a d d A c t i o n L i s t e n e r ( b l u e A c t i o n ) ;
redButton . a d d A c t i o n L i s t e n e r ( r e d A c t i o n ) ;
Object o b j e c t = e v e n t . g e t S o u r c e ( ) ;
}
// WindowListener
c l a s s Terminator implements WindowListener {
p u b l i c v o i d windowClosing ( WindowEvent e ) {
System . e x i t ( 0 ) ;
}
p u b l i c v o i d windowOpened ( WindowEvent e ) {}
p u b l i c v o i d windowClosed ( WindowEvent e ) {}
p u b l i c v o i d w i n d o w I c o n i f i e d ( WindowEvent e ) {}
p u b l i c v o i d w i n d o w D e i c o n i f i e d ( WindowEvent e ) {}
p u b l i c v o i d windowActivated ( WindowEvent e ) {}
p u b l i c v o i d windowDeactivated ( WindowEvent e ) {}
}
WindowListener l i s t e n e r = new Terminator ( ) ;
frame . addWindowListener ( l i s t e n e r ) ;
Swing
AWT - Abstract Window Toolkit. AWT replaced by JFC (Java Foundation Classes) in Java 2. GUI part of JFC
is known as Swing. GUIs built from GUI components called widgets (window Gadgets). Widgets are objects
with which users interact via mouse, keyboard, voice, etc. rt.jar file contains java code for swing. Built on AWT
primitives. Some old AWT classes such as event models are still used in Swing.
MVC (Model View Controller) design pattern. According to MVC, Model stores the content or data (Content state of a button, text in a text field), view display the content (visual appearance), and Controller handles user
input(Behaviour or reaction to events). A text-field example.
The model must implement methods to change the contents and to discover what the content is (add, remove,
getText, etc.). The model is completely non-visual. The controller handles user input events. Wrapper classes
(e.g., JButton, JTextField) store the model and view. Queries about the model and view are handled by wrapper
classes. Look and feel is responsible for the view and UI design e.g. Nimbus in Java 6. Each button stores a
button model that can be retrieved.
11
All components in a container are positioned by a layout manager. Default layout manager for panel is FlowLayout. FlowLayout reflows elements upon resizing. Default layout : Centre. Can be further set by Panel.setLayout(new
FlowLayout(FlowLayout.LEFT)).
Default layout manager of the content pane of every JFrame is BorderLayout. Components here, can be placed
in centre, north, south, east, or west of the content pane.
GridLayout consists of grid (think Bootstrap). Arranges components in rows and columns like a spreadsheet,
cells are always same sized and shrink/expand upon window resize. Buttons must be attached to event listeners.
All swing components (java.swing package) are subclasses of java.awt.Container. Most swing components emit
events from the java.awt.event package. Components of Swing :
Containers - (components that contain other components e.g. JFrame, Panel). JFrame - independent window
that can be moved around. JPanel - blank rectangular component that can contain other components.
Usually, place panels within frames.
Text Input - JTextFIeld and JTextArea, both inherit from JTextComponent abstract class. JTextComponent
has text manipulation methods : setText(String t), getText(), and setEditable(boolean b). JPasswordField for
passwords, JFormattedTextField for validating user input. Formatter for validating input (Default Formatter,
getNumberInstance, getCurrencyInstance, etc.)
Labels - JLabel is a component that hold texts to identify components and dont react to user input.
Buttons - JCheckBox (multiple choice), JRadioButton (single choice), JButton (good old button) for event
handling.
Menus - JMenuBar (can only be used with JFrame or JApplet) as they provision setJMenuBar(). Menus can
have icons, labels, or both. Menus can be of regular, radio, or checkbox type. There are also popup menus
such as JPopUpMenu, these dont have a title.
Toolbar - A button bar providing quick access to elements.
Dialog Boxes - Modal (doesnt allow interaction with the rest of the app unless information is supplied e.g.
select file), Modeless (Lets users manage both dialog box and app simultaneously). Mainly uses JOptionPane.
Types : JDialog, JFileChooser, etc.
1
2
// JButton
JButton button = new JButton (
Blue
);
12
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
13
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
JDBC
Java Database Connectivity. Allows Java program access to databases using standard SQL statements using JDBC
API. Pure-Java RDBMS JavaDB.
Specify data source when connecting to the DB (Syntax similar to URLs). DriverManager [package java.sql]
1 Ex : S p e c i f y l o c a l Derby d a t a b a s e & a PostgreSQL d a t a b a s e named COREJAVA
2 j d b c : derby : / / l o c a l h o s t : 1 5 2 7 /COREJAVA; c r e a t e=t r u e
3 j d b c : p o s t g r e s q l :COREJAVA
4
5 Register Drivers :
6
java
D j d b c . d r i v e r s=o r g . p o s t g r e s q l . D r i v e r MyProg
14
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
33
34
35
36
37
38
39
40
o r s e t a system p r o p e r t y
System . s e t P r o p e r t y ( j d b c . d r i v e r s
o r g . p o s t g r e s q l . Driver )
Sample prog :
String url =
j d b c : p o s t g r e s q l : COREJAVA ;
S t r i n g username =
dbuser ;
S t r i n g password =
secret
;
try {
Connection conn = DriverManager . g e t C o n n e c t i o n ( u r l , username , password ) ;
conn . setAutoCommit ( f a l s e ) ; // Turn O f f auto commit
Statement s t a t = conn . c r e a t e S t a t e m e n t ( ) ;
S t r i n g command = U p d a t e B o o k s +
SET P r i c e = P r i c e
5.00
+
WHERE T i t l e NOT LIKE
%I n t r o d u c t i o n%
;
s t a t . executeUpdate ( command )
R e s u l t S e t r s = s t a t . executeQuery ( S E L E C T FROM Books ) ;
w h i l e ( r s . next ( ) ) {
String isbn = rs . getString ( 1 ) ;
d o u b l e p r i c e = r s . getDouble (
Price
}
s t a t . executeUpdate ( command1 ) ;
s t a t . executeUpdate ( command2 ) ;
conn . commit ( ) ;
}
catch ( Exception e ){
conn . r o l l b a c k ( ) ;
}
finally{
conn . c l o s e ( ) ;
}
15
);
16