Download Java2

Document related concepts
no text concepts found
Transcript
Java
Dr. Yong Uk Song
Dept. of MIS
Yonsei University Wonju Campus
1
Session 1.
Introduction
2
Programming Languages (1)



First Generation
 Machine Languages
(e.g.) 01101011
Second Generation
 Assembly Languages
(e.g.) ADD X
 Assembler
Third Generation
 High Level Languages
(e.g.) a = a + x
 Compiler, Interpreter
3
Programming Languages (2)


Fourth Generation
 Non-Procedural Languages
(cf.) Procedural Languages
 Do What?
(cf.) Do How?
(e.g.) SELECT id FROM customer WHERE id > 50
Fifth Generation
 Artificial Intelligence
 Voice Recognition + Natural Language Processing
+…
4
Programming Languages (3)

Categories of Third Generation
Languages


Structured Programming Language
Object-oriented Programming Language
5
Structured Programming
Languages

Objectives



Tools


Debugging
Maintenance
Readability
Methodology


Divide and Conquer : Modulization
Control : Sequence, Division, Repetition
6
Object-oriented Programming
Languages

Objectives


Tools


Productivity of SW
Extensibility, Reusability
Methodology



Data-driven approach : Classes and Instances
Encapsulation(Data abstraction), Inheritance,
Polymorphism
The importance of control (sequence, division,
repetition) in a module is still stressed.
7
Data Abstraction


Separating of the representation of a
data object from the specification that
are essential for its correct use.
Classes




Data hiding
Member functions
Initialization
Operator overloading
8
Inheritance



Inheritance allows you to reuse data
and functions in the classes you have
created by passing all or parts of them
down to children classes (i.e.
subclasses, derived classes).
Type hierarchy
Single inheritance vs. Multiple
inheritance
9
Polymorphism





With polymorphism, you can send a
message to an object without worrying
about how the system will implement
the action.
Operator overloading (C++)
Function overloading
Function overriding
Virtual functions (default in Java)
10
Learning Java Is . . .



Learning programming structures
Learning classes
Learning initialization



Constructors
Learning derived classes
Learning packages, interfaces,
exception handling, stream, networking,
etc.
11
History of Java

Green project (Sun Microsystems, 1991)




Web Browser






A compact programming language for electronic devices
such as interactive TV, smart refrigerator, …
The target OS was called Star7
Oak (James Gosling)
WebRunner (HotJava) (Patrick Naughton & Jonathan
Payne) (1994)
JavaOne Conference (1996.5)
JavaSoft (Marc Andreesen(Netscape))
Java 1.0.2
Java 1.1.5
Java 2 (Java 1.2)
12
Platform Independence


Byte code
Virtual Machine

= Java Interpreter / Java Runtime
13
What is programming?


The purpose of programming is to make a SW which will
be executed later by another people to do a predefined
job.
The SWs are in fact executable files.




File name : *.exe
E.g. MS-Office, Notepad, MS-Windows XP, …
The final goal of programming is to make an executable
file.
Steps to make an executable file

Coding  Source code


Sometimes we call coding as programming in a narrow sense.
Compiling  Executable file

Compiling is included as an additional step of programming in a
wider sense.
14
Programming in Java

Source Codes


Executable Files


xxx.java
xxx.class
Execution

java xxx
15
Where are the Tools?

http://java.sun.com/

Java SE JDK


The core SW to develop and execute a Java
program.
NetBeans


IDE (Integrated development environment)
To support every steps while programming in
Java; coding(editing), compiling, execution,
debugging.
Using NetBeans IDE





Build a New Project
Edit the Source Code
Compile
Execute (Run)
Debug
Hello.java
class Hello
{
public static void main(String[ ] args)
{
System.out.println("Hello, world");
}
}
18
Exercise


Build a NetBeans project called Hello.
Make a program which prints out
"Hello".
19
Session 2.
Variables and Expressions
20
Comments (1)

/* ... */


C-language style comments
Comments for multiple lines
(e.g.)
/* This is a comment line 1.
This is a comment line 2.
This is a comment line 3.
… */

// ...


C++-language style comments
Comments for a single line (until end of line)
(e.g.)
// This is a comment.
21
Comments (2)

/** ... */


Comments for javadoc
Javadoc is a documentation generator from Sun Microsystems for generating API
documentation in HTML format from Java source code.
(e.g.)
/**
* Validates a chess move. Use {@link #doMove(int, int, int, int)} to move a piece.
*
* @param theFromFile file from which a piece is being moved
* @param theFromRank rank from which a piece is being moved
* @param theToFile file to which a piece is being moved
* @param theToRank rank to which a piece is being moved
* @return
true if the chess move is valid, otherwise false
*/
boolean isValidMove(int theFromFile, int theFromRank, int theToFile, int theToRank)
{
...
}
22
Exercise



Build a NetBeans project called Hello.
Make a programs which prints out
"Hello".
Add a comment as following:
This is a Java Hello World program.
This is my first Java program.
23
Variables and Literals

Variables




Of which value may be changed
To store some value
(e.g.) username = "song";
(e.g.) i = 3;
(e.g.) d = 1.2;
Declaration is required
(e.g.) String username;
(e.g.) int i;
(e.g.) double d;
Literals


Of which value can NOT be changed
Used as they are
(e.g.) "song"
(e.g.) 3
(e.g.) 1.2
24
Variable Declarations

Syntax


type variable1, variable2, …
Types

8 Primitive types


Arrays


byte, short, int, long, float, double, char, boolean
[]
Class types

Built-in Classes


Object, Class, String, Byte, Short, Int, Long, Float, Double,
Char, Boolean, …
User-defined Classes
25
Naming of Variables, Classes, …

Alphanumeric



Case sensitive



Upper and lower capital characters are regarded as different
characters.
e.g.) Int / int
Can not use keywords as names



A ~ Z, a ~ z, 0 ~ 9, _
Under bar(_) is regarded as an alphabet.
e.g.) boolean, break, byte, case, catch, char, class, const, do,
double, else, extends, final, float, for, goto, if, int, long, new,
package, private, protected, public, return, short, static, super,
switch, this, throw, throws, try, void, while, …
e.g.) false, null, true
The names of public classes should be same as their file
names.
26
Example of Variable Declarations

Correct






int i;
int i, aInteger, _i;
char c;
char c, aChar, _2;
double d;
double d, aDbl,
f100_;

Incorrect






int 2a;
int i; aInteger; _I;
char 2_3;
char c; aChar; _2;
double a&b;
double a Dbl, 100f_;
27
Exercise


Build a NetBeans project called Test.
Declare an integer variable "i" and a
double variable "d" in the "main"
method.
28
Literals

int














2.25
19E-95, 19e-95



'\n', '\t', …
'\'', '\\'
'\ooo', '\uhhhh'
(e.g. '\101', '\uC790')
'\A', '\"', …
String Constants

double
'A', '\n', '\r'
Escape Sequence


true, false
char

10L, 10l
012L, 012l
0xAL, 0xAl, 0xaL, 0xal
2.25F
2.25f
boolean

float


10
012
0xA, 0xa, 0XA, 0Xa
long



"Hello, world\n"
"-- \n -- ' -- \" -- \\ -- A --"
"-- \033 -- \uC790 --"
Please, note:


'A'
"A"
29
Expressions

Expressions



Operators


3*4+2
a*b+2
*, +, …
Operands




Literals
Variables
function calls
another expressions
(e.g.) 123 + 1
(e.g.) a + 1
(e.g.) Math.sin(3.14) + 1
(e.g.) 1 + (3 * a)
30
Forms of Expressions

Infix form


Prefix form



(+ 3 4)
Lisp language
Postfix form


3+4
34+
Java and many other third generation
languages use infix form for their expressions.
31
Categories of Operators (by
number of operators)

Unary operators


Binary operators


+a, -a, ++a, a++, --a, a--, …
a + b, a >= b, a && b, a = 3, …
Ternary operators

a?0:1
32
Another Categories of
Operators

Arithmetic Operators


Relational Operators


++, --
Assignment Operators


&&, ||, !
Incremental/Decremental Operators


>, >=, <, <=, ==, !=
Logical Operators


+, -, *, /, %
=, +=, -=, *=, /=, %=
Conditional Operators

?:
33
Arithmetic Operators
+, -, *, /, %(modulus)
 Be careful about the types of operands
(e.g.)

int a = 3, d = 8, b = 1, c = 1;
a+3
d/4
a*4+b
a*b-c
5%2
→1
9/2
→ 4 (It is NOT 4.5 !)
34
Exercise


Build a NetBeans project called Test.
Calculate and print out the result of "3 +
4.5".
35
String Concatenation Operator

+
(e.g.)
"abc" + "def"
"abc" + "123"
"abc" + 123
"abc" + 12.3
→ "abcdef"
→ "abc123"
→ "abc123"
→ "abc12.3"
String a = "abc";
a + "def"
→ "abcdef"
Relational Operators


>, >=, <, <=, ==, !=
Return values


False : false (boolean)
True : true (boolean)
(e.g.)
int a = 3, b = 1;
a>3
a == b
a != 3
37
Exercise


Build a NetBeans project called Test.
Calculate and print out the result of "3
>= 4.5".
38
Logical Operators


&&, ||, !
Return values


False : false (boolean)
True : true (boolean)
(e.g.)
int a = 3, b = 1, c = 1;
(a > 3) && (a <= 7)
(a > b) || (c == 1)
!(a > b)
↔ a <= b
39
Exercise


Build a NetBeans project called Test.
Calculate and print out the result of "3
>= 4.5 and 2 < 5".
40
Incremental/Decremental
Operators


++, -Return values



The value after increment/decrement when it appears in the front of the variable
The value before increment/decrement when it appears in the rear of the variable
Side effect



Increment/decrement of the value of the variable
Hence, its operand must be a variable.
Note: unary operators
(e.g.)
int n = 1;
n++
++n
++n + 1
n++ + 1
n---n
--n + 1
n-- + 1
41
Return Values and Side-effects

Return values
(e.g.) 3 + 4 → Value 7 returns as a result.
(e.g.) a = 4 → Value 4 returns as a result.

Side-effects
(e.g.) a = 4 → Variable "a" stores value 4.
42
Exercise




Build a NetBeans project called Test.
Declare an integer variable "i".
Set the value of the variable "i" as 3.
Calculate and print out the result of
"i++" and "++i" sequentially.
43
Assignment Operators


=, +=, -=, *=, /=, %=
Return values


The value stored to the left-hand-side (LHS) operand
(variable)
Side effect



Change in the value of the variable
Hence, its LHS operand must be a variable.
Note: binary operator
(e.g.)
int a, b;
a = 3;
a = b = 4;
a += 3;
44
Exercise





Build a NetBeans project called Test.
Declare two integer variables "i" and "j".
Calculate and print out the result of "i = j
= 3".
Print out the value of "i".
Print out the value of "j".
45
Conditional Operators


?:
Return values



The return value of the second operand if the return value of
the first operand is true
The return value of the third operand if the return value of
the first operand is false
Remark


The types of the second and third operands should be same.
If they are different, an implicit type conversion rule applies.
(e.g.)
int a = 3, i = 1, j = 1;
(a < 3) ? 4 : 5
(a == 3) ? i : (j + 1)
46
Exercise







Build a NetBeans project called Test.
Declare three integer variables "i", "j" and "k".
Calculate and print out the result of "i = j = k =
3".
Calculate and print out the result of "(i <= j) ?
++j : k++".
Print out the value of "i".
Print out the value of "j".
Print out the value of "k".
47
Implicit Type Conversions

Implicit rules


In case of binary or ternary operators, if the
types of their (last) two operands are
different, the type of one (more specific)
operand is automatically converted to that
of the other (more general) one.
Generality

byte  short  int  long  float  double
48
Exercise


Build a NetBeans project called Test.
Print out the result of "(2 < 3) ? 3 : 4.0".
49
Explicit Type Conversions



Type casting operator (unary operator)
Format
(type)expression
Usage


To enhance readability
To remove warnings by compilers
(e.g.) (int)a, (int)(9 / 2), i = (int)(9.0 / 2.0)
50
Exercise






Build a NetBeans project called Test.
Declare an integer variable "i".
Declare two double variables "d" and "e".
Set d as 9.0 and e as 2.0.
Calculate and print out the result of "i = d /
e".
If you have an error or a warning after
compiling, modify the expression to "i =
(int)(d / e)".
51
Priority among Operators
Operators
Associativity
Remarks
() [] .
left to right
! ~ ++ -- + - instanceof
right to left
unary
new (type)
right to left
unary
* / %
left to right
+ -
left to right
<< >> >>>
left to right
< <= > >=
left to right
== !=
left to right
&
left to right
^
left to right
|
left to right
&&
left to right
||
left to right
?:
right to left
= += -= *= /= %= &= ^= |= <<= >>=
right to left
ternary
52
Exercise




Build a NetBeans project called Test.
Declare two integer variables "i" and "j".
Try to calculate and print out the result
of "i = 2 * j = 3".
If you have an error or a warning after
compiling, modify the expression to "i =
2 * (j = 3)".
53
Session 3.
Standard Input and Output
54
Standard Output

Syntax
void System.out.print(Object)
void System.out.println(Object)

Remark

The object can be of any type; primitive types,
arrays, or built-in or user-defined classes.
(e.g.)
System.out.print("String");
System.out.print(123);
System.out.println("String");
System.out.println(123);
55
Standard Input

Syntax
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String BufferedReader.readLine( ) throws IOException
(e.g.)
import java.io.*;
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String str = reader.readLine();
System.out.println(str);
int i = Integer.parseInt(str);
System.out.println(i * 23);
} catch (IOException e) { }
56
Exercise





Build a NetBeans project called Test.
Declare a String variable s and an integer
variable i.
Read a string from the standard input and
set it as the value of s.
Parse and convert s to an integer and set
it as the value of i.
If i is less than 20, print out a string
"juvenile", otherwise print out a string
"adult". (use conditional operator)
57
Session 4.
Control Flow
58
Structured Programming

Three Control Structures


Sequence
Division


Repetition


if, switch
for, while, do while
Readability, Maintenance

Do not use "jump" control.
59
Statements and Blocks

Statements


Expressions which are ended with a semi-colon(;).
(e.g.)
x = 0;
System.out.println("Hello");
Blocks


Grouping several statements by open and closing braces.
Treated as statements, too.
(e.g.)
if (i != 0)
{
a = i + 3;
b = i * 4;
}
60
if - else (1)

Syntax
if (expression)
statement
else
statement
The "expression"
must return a boolean
value.
(e.g.)

int n = 3, a;
if (n > 0)
a = 1;
else
a = 0;

Extended Syntax
if (expression)
statement
else if (expression)
statement
…
else
statement
(e.g.)
if (x < 0) i = -1;
else if (x < 100) i = 0;
else i = 1;
61
if - else (2)
A else is associated with the closest
previous else-less if.
(e.g.)

if (n > 0)
if (a > b)
z = a;
else
z = b;
if (n > 0)
if (a > b)
z = a;
else
z = b;
62
Exercise





Build a NetBeans project called Test.
Declare a String variable s and an integer
variable i.
Read a string from the standard input and
set it as the value of s.
Parse and convert s to an integer and set
it as the value of i.
If i is less than 20, print out a string
"juvenile", otherwise print out a string
"adult". (use if statement)
63
switch (1)

Syntax
switch (expression)
{
case constant-expression: statements
case constant-expression: statements
…
default: statements
}


The return type of the expression should be one of
byte, char, short, or int.
break, return
64
switch (2)
(e.g.)
switch (c)
{
case 'Y':
case 'y':
answer = 1;
break;
default:
answer = 0;
break;
}
65
Exercise





Build a NetBeans project called Test.
Declare a String variable s and an integer
variable i.
Read a string from the standard input and set it
as the value of s.
Parse and convert s to an integer and set it as
the value of i.
If i is less than 3, print out a string "baby", if
less than 12, print out a string "kid", if less than
20, print out s a string "teenager", otherwise
print out a string "adult". (use switch statement)
66
for

Syntax
for (expression; expression; expression)
statement
(e.g.)
for (i = 0; i < 100; i++)
{
System.out.println(i);
}
67
Exercise





Build a NetBeans project called Test.
Declare a String variable s and an integer
variable n.
Read a string from the standard input and
set it as the value of s.
Parse and convert s to an integer and set
it as the value of n.
Calculate and print out the factorial value
of n. (use for statement)
68
while

Syntax
while (expression)
statement
(e.g.)
i = 0;
while (i < 100)
{
System.out.println(i);
i++;
}
69
Exercise





Build a NetBeans project called Test.
Declare a String variable s and an integer
variable n.
Read a string from the standard input and
set it as the value of s.
Parse and convert s to an integer and set
it as the value of n.
Calculate and print out the factorial value
of n. (use while statement)
70
do - while

Syntax
do
statement
while (expression);
(e.g.)
i = 0;
do
System.out.println(i);
while (i < 100);
71
break
A "break" causes the innermost enclosing
loop (such as "for", "while", and "do") or
"switch" to be exited immediately.
(e.g.)

for (i = 0; ; i++)
if (i >= 100)
break;
else
System.out.println(i);
72
Exercise



Build a NetBeans project called Guess.
Program a guessing game.
That is:





Select a random number between 0 and 100 by using
(int)(Math.random() * 100.0).
Input a number from the user.
If the number is less than the selected random number,
print out "Guess bigger!".
If the number is greater than the selected random
number, print out "Guess smaller!".
If the number is equal to the selected random number,
print out "You got it!" and then finish the program.
73
Labeled break
Designate the point where the control should
go after break
(e.g.)

out:
for (int i = 0; i < 10; i++)
{
while (x < 50)
{
if (i * x++ > 400) break out;
}
}
74
Homework





Summation from 1 to n
20th element of Fibonacci series
Prime numbers which are greater than 0
and less than 10,000
Minimum and maximum values among
integer values from standard input
Generate Check digit for Social Security
Number.
75
Session 5.
Arrays
76
What is Array?


An array is a data structure consisting of
a group of elements that are accessed
by indexing.
Each element has the same data type
and the array occupies a contiguous
area of storage.
77
Steps using an Array



Declare an array variable
Create an array object
Use each element in the array
78
Declaring an Array

Syntax


type variable[ ], … ;
type[ ] variable;
"type" is the type of each element.
(e.g.)

int a[ ], b[ ];
double[ ] d;
79
Creating an Array


Use "new" operator
 variable = new type[size];
 "size" may be an expression.
 Initial value of each element
 byte, short, int, long, float, double : 0
 boolean : false
 char : ‘\0’
 Objects : null
(e.g.)
playerName = new String[10];
int[ ] temp = new int[100];
Initialization (only for primitive types and String)
 String[ ] variable = { str1, str2, … };
(e.g.)
String[ ] playerName = { "Kim", "Park", "Song" };
80
Using an Array

Each element is referred by
"variable[index]"


index = 0 ~ size-1
"length" attribute
(e.g.)
a[0] = 10;
i = 3 * a[1] + 1;
n = a.length;
81
Exercise





Build a NetBeans project called Array.
Declare an array "a" of type int.
Create the "a" with the size of 10.
Set each element of "a" as 1.
Print out all elements of "a".
82
Multi-dimensional Arrays
(e.g.)
int[ ][ ] coords = new int[12][12];
coords[0][0] = 1;
coords[0][1] = 1;
83
Exercise



Store ten int values to an array, which
are input from the standard input.
Summate all elements of an int-type
array.
Sort an int-type array using Bubble sort
algorithm, of which elements are input
from the standard input.
84
Session 6.
Classes
85
Classes: Introduction

A class is a programming language construct
that is used as a blueprint to create objects.



This blueprint includes attributes and methods that
the created objects all share.
Classes, when used properly, can accelerate
development by reducing redundant code
entry, testing and bug fixing.
Built-in classes vs. User-defined classes

String, Object, Math
86
Classes: Main Concepts

Encapsulation(Data abstraction)




Inheritance





The term encapsulation is often used interchangeably with information hiding.
The principle of information hiding is the hiding of design decisions in a computer
program that are most likely to change, thus protecting other parts of the
program from change if the design decision is changed.
Supported by keywords like class or interface
Inheritance is a way to form new classes using classes that have already been
defined.
The new classes, known as derived classes, take over (or inherit) attributes and
behavior of the pre-existing classes, which are referred to as base classes (or
ancestor classes).
It is intended to help reuse existing code with little or no modification.
Supported by keywords like extends or implements
Polymorphism


Polymorphism is a programming language feature that allows values of different
data types to be handled using a uniform interface.
Supported by method overriding
87
Homework

Report on polymorphism

List and explain types of polymorphism.
88
Classes: Steps using a Class




Declare a class (only for user-defined
classes)
Declare an instance variable (object) for
a class
Create an object
Use the object
89
Classes : Declaring a Class
class class-name
{
members
private-members
protected-members
public-members
} // note - ;
(e.g.)
class MyDate
{
private int year, month;
private int day;
public void set(int y, int m,
int d)
{
year = y;
month = m;
day = d;
}
}
90
Classes : Declaring a Class

Private members



Only internal party can use them.
Internal party = Member functions
(methods)
Public members

Both internal and external parties can use
them.
91
Classes: Declaring an Object

type variable, … ;
(e.g.)
String str;
MyDate d;
92
Classes: Creating an Object

Operator new
variable = new type(args);
 The args are defined in constructors.
(e.g.)

str = new String( );
d = new MyDate( );
MyDate a = new MyDate(2000, 11, 23);
str = "aaa";
// special treatment for String
String s = "abc";
// special treatment for String
93
Classes: Using an Object

variable.member
(e.g.)
b = str.length();
d.set(2000, 12, 1);
94
Exercise


Build a NetBeans project called Test.
Declare MyDate class, which has members
like:






Three int member variables; year, month, day.
Method set(int y, int m, int d), which sets values of
year, month, and day.
Method print( ), which prints out like "2008/9/12".
In main method, declare and create an object
for MyDate class.
In main method, set the date as Sep. 12, 2008.
In main method, print out the date.
95
Classes : Members



Constants
Variables
Methods
96
Classes : Constants
Named literal
 Keyword: final
 Must be initialized
(e.g.)

class MyCircle
{
final double pi = 3.141592;
final int CENTER = 0;
}
97
Exercise


Build a NetBeans project called Test.
Declare MyCircle class, which has members
like:



Method set(double r), which sets the radius of the
circle.
Method getArea( ), which returns the area of the
circle.
Test the MyCircle class in main method.



Declare a circle.
Set the radius of the circle as 3.
Print out the area of the circle.
98
Classes : Variables
Instance variables
(e.g.)
class date
{
String s;
}

Class variables
(e.g.)
class date
{
static String s;
static final int pi = 3.141592;
}
…
date.s = "ddd";
r = 2 * date.pi;

99
Classes : Methods (1)


Instance Methods
return-type function-name(args)
{
...
return(…);
}
Class Methods
static return-type function-name(args)
{
...
return(…);
}
…
class-name.function-name(…);
100
Classes : Methods (2)
(e.g.)
class MyDate
{
void set(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
int[ ] get(int n)
{
int r = new int[100];
…
return(r);
}
}
101
Classes : Method main
Starting(Entry) point of a program
 public static void main(String[ ] args)
(e.g.)

class Hello
{
public static void main(String[ ] args)
{
System.out.println("Hello, world");
}
}
102
Exercise


Build a NetBeans project called Test.
Declare MyPoint class, representing a coordinate, which has members
like:



double variables m_x and m_y
Methods set(double, double), getX( ), and getY( )
Method multiplyTo(MyPoint)



Method compareTo(MyPoint)
Method print( )


Format: (x, y)
Method String toString( )


U * V = (xu * xv, yu * yv)
Format: (x, y)
Test the MyPoint class in main method.




Declare two points a and b.
Set a as (2, 3) and b as (4, 5).
Multiply a and b and print out the result.
Compare a and b and print out the result.
103
Exercise

Merge the two classes, Main and
MyPoint from the previous exercise, into
the Main class.
104
Homework

Build a program to find prime numbers
from 1 through 10,000.

Have to declare and use a method boolean
isPrime(int n) in the Main class.
105
Classes : this
To refer the object itself
 Class methods(static) can not use "this".
(e.g.)

t = this.x;
this.resetData(this);
return(this);
106
Classes: this

Reasons why using this

To override scope


To enhance readability


this.year = year
this.set(2008, 9, 12);
To refer the object again

set(2.3).print( );
107
Classes : Scope


Scope is an enclosing context where
values and expressions are associated.
Local variables


Instance or class variables


Only in the function
Only in the class
Local variables have priority over the
instance or class variables.
108
Classes: this
class MyCircle {
int radius;
MyCircle set(int r) {
radius = r;
return(this);
}
void print( ) {
System.out.println(radius);
}
}
109
Classes : Argument passing

Call by value


Primitive types
Call by reference


Arrays
Objects
110
An Object is a Pointer!
(e.g.)
MyDate d = new MyDate( );
MyDate t;
t = d;
t.set(1999, 11, 23);
d.set(2000, 11, 12);
111
Classes : Class Methods
Class methods can not use instance members
(constants, variables, methods).
 It is better to declare methods, which have
nothing to do with instances, as class methods.
(e.g.)

Math.sqrt(4.0);
Integer.parseInt("42");
cf.) Math m = new Math( );
m.sqrt(4.0);
112
Command-line Arguments
public static void main(String[ ] args)

args[0], args[1], …
(e.g.)
class EchoArgs
{
public static void main(String[ ] args)
{
for (int i = 0; i < args.length; i++)
{
System.out.println("Arg " + i + " : " + args[i]);
}
}
}

113
Exercise



Build a NetBeans project called Test.
Input an integer, which represents a
radius of a circle, from a command-line
argument.
Calculate and print out the area of the
circle.
114
Homework

Complete the MyDate class, so that it
can be provided as a library.
115
Session 7.
Methods
116
Methods : Overloading


Overloading allows the creation of several
functions with the same name which differ from
each other in terms of the type of the input and
the type of the output of the function.
Methods are distinguished by:


Number of arguments
Types of arguments
(e.g.)
class aClass {
int sum(int a, int b) { … }
double sum(double a, double b) { … }
}
117
Exercise


Build a NetBeans project called Test.
Declare MyPoint class, representing a coordinate, which has members
like:


double variables x and y
Overloaded Methods set





 Use Double.parseDouble
U * V = (xu * xv, yu * yv)
Method toString( )


 Not necessary thanks to implicit type conversion
Method getX( ) and getY( )
Method multiplyTo(MyPoint V)


set(int x, int y)
set(double x, double y)
set(String x, String y)
"(x, y)"
Test the MyPoint class in main method.



Declare two points a and b.
Set a as (2, 3) and b as (4, 5).
Multiply a and b and print out the result.
118
Methods : Constructors





A member function (method)
Have the same names as the classes
Have no return type
Called automatically just after the object is constructed
Constructor is also a method, so it can be overloaded.

To call another overloaded constructor, use keyword this.


this(args);
To call a constructor:

MyDate today = new MyDate(1996, 3, 21);
119
Exercise


Build a NetBeans project called Test.
Declare MyPoint class, representing a coordinate, which has members like:


double variables x and y
Overloaded constructors




Overloaded Methods set




 Use Double.parseDouble
U * V = (xu * xv, yu * yv)
Method toString( )


set(double x, double y)
set(String x, String y)
Method getX( ) and getY( )
Method multiplyTo(MyPoint V)


MyPoint( )
MyPoint(double x, double y)
MyPoint(String x, String y)
"(x, y)"
Test the MyPoint class in main method.


Declare two points a(2, 3) and b(4, 5).
Multiply a and b and print out the result.
120
Interface and Implementation


The operation (methods) should be
defined clearly and simply.
The class details should be hided from
users and be accessible only by the
pre-intended operations (methods).


Black Box
The operations (methods) defined in a
class should be able to be used without
change, even after the internal
implementation has been changed.
121
Homework

Provide a class for Bubble Sorting.
class BubbleSorting
{
private int a[ ];
public BubbleSorting( ) { … }
public BubbleSorting(int b[ ]) { … }
public void sort( ) { … }
public void print( ) { … }
}
122
Session 8.
Inheritance
123
Inheritance : Subclasses

Syntax


class subclass extends superclass
Single inheritance


Multiple inheritance is not allowed.
In other word, only one class name is allowed after the
extends keyword.
(e.g.)
class Date
{…}
class MyDate extends Date
{…}
124
Exercise


Build a NetBeans project called Test.
Declare MyDate class, representing a date, which has members like:


int variables m_year, m_month, m_day
Overloaded constructors




Method getYear( ), getMonth( ) and getDay( )
Method toString( )


"YYYY/MM/DD"
Declare MyTime class, representing a time, which is a subclass of MyDate and has members like:


int variables m_hour, m_minute, m_second
Overloaded constructors




MyTime( )
MyTime(int year, int month, int day, int hour, int minute, int second)
Method getHour( ), getMinute( ), getSecond( )
Method toString( )


MyDate( )
MyDate(int year, int month, int day)
"YYYY/MM/DD:HH:MM:SS"
Test the MyTime class in main method.


Declare a time t(2008, 10, 23, 11, 45, 50).
Print out t.
125
Inheritance : Overriding

Two kinds of overriding



Variable overriding


Variable overriding
Method overriding
Declaring a variable member having the same
name (but may have different type) with
another variable member in its superclass.
To refer the superclass variable member

super.VariableName
126
Inheritance : Overriding
class A
{
int a;
}
class B extends A
{
double a;
void f( )
{
System.out.println(a);
System.out.println(super.a);
}
}
public class Test
{
public static void main(String
args[ ])
{
B b = new B( );
b.f( );
System.out.println(b.a);
}
}
127
Inheritance : Overriding

Method overriding



To refer the superclass method


Declaring a method having the same
prototype with another method in its
superclass.
When their prototypes are different, they are
regarded as different methods to each other.
super.MethodName(args)
Method overriding is an important feature
that facilitates polymorphism in the design
of object-oriented programs.
128
Inheritance : Overriding
class Super
{
int aMethod(int a)
{…}
}
class Sub extends Super
{
int aMethod(int a)
{
…
n = super.aMethod(12);
…
}
}
129
Exercise


Build a NetBeans project called Test.
Declare MyDate class, representing a date, which has members like:


int variables m_year, m_month, m_day
Overloaded constructors




Method getYear( ), getMonth( ) and getDay( )
Method toString( )


"YYYY/MM/DD"
Declare MyTime class, representing a time, which is a subclass of MyDate and has members like:


int variables m_hour, m_minute, m_second
Overloaded constructors


MyTime( )
MyTime(int year, int month, int day, int hour, int minute, int second)

Method getHour( ), getMinute( ), getSecond( )
Method toString( )

Method test( ), which calls toString( ) and super.toString( ) consecutively and then prints out the two results.



MyDate( )
MyDate(int year, int month, int day)
"YYYY/MM/DD:HH:MM:SS"
Test the MyTime class in main method.



Declare a time t(2008, 10, 23, 11, 45, 50).
Call t.test( ).
Call t.toString( ) and print out its result.
130
Inheritance : Overriding

To call a constructor of super class


super(args)
Constructor overriding must be at the
first line of a constructor.
131
Inheritance : Overriding
class Super
{
int x;
Super(int a)
{
x = a;
}
}
class Sub extends Super
{
int y;
Sub(int a, int b)
{
x = a;
y = b;
}
}
class Super
{
int x;
Super(int a)
{
x = a;
}
}
class Sub extends Super
{
int y;
Sub(int a, int b)
{
super(a);
y = b;
}
}
132
Exercise


Build a NetBeans project called Test.
Declare MyDate class, representing a date, which has members like:


int variables m_year, m_month, m_day
Overloaded constructors




Method getYear( ), getMonth( ) and getDay( )
Method toString( )


"YYYY/MM/DD"
Declare MyTime class, representing a time, which is a subclass of MyDate and has members like:


int variables m_hour, m_minute, m_second
Overloaded constructors


MyTime( )
MyTime(int year, int month, int day, int hour, int minute, int second)
 Use super constructor here.

Method getHour( ), getMinute( ), getSecond( )
Method toString( )

Method test( ), which calls toString( ) and super.toString( ) consecutively and then prints out the two results.



MyDate( )
MyDate(int year, int month, int day)
"YYYY/MM/DD:HH:MM:SS"
Test the MyTime class in main method.



Declare a time t(2008, 10, 23, 11, 45, 50).
Call t.test( ).
Call t.toString( ) and print out its result.
133
Inheritance : Virtual Function
class Super
{
void vf(int a)
{…}
void cf( )
{ … vf(3); … }
}
class Sub extends Super
{
void vf(int a)
{…}
}
void call( …)
{
Sub x = new Sub( );
x.cf( );
Super y = x;
y.cf( );
}
134
Exercise


Build a NetBeans project called Test.
Declare MyDate class, representing a date, which has members like:


int variables m_year, m_month, m_day
Overloaded constructors




Method getYear( ), getMonth( ) and getDay( )
Method toString( )


"YYYY/MM/DD"
Declare MyTime class, representing a time, which is a subclass of MyDate and has members like:


int variables m_hour, m_minute, m_second
Overloaded constructors




MyTime( )
MyTime(int year, int month, int day, int hour, int minute, int second)
Method getHour( ), getMinute( ), getSecond( )
Method toString( )


MyDate( )
MyDate(int year, int month, int day)
"YYYY/MM/DD:HH:MM:SS"
Test the MyDate and MyTime class in main method.




Declare and create an array of MyDate, A, which has 10 elements.
Declare and create five MyDate objects and store them to A.
Declare and create five MyTime objects and store them to A.
For each element of A, call toString( ) and print out the result.
135
Exercise: YData (1)


Declare a class YDataInteger, which
has an int variable named value.
Declare a constructur YDataInteger(int
value), which sets the member value as
the argument value.
136
Answer: YData (1)
class YDataInteger
{
int value;
YDataInteger(int value)
{
this.value = value;
}
}
137
Exercise: YData (2)


Override two methods void set( ) and void
set(int value) in YDataInteger class, where
void set( ) sets value as zero and void set(int
value) sets value as argument value.
Avoiding redundancy is essential in this
exercise.
138
Answer: YData (2)
class YDataInteger
{
int value;
YDataInteger(int value)
{
set(value);
}
void set(int value)
{
this.value = value;
}
void set( )
{
set(0);
}
}
139
Exercise: YData (3)


Declare a constructor YDataInteger( ),
which sets value as zero.
Again, avoiding redundancy is essential
in this exercise, so the constructor
YDataInteger( ) must call the
constructor YDataInteger(int value).
140
Answer: YData (3)
class YDataInteger
{
int value;
YDataInteger(int value)
{
set(value);
}
YDataInteger( )
{
this(0);
}
void set(int value)
{
this.value = value;
}
void set( )
{
set(0);
}
}
141
Exercise: YData (4)




Declare a class YDataDouble, which has a double variable named
value.
Declare a constructur YDataDouble(double value), which sets the
member value as the argument value.
Override two methods void set( ) and void set(double value) in
YDataDouble class, where void set( ) sets value as 0.0 and void
set(double value) sets value as argument value. Avoiding redundancy
is essential in this exercise.
Declare a constructor YDataDouble( ), which sets value as 0.0. Again,
avoiding redundancy is essential in this exercise, so the constructor
YDataDouble( ) must call the constructor YDataDouble(double value).
142
Answer: YData (4)
class YDataDouble
{
double value;
YDataDouble(double value)
{
set(value);
}
YDataDouble( )
{
this(0.0);
}
void set(double value)
{
this.value = value;
}
void set( )
{
set(0.0);
}
}
143
Exercise: YData (5)



Declare a class YData which is the super
class of YDataInteger and YDataDouble.
Update the programs for YDataInteger and
YDataDouble.
Declare a virtual function void print( ) for
YDataInteger, YDataDouble and YData,
where void print( ) standard-outputs int
value and double value at YDataInteger
and YDataDouble respectively.
144
Answer: YData (5)
class YData
{
void print( ) { }
}
class YDataInteger extends YData
{
int value;
YDataInteger(int value)
{
set(value);
}
YDataInteger( )
{
this(0);
}
void set(int value)
{
this.value = value;
}
void set( )
{
set(0);
}
void print( )
{
System.out.println(value);
}
}
class YDataDouble extends YData
{
double value;
YDataDouble(double value)
{
set(value);
}
YDataDouble( )
{
this(0.0);
}
void set(double value)
{
this.value = value;
}
void set( )
{
set(0.0);
}
void print( )
{
System.out.println(value);
}
}
145
Exercise: YData (6)

Declare public String toString( ).
146
Answer: YData (6)
class YData
{
}
class YDataInteger extends YData
{
int value;
YDataInteger(int value)
{
set(value);
}
YDataInteger( )
{
this(0);
}
void set(int value)
{
this.value = value;
}
void set( )
{
set(0);
}
public String toString( )
{
return(Integer.toString(value));
}
}
class YDataDouble extends YData
{
double value;
YDataDouble(double value)
{
set(value);
}
YDataDouble( )
{
this(0.0);
}
void set(double value)
{
this.value = value;
}
void set( )
{
set(0.0);
}
public String toString( )
{
return(Double.toString(value));
}
}
147
Example

Regression

class YRegression


class YLogisticRegression
class YMatrix




class YMatrixM
class YTransposedMatrix
class YXMatrix
class YLogisticXViMatrix
148
Session 9.
Inner Classes
149
Inner Classes : Categories




Nested Classes
Inner Classes
Local Classes
Anonymous Classes
150
Nested Classes
public class NestedClass
{
static int i = 100;
static class Nested1
{
public int getInt( )
{ return(i); }
}
public static void main(String args[ ])
{
Nested1 nested1 = new Nested1( );
System.out.print(nested1.getClass( ));
System.out.print("'s class method getInt( ) : ");
System.out.println(nested1.getInt( ));
}
}
151
Inner Classes
public class InnerClass
{
int i;
public InnerClass(int i)
{ this.i = i; }
public class Inner1
{
public int getInt( )
{ return(i); }
}
public static void main(String args[ ])
{
InnerClass inner = new InnerClass(100);
InnerClass.Inner1 inner1 = inner.new Inner1( );
System.out.print(inner1.getClass( ));
System.out.print("'s class method getInt( ) : ");
System.out.println(inner1.getInt( ));
}
}
152
Local Classes
public class LocalClass
{
public void testLocalClass(final int i)
{
class Test
{
public void callMe( )
{
System.out.println("Variable i : " + i);
System.out.println(getClass( ));
}
}
Test test = new Test( );
test.callMe( );
}
public static void main(String args[ ])
{
LocalClass local = new LocalClass( );
local.testLocalClass(100);
}
}
153
Anonymous Classes
public class AnonymousClass
{
public void testAnonymousClass(final int i)
{
Object obj = new Object( )
{
public String toString( )
{
System.out.println(getClass( ));
System.out.println(AnonymousClass.this.getClass( ));
return(super.toString( ));
}
};
System.out.println(obj);
}
public static void main(String args[ ])
{
AnonymousClass anonymous = new AnonymousClass( );
anonymous.testAnonymousClass(100);
}
}
154
Session 10.
Packages
155
Packages


A Java package is a mechanism for
organizing Java classes into namespaces.
Merits


Modularize several classes into a unit
Identify class names without ambiguity


A package provides a unique namespace for the
types it contains.
Enhance access control

Classes in the same package can access each
other's protected members.
156
Packages: Declarations

Syntax
package dir1.dir2…package-name;
A package statement must be at the top of a
Java source file except comments.
 The directory name in a package statement
must be consistent with the path of the Java
source file.
(e.g.)

Source code of D.java
package a.b.c;
…
Path of D.java
a/b/c/D.java
157
Packages: Usage

import


import package.Class-name;
import package.*;
(e.g.)
import java.util.Vector;
Vector v = new Vector( );

Full Class Name

package.Class-name
(e.g.)
Vector v = new Vector( );
java.util.Vector v = new java.util.Vector( );
158
Exercise


Build a NetBeans project called Test.
Declare MyDate class in mylib/date package, representing a date, which has members like:


int variables m_year, m_month, m_day
Overloaded constructors




Method getYear( ), getMonth( ) and getDay( )
Method toString( )


"YYYY/MM/DD"
Declare MyTime class in mylib/time package, representing a time, which is a subclass of MyDate
and has members like:


int variables m_hour, m_minute, m_second
Overloaded constructors




MyTime( )
MyTime(int year, int month, int day, int hour, int minute, int second)
Method getHour( ), getMinute( ), getSecond( )
Method toString( )


MyDate( )
MyDate(int year, int month, int day)
"YYYY/MM/DD:HH:MM:SS"
Test the MyDate and MyTime class in main method.




Declare and create an array of MyDate, A, which has 10 elements.
Declare and create five MyDate objects and store them to A.
Declare and create five MyTime objects and store them to A.
For each element of A, call toString( ) and print out the result.
159
Exercise



Build a NetBeans project called Use.
Add the JAR file from the above exercise to its library.
Test the MyDate and MyTime class in main method.




Declare and create an array of MyDate, A, which has 10
elements.
Declare and create five MyDate objects and store them to A.
Declare and create five MyTime objects and store them to A.
For each element of A, call toString( ) and print out the
result.
160
Packages



Where can we find the location of packages?
 CLASSPATH
 Full class names
 import statements
Avoiding duplication of class names in different packages
 If class names are different, use their class names only.
 If class names are same, use their full class names.
Naming convention for packages
 Reverse the Internet domain name
 (e.g.)
 Domain name: yonsei.ac.kr
 Package name: kr.ac.yonsei.dir1.dir2.…package-name
161
Session 11.
Modifiers
162
Modifiers






public, protected, private
 Access control for classes, methods and variables
static
 Declaring classes, methods and variables
final
 Suppress inheritance of classes, methods and
variables
abstract
 Declaring abstract classes and abstract methods
synchronized, volatile
 Used for multi-thread
transient
 Exclude a object from serialization
163
Access Control of Members
public
protected
Default
private
Same class
Yes
Yes
Yes
Yes
Different class in
same package
Yes
Yes
Yes
No
Different class in
different package
Yes
No
No
No
Subclass in same
package
Yes
Yes
Yes
No
Subclass in
different package
Yes
Yes
No
No
164
Exercise

The previous table about access control
is incorrect. Correct the table by trial
and error.
165
Access Control of Classes
public
protected
Default
private
Same file
Yes
Yes
Yes
Yes
Same package
Yes
Yes
Yes
No
Different package
Yes
No
No
No
166
Abstract Classes and Methods

Abstract Methods

Declarations

public abstract return-type method-name(args);
Methods without body (implementation)

Role of defining shared activities or attributes among subclasses
(e.g.)

public abstract int sum(int[ ] a);

Abstract Classes

Declarations

public abstract class class-name { … }
(e.g.)
public abstract class ALib
{
public abstract int sum(int[ ] a);
…
}


All classes which have one or more abstract methods must be abstract classes.
It is better to use interface if all methods in a class are abstract methods.
167
Exercise

For the previous exercise about YData,
declare the method print( ) as an
abstract method.
168
Answer: YData
public abstract class YData
{
public abstract void print( );
}
public class YDataInteger extends YData
{
private int value;
public YDataInteger(int value)
{
set(value);
}
public YDataInteger( )
{
this(0);
}
public void set(int value)
{
this.value = value;
}
public void set( )
{
set(0);
}
public void print( )
{
System.out.println(value);
}
}
public class YDataDouble extends YData
{
private double value;
public YDataDouble(double value)
{
set(value);
}
public YDataDouble( )
{
this(0.0);
}
public void set(double value)
{
this.value = value;
}
public void set( )
{
set(0.0);
}
public void print( )
{
System.out.println(value);
}
}
169
Session 12.
Interface
170
Multiple/Single Inheritance

Limit of single inheritance


Limit of multiple inheritance



Poor expressiveness
Complexity
Ambiguity
Java

Single inheritance


For simplicity
Interface

For expressiveness
171
Interface: Declarations
Syntax
public interface interface-name
{
constants
methods
}

All methods in interfaces are automatically declared as public and
abstract.

So, the methods can not be declared as private or protected.

All variables in interfaces are automatically declared as public,
static, and final.
(e.g.)
public interface Growable
{
void growIt( );
void growItBigger( );
}

172
Interface: Implementation
Syntax
public class class-name implements interface1, interface2, …
{
…
}

The implementation class must implement all the methods declared in
its interfaces.

Java classes can implement multiple interfaces, which results in
multiple inheritance.
(e.g.)
public class Aclass implments Growable
{
int age;
void growIt( ) { … }
void growItBigger( ) { … }
int getAge( ) { … }
…
}

173
Interface: Usage


The effect of interfaces is that it forces
implementation of abstract methods.
Interfaces are treated like classes when
they are used as:
Variables
 Arguments
(e.g.)

Growable aGrowable = new Aclass( );
public int setGrowable(Growable g) { … }
174
Interface: Inheritance

Syntax

public interface sub-interface extends superinterface1, super-interface2, …
Multiple inheritance are allowed for interfaces.
(e.g.)

public interface SubGrowable extends Growable
{
…
}
175
Session 13.
Exception Handling
176
Steps for Exception Handling




Define an exception class
Throw
[Pass] (optional)
Catch [& pass & catch …]
177
Exception: Classes
Exception
IOException
FileNotFoundException
RuntimeException
ArithmeticException
NullPointerException
178
Exception: Exception Class
Every exception class should be a subclass
of the Exception class.
(e.g.)

public class AnException extends IOException
{
AnException( ) { … }
AnException(String msg) { super(msg); }
…
}
179
Exercise


Build a NetBeans project called Test.
Declare InvalidValueException which is
a subclass of RuntimeException.
180
Exception: Throwing

Syntax
public type method(args) throws AnException
{
…
AnException e = new AnException(args);
throw e;
…
}
181
Exercise


(Continue from the previous exercise.)
Declare MyDate class which has:


int members m_year, m_month, and
m_day
Method set(int year, int month, int day),
which throws InvalidValueException when
month or day are invalid: that is, month < 1,
month > 12, day < 1, or day > 31.
182
Exception: Catching

Syntax
try
{…}
catch (AnException e1)
{…}
catch (AnOtherException e2)
{…}
…
catch (Exception e)
{…}
finally
{…}

The catches should be in order of which
exceptions are listed from specific
exceptions to more general exceptions.
183
Exercise


(Continue from the previous exercise.)
Declare MyTime class, which is a
subclass of MyDate, and which has:


int members m_hour, m_minute, and
m_second
Method set(int year, int month, int day, int
hour, int minute, int second), which calls
set method in MyDate and catches the
InvalidValueException.
184
Exception: Passing

Syntax
public type method(args) throws
AnException
{
…
Methods which throw AnException
…
}
185
Exercise


(Continue from the previous exercise.)
Declare MyTime class, which is a subclass of
MyDate, and which has:



int members m_hour, m_minute, and m_second
Method set(int year, int month, int day, int hour, int
minute, int second), which calls set method in
MyDate and passes the InvalidValueException.
Program public static void main(String args[])
which creates an instance t of MyTime class,
calls t.set(…), and catches the
InvalidValueException.
186
Exception: Catching &
Passing

Syntax
public type method(args) throws AnException
{
…
try
{…}
catch (AnException e)
{
…
e.printStackTrace();
…
throw e;
}
}
187
Exercise


(Continue from the previous exercise.)
Declare MyTime class, which is a subclass of
MyDate, and which has:



int members m_hour, m_minute, and m_second
Method set(int year, int month, int day, int hour, int
minute, int second), which calls set method in MyDate
and catches and passes the InvalidValueException.
Program public static void main(String args[]) which
creates an instance t of MyTime class, calls
t.set(…), and catches the InvalidValueException.
188
Exception: Catching or
Passing

Unchecked exception


RuntimeException and its subclasses do
NOT need to be caught or passed.
Checked exception

Other exceptions including IOException
and their subclasses MUST be caught or
passed.
189
Exception: Methods


String getMessage( )
void printStackTrace( )
190
Exercise


(Continue from the previous exercise.)
Declare MyTime class, which is a subclass of
MyDate, and which has:



int members m_hour, m_minute, and m_second
Method set(int year, int month, int day, int hour, int
minute, int second), which calls set method in MyDate,
catches the InvalidValueException, calls
printStackTrace( ) for the InvalidValueException, and
then throws the InvalidValueException.
Program public static void main(String args[]) which
creates an instance t of MyTime class, calls
t.set(…), and catches the InvalidValueException.
191
Exception: Inheritance
Overriding methods of a class must throw less
exceptions than its superclasses.
(e.g.)

public class RadioPlay
{
public void start( ) throws Aexception { … }
}
Public class StereoPlay extends RadioPlay
{
public void start( ) { … }
}
192
Session 14.
Stream
193
Stream




A passage of data between a program and other data sources
or sinks.
Input stream sends data from a data source to the program,
while output stream sends data from the program to a data sink.
Stream is a concept to unify reading from and writing to storage
devices like main memory, discs, CD-ROM, networks, etc.
Java Streams

Byte Stream


Character Stream (supports Unicode)


Reader, Writer
Bridge from byte streams to character streams


InputStream, OutputStream
InputStreamReader, OutputStreamWriter
import java.io.*
194
Byte Stream

Input






Output






InputStream( )
FileInputStream(File file) / FileInputStream(String fileName)
BufferedInputStream(InputStream in)
DataInputStream(InputStream in)
ObjectInputStream(InputStream in)
OutputStream( )
FileOutputStream(File file, [boolean append]) / FileOutputStream(String
fileName, [boolean append])
BufferedOutputStream(OutputStream out)
DataOutputStream(OutputStream out)
ObjectOutputStream(OutputStream out)
Input & Output

RandomAccessFile(File file, String mode) / RandomAccessFile(String fileName,
String mode)
195
Character Stream

Input







Reader( )
FileReader(File file) / FileReader(String fileName)
BufferedReader(Reader in)
LineNumberReader(Reader in)
StreamTokenizer(Reader r)
StringReader(String s)
Output





Writer( )
FileWriter(File file, [boolean append]) / FileWriter(String fileName)
BufferedWriter(Writer out)
PrintWriter(File file) / PrintWriter(OutputStream out) /
PrintWriter(Writer out) / PrintWriter(String fileName)
 PrintStream
StringWriter(String s)
196
Bridge from Byte Streams to
Character Streams

Input


InputStreamReader(InputStream in)
Output

OutputStreamWriter(OutputStream out)
(e.g.)
try {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String str = reader.readLine();
System.out.println(str);
int i = Integer.parseInt(str);
System.out.println(i * 23);
} catch (IOException e) { }
197
File Class











File(String filename)
boolean exists( )
int length( )
long lastModified( )
boolean isDirectory( )
booealn isFile()
void mkdir( )
void renameTo(File)
void delete( )
String getAbsolutePath( )
String getCanonicalPath( )










String getName( )
String getParent( )
File getParentFile( )
String getPath( )
String[] list( )
File[ ] listFiles( )
static File[ ] listRoots( )
static File
createTempFile(String
head, String ext)
void deleteOnExit( )
String toURI( )
198
Byte Stream


abstract class InputStream

int read( ) throws IOException
 Return – input byte / -1(End of stream)

int read(byte buf[ ]) throws IOException
  read(buf, 0, buf.length)

int read(byte buf[ ], int start, int len) throws IOException

close( )
abstract class OutputStream

void write(int data) throws IOException

int write(byte buf[ ]) throws IOException
  write(buf, 0, buf.length)

int write(byte buf[ ], int start, int len) throws IOException

close( )

flush( )
199
Buffered Stream


BufferedInputStream extends FilterInputStream

BufferedInputStream(InputStream in)

BufferedInputStream(InputStream in, int buffersize)

int read( ) throws IOException

Return – input byte / -1(End of stream)

int read(byte buf[ ]) throws IOException

 read(buf, 0, buf.length)

int read(byte buf[ ], int start, int len) throws IOException

close( )

mark(int limit)

reset( )
BufferedOutputStream extends FilterOutputStream

BufferedOutputStream(OutputStream out)

BufferedOutputStream(OutputStream out, int buffersize)

void write(int data) throws IOException

int write(byte buf[ ]) throws IOException

 write(buf, 0, buf.length)

int write(byte buf[ ], int start, int len) throws IOException

close( )

flush( )
200
Buffered Stream
try
{
FileInputStream fis = new FileInputStream("test.dat");
BufferedInputStream bis = new BufferedInputStream(fis);
…
bis.read( );
bis.read(buf);
…
bis.close( );
}
catch (IOException e) { }
201
Data Stream



DataInputStream extends FilterInputStream

DataInputStream(InputStream in)

boolean readBoolean( )

byte readByte( )

double readDouble( )

float readFloat( )

int readInt( )

long readLong( )

short readShort( )

int readUnsignedByte( )

int readUnsignedShort( )
DataOutputStream extends FilterOutputStream

DataOutputStream(OutputStream out)

void writeBoolean(boolean)

void writeByte(byte)

void writeDouble(double)

void writeFloat(float)

void writeInt(int)

void writeLong(long)

void writeShort(short)
End of stream

EOFException
202
Data Stream
try
{
FileOutputStream fos = new FileOutputStream("test.dat");
DataOutputStream dos = new DataOutputStream(fos);
…
dos.writeInt(20);
dos.writeDouble(1.2);
…
dos.close( );
}
catch (EOFException eof) { dos.close( ); }
catch (IOException e) { }
203
Buffered & Data Stream
try {
FileInputStream fis = new FileInputStream("test.dat");
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
…
try {
…
int i = dis.readInt( );
…
}
catch (EOFException eof)
{ dis.close( ); }
…
}
catch (IOException e) { }
204
Character Stream


abstract class Reader

int read( ) throws IOException
 Return – input byte / -1(End of stream)

int read(char buf[ ]) throws IOException
  read(buf, 0, buf.length)

int read(char buf[ ], int start, int len) throws IOException

close( )
abstract class Writer

void write(char buf[ ]) throws IOException
  write(buf, 0, buf.length)

void write(char buf[ ], int start, int len) throws IOException

void write(int c) throws IOException

void write(String str) throws IOException

void write(String str, int start, int len) throws IOException

close( )

flush( )
205
Buffered Reader/Writer

BufferedReader extends Reader





BufferedReader(Reader in)
BufferedReader(Reader in, int buffersize)
String readLine( ) throws IOException
long skip(long n) throws IOException
BufferedWriter extends Writer



BufferedWriter(Writer out)
BufferedWriter(Writer out, int buffersize)
void newLine( ) throws IOException
206
Buffered Reader/Writer
try
{
String s;
FileReader fr = new FileReader("test.dat");
BufferedReader br = new BufferedReader(fr);
while ((s = br.readLine()) != null)
{
System.out.println(s);
}
br.close( );
}
catch (Exception e) { }
207
PrintWriter

PrintWriter extends Writer






PrintWriter(File file)
PrintWriter(String fileName)
PrintWriter(OutputStream out)
PrintWriter(Writer out, [boolean autoFlush])
PrintWriter printf(String format, Object...
args)
(Note) \n, \r\n
208
PrintWriter
try
{
int i,s;
PrintWriter w = new PrintWriter("test.txt");
for (i = 0, s = 0; i < 100; i++)
{
s += i;
w.printf("%d - %d\r\n", i, s);
}
w.close();
}
catch (IOException e) { }
209
Exercise


Build a NetBeans project called Test.
Copy a text file "a.txt" to another text file
"b.txt".
210
Session 15.
API
211
API Specification
212
Class String










char charAt(int index)
int compareTo(String anotherString)
int compareToIgnoreCase(String str)
boolean equals(Object anObject)
boolean equalsIgnoreCase(String anotherString)
static String format(String format, Object... args)
boolean isEmpty()
int length()
String substring(int beginIndex, int endIndex)
String trim()
213
Exercise


Build a NetBeans project called Test.
Print out a date in the format of
"MM/DD/YYYY".
214
Class Integer









Integer(int value)
int compareTo(Integer anotherInteger)
boolean equals(Object obj)
int intValue()
long longValue()
short shortValue()
double doubleValue()
static int parseInt(String s)
static int parseInt(String s, int radix)
215
Exercise


Build a NetBeans project called Test.
Parse a string "123" to get int 123.
216
Class Double









Double(double value)
int compareTo(Double anotherDouble)
boolean equals(Object obj)
double doubleValue()
float floatValue()
int intValue()
long longValue()
short shortValue()
static double parseDouble(String s)
217
Exercise


Build a NetBeans project called Test.
Parse a string "12.3" to get double 12.3.
218
Class Long










Long(long value)
int compareTo(Long anotherLong)
boolean equals(Object obj)
long longValue()
int intValue()
short shortValue()
double doubleValue()
float floatValue()
static long parseLong(String s)
static long parseLong(String s, int radix)
219
Exercise


Build a NetBeans project called Test.
Parse a string "123" to get long 123L.
220
Class Vector<E>








boolean add(E e)
void add(int index, E element)
E set(int index, E element)
E get(int index)
int size()
boolean contains(Object o)
boolean isEmpty()
void clear()
221
Exercise




Build a NetBeans project called Test.
Declare and create an object aString
which is a vector of strings.
Add strings "a", "b", "c", and "d" to
aString.
Print out the elements of aString.
222
Class Stack<E> extends
Vector<E>



E peek()
E pop()
E push(E item)
223
Exercise




Build a NetBeans project called Test.
Declare and create an object kString
which is a stack of strings.
Push strings "a", "b", "c", and "d" to
aString.
Print out each element of aString by
popping.
224
Class Hashtable<K,V>






V get(Object key)
V put(K key, V value)
int size()
boolean isEmpty()
void clear()
Enumeration<K> keys()
225
Exercise




Build a NetBeans project called Test.
Declare and create an object hName
which is a hashtable of String key and
String value.
Add key-value pairs of (A, a), (B, b), (C,
c), and (D, d)
Get and print out the value for key B.
226
Class Calendar



Calendar Calendar.getInstance()
 current time
void set(int year, int month, int date, int hourOfDay, int minute, int
second)
int get(int field)












YEAR
MONTH
DAY_OF_MONTH
DAY_OF_WEEK
DAY_OF_YEAR
AM_PM
HOUR
MINUTE
SECOND
MILLISECOND
Date getTime()
void setTime(Date date)
227
Class GregorianCalendar
extends Calendar




GregorianCalendar()  current time
GregorianCalendar(int year, int month,
int dayOfMonth, int hourOfDay, int
minute, int second)
boolean isLeapYear(int year)
void add(int field, int amount)
228
Formatting Calendar
import java.util.*;
import java.text.*;
Calendar c = Calendar.getInstance();
DateFormat df = new
SimpleDateFormat("yyyy/MM/dd:HH:m
m:ss");
System.out.println(df.format(c.getTime()));
229
Parsing Calendar
import java.util.*;
import java.text.*;
try {
Calendar c = Calendar.getInstance();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd:HH:mm:ss");
Date d = df.parse("2010/03/23:11:23:25");
c.setTime(d);
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
System.out.println(df1.format(c.getTime()));
} catch (Exception e) {
e.printStackTrace();
}
230
Exercise



Build a NetBeans project called Test.
Print out the current time.
Print out the time after 13 hours and 55
minutes.
231
Session 16.
Serialization
232
Serializtion이란?


객체 직렬화
이전까지 파일이나 다른 스트림으로 객
체를 기록하기 위해 단순 노동을 했어야
했던 것을 손쉽게 저장할 수 있도록 Java
에 추가된 도구
233
Default Serialization (1)
public class A implements Serializable
{
int stat;
transient int temp;
public A( … ) { … }
…
}
• java.io.Serializable 인터페이스는 메소드나 필드를 갖
고 있지 않으며, 단지 이 객체가 Serialize해도 괜찮은
지 아닌지만 판단하도록 표시
• transient 한정사는 Serialization에 포함하지 말 것을
표시
234
Default Serialization (2)
import java.io.*;
…
A a = new A( … );
…
try
{
FileOutputStream fout = new FileOutputStream("filename");
ObjectOutputStream objout = new ObjectOutputStream(fout);
objout.writeObject(a);
objout.close( );
}
catch (Exception e) { }
235
Default Serialization (3)
import java.io.*;
…
A a;
try
{
FileInputStream fin = new FileInputStream("filename");
ObjectInputStream objin = new ObjectInputStream(fin);
a = (A)objin.readObject( );
objin.close( );
}
catch (Exception e) { }
236
Overriding Serialization (1)




private void writeObject(java.io.ObjectOutputStream
out) throws IOException;
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
out.defaultWriteObject( );
 자동 Serialization의 대상인 멤버들을 Serialize한다.
in.defaultReadObject( );
 자동 Serialization의 대상인 멤버들을 Serialize한다.
237
Overriding Serialization (2)
import java.io.*;
public class A implements Serializable
{
int year;
public A(int y)
{
year = y;
}
private void writeObject(ObjectOutputStream out) throws IOException
{
//out.defaultWriteObject( );
out.writeInt(year);
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException
{
//in.defaultReadObject( );
year = in.readInt( );
}
}
238
Session 17.
Multi-threading
239
Process & Thread

Process



운영체제가 관리하는 작업의 단위
프로그램 실행이란 프로세스를 만들어서 사
용하는 것
Thread

하나의 프로세스에 속하면서 프로세스가 가
지고 있는 자원들을 다른 Thread와 공유
240
Multi-threading (1)

Thread 클래스 확장


public class A extends Thread
Runnable 인터페이스 구현


public class A implements Runnable
public void run( )
(Note) class Thread implements Runnable
241
Multi-threading (2)
class ThreadRun implements Runnable
{
public void run( )
{
…
}
}
public class A
{
transient Thread m_threadRun = null;
…
public void MultiThreading( )
{
…
if (m_threadRun == null || !m_threadRun.isAlive( ))
{
m_threadRun = new Thread(new ThreadRun( ));
m_threadRun.start( );
}
…
}
}
242
Priority

void setPriority(int priority)
priority의 값이 클 수록 높은 우선순위를 가짐
 priority의 값은 MAX_PRIORITY보다 클 수 없음
 public static final int MAX_PRIORITY = 10;
 public static final int MIN_PRIORITY = 1;
 public static final int NORM_PRIORITY = 5;
(e.g.)

m_threadRun.setPriority(Thread.MIN_PRIORITY + 3);

int getPriority( )
243
Synchronization (1)


같은 자원에 서로 다른 Thread가 동시에
접근할 때의 문제점 해결
synchronized 한정사 사용


한 Thread만이 synchronized Block을 수행
할 수 있음
형식


synchronized type method(…) { … }
… synchronized (object) { … }
244
Synchronization (2)
public class ThreadTest implements Runnable
{
static int count;
public void run( )
{
for (int i = 0; i < 5; i++)
{
synchronized(ThreadTest.class)
{
counter( );
}
try
{
Thread.sleep(500);
}
catch (InterruptedException e) { }
}
}
public void counter( )
{
System.out.println(Thread.currentThread( ).getName( ) + " : " + count);
count++;
}
public static void main(String args[ ])
{
Thread t1 = new Thread(new ThreadTest( ));
Thread t2 = new Thread(new ThreadTest( ));
t1.start( );
t2.start( );
}
}
245
Thread Status

Useful methods


Do NOT use


start( ), sleep(long milisec), sleep(long milisec, int
nanosec)
yield( ), destroy( ), stop( ), resume( ), suspend( )
sleep( ) throws InterruptedException



다른 Thread들이 작업할 수 있도록 이 Thread를 잠
시 쉬게 하는 메소드
m_thread.sleep(100);
m_thread.sleep(100, 250);
246
Session 18.
Networking
247
TCP/IP
Server
Package
Class & Methods
Client
import java.io.*;
import java.net.*;
import java.io.*;
import java.net.*;
ServerSocket(int port)
Socket accept( );
Socket(String host, int port)
InputStream getInputStream( );
OutputStream getOutputStream( );
void close( );
UnknownHostException
Exceptions
248
Example of Server
import java.io.*;
import java.net.*;
try
{
ServerSocket serverSocket = new ServerSocket(80);
Socket clientConn = serverSocket.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(clientConn.getInputStream()));
PrintWriter output = new PrintWriter(clientConn.getOutputStream(), true);
String request;
request = input.readLine();
System.out.println(request);
output.println("HTTP/1.1 200 OK\n\n<HTML><BODY>a</BODY></HTML>");
output.close();
input.close();
clientConn.close();
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Failed I/O: " + e);
System.exit(1);
}
249
Example of Client
import java.io.*;
import java.net.*;
try
{
Socket socket = new Socket("dragon.yonsei.ac.kr", 80);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
output.println("GET /~yusong/index.html HTTP/1.1\n");
String response;
response = input.readLine();
System.out.println(response);
output.close();
input.close();
socket.close();
}
catch (UnknownHostException e)
{
System.err.println("Unknown host: " + e);
System.exit(1);
}
catch (IOException e)
{
System.err.println("Failed I/O: " + e);
System.exit(1);
}
250
HTTP
import java.net.*;
Import java.io.*;
public URL(String fullURL) throws MalformedURLException
public InputStream openStream( ) throws IOException
public URLConnection openConnection( ) throws IOException
public abstract HttpURLConnection(URL url)
public void setDoOutput(boolean dooutput)
public OutputStream getOutputStream( ) throws IOException
public String getHeaderField(String name)
public InputStream getInputStream( ) throws IOException
251
Example of Web Browser
import java.io.*;
import java.net.*;
try
{
URL url = new URL("http://dragon.yonsei.ac.kr/~yusong/");
BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream()));
String l;
while ((l = input.readLine()) != null)
{
System.out.println(l);
}
}
catch (IOException e)
{
System.err.println("Failed I/O: " + e);
System.exit(1);
}
252
Example of Web Browser
try
{
URL url = new URL("http://localhost/default.asp");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
// Request
urlConnection.setRequestMethod("POST");
urlConnection.setFollowRedirects(true);
urlConnection.setDoOutput(true);
PrintWriter output = new PrintWriter(urlConnection.getOutputStream(), true);
output.println("a=b&c=d");
// Response
String res = urlConnection.getResponseMessage();
System.out.println(res);
String enc = urlConnection.getContentType();
System.out.println(enc);
BufferedReader input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String l;
while ((l = input.readLine()) != null)
{
System.out.println(l);
}
urlConnection.disconnect();
}
catch (IOException e)
{
System.err.println("Failed I/O: " + e);
System.exit(1);
}
253
Session 19.
JDBC
254
JDBC


Java Database Connectivity
DB 프로그래밍 순서



데이터베이스 생성
데이터베이스 테이블 생성 (필요에 따라)
데이터베이스 연결 설정


e.g. ODBC
JDBC 프로그래밍
255
데이터베이스 및 테이블 생성

데이터베이스 생성



MS Access
*.mdb
데이터베이스 테이블 생성


Table design
Data 입력
256
데이터베이스 연결 설정
데이터베이스 연결 설정
데이터베이스 연결 설정
데이터베이스 연결 설정
데이터베이스 연결 설정
데이터베이스 연결 설정
데이터베이스 연결 설정
JDBC 프로그래밍
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection
("jdbc:odbc:ydsn", "user", "password");
Statement stmt = conn.createStatement();
stmt.execute(query);
ResultSet rs = stmt.getResultSet();
…
rs.close();
stmt.close();
conn.close();
JDBC 프로그래밍 예제 (1)
String DB_URL = "jdbc:odbc:ydsn";
String DB_USER = "";
String DB_PASSWORD= "";
Connection conn;
Statement stmt;
ResultSet rs;
String query = "SELECT * FROM customer";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
stmt = conn.createStatement();
stmt.execute(query);
rs = stmt.getResultSet();
JDBC 프로그래밍 예제 (2)
while (rs.next())
{
System.out.print(rs.getString("name") + " / ");
System.out.print(rs.getString("username") + " / ");
System.out.print(rs.getString("password") + "\n");
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Appendix
267
Names for Symbols
Name
Name
~
Tilde
'
Single quotation mark, Apostrophe
`
Grave
"
Double quotation mark
!
Exclamation mark
/
Slash, Virgule
@
At sign, Commercial at
\
Back slash
#
Number sign, Crosshatch, Pound sign
|
Vertical bar
$
Dollar sign
,
Comma
%
Percent sign
.
Dot, Period, Full stop
^
Hat sign, Circumflex
?
Question mark
&
Ampersand
()
(Left / Right) parenthesis
*
Asterisk, Star sign
{}
(Left / Right) braces, curved parenthesis
–
Dash, Hyphen, Minus sign
[]
(Left / Right) bracket, squared parenthesis
_
Underscore, Underline
<>
(Left / Right) angle bracket, pointed brackets
+
Plus sign

(Left / Right) [unidirectional] arrows
=
Equal sign

Bidirectional arrow
:
Colon
;
Semicolon
268