268
1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Embed Size (px)

Citation preview

Page 1: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

1

Java

Dr. Yong Uk Song

Dept. of MIS

Yonsei University Wonju Campus

Page 2: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

2

Session 1.Introduction

Page 3: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

3

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

Page 4: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

4

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

+ …

Page 5: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

5

Programming Languages (3) Categories of Third Generation

Languages Structured Programming Language Object-oriented Programming Language

Page 6: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Structured Programming Languages Objectives

Debugging Maintenance

Tools Readability

Methodology Divide and Conquer : Modulization Control : Sequence, Division, Repetition

6

Page 7: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

7

Object-oriented Programming Languages Objectives

Productivity of SW Tools

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.

Page 8: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

8

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

Page 9: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

9

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

Page 10: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

10

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)

Page 11: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

11

Learning Java Is . . . Learning programming structures Learning classes Learning initialization

Constructors Learning derived classes Learning packages, interfaces,

exception handling, stream, networking, etc.

Page 12: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

History of Java Green project (Sun Microsystems, 1991)

A compact programming language for electronic devices such as interactive TV, smart refrigerator, …

The target OS was called Star7 Oak (James Gosling)

Web Browser 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

Page 13: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

13

Platform Independence Byte code Virtual Machine

= Java Interpreter / Java Runtime

Page 14: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 15: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

15

Programming in Java Source Codes

xxx.java Executable Files

xxx.class Execution

java xxx

Page 16: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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.

Page 17: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Using NetBeans IDE Build a New Project Edit the Source Code Compile Execute (Run) Debug

Page 18: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

18

Hello.java

class Hello

{

public static void main(String[ ] args)

{

System.out.println("Hello, world");

}

}

Page 19: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Hello. Make a program which prints out

"Hello".

19

Page 20: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

20

Session 2.Variables and Expressions

Page 21: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

21

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.

Page 22: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

22

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){ ... }

Page 23: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 24: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 25: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Variable Declarations Syntax

type variable1, variable2, … Types

8 Primitive types byte, short, int, long, float, double, char, boolean

Arrays [ ]

Class types Built-in Classes

Object, Class, String, Byte, Short, Int, Long, Float, Double, Char, Boolean, …

User-defined Classes

25

Page 26: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Naming of Variables, Classes, … Alphanumeric

A ~ Z, a ~ z, 0 ~ 9, _ Under bar(_) is regarded as an alphabet.

Case sensitive Upper and lower capital characters are regarded as different

characters. e.g.) Int / int

Can not use keywords as names 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

Page 27: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

27

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_;

Page 28: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Declare an integer variable "i" and a

double variable "d" in the "main" method.

28

Page 29: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Literals int

10 012 0xA, 0xa, 0XA, 0Xa

long 10L, 10l 012L, 012l 0xAL, 0xAl, 0xaL, 0xal

float 2.25F 2.25f

double 2.25 19E-95, 19e-95

boolean true, false

char 'A', '\n', '\r'

Escape Sequence '\n', '\t', … '\'', '\\' '\ooo', '\uhhhh'

(e.g. '\101', '\uC790') '\A', '\"', …

String Constants "Hello, world\n" "-- \n -- ' -- \" -- \\ -- A --" "-- \033 -- \uC790 --"

Please, note: 'A' "A"

29

Page 30: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Expressions Expressions

3 * 4 + 2 a * b + 2

Operators *, +, …

Operands Literals (e.g.) 123 + 1 Variables (e.g.) a + 1 function calls (e.g.) Math.sin(3.14) + 1 another expressions (e.g.) 1 + (3 * a)

30

Page 31: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Forms of Expressions Infix form

3 + 4 Prefix form

(+ 3 4) Lisp language

Postfix form 3 4 +

Java and many other third generation languages use infix form for their expressions.

31

Page 32: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

32

Categories of Operators (by number of operators)

Unary operators +a, -a, ++a, a++, --a, a--, …

Binary operators a + b, a >= b, a && b, a = 3, …

Ternary operators a ? 0 : 1

Page 33: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Another Categories of Operators Arithmetic Operators

+, -, *, /, % Relational Operators

>, >=, <, <=, ==, != Logical Operators

&&, ||, ! Incremental/Decremental Operators

++, -- Assignment Operators

=, +=, -=, *=, /=, %= Conditional Operators

? :

33

Page 34: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

34

Arithmetic Operators +, -, *, /, %(modulus) Be careful about the types of operands(e.g.)

int a = 3, d = 8, b = 1, c = 1;a + 3d / 4a * 4 + ba * b - c5 % 2 → 19 / 2 → 4 (It is NOT 4.5 !)

Page 35: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Calculate and print out the result of "3 +

4.5".

35

Page 36: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

String Concatenation Operator +(e.g.)

"abc" + "def" → "abcdef""abc" + "123" → "abc123""abc" + 123 → "abc123""abc" + 12.3 → "abc12.3"

String a = "abc";a + "def" → "abcdef"

Page 37: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

37

Relational Operators >, >=, <, <=, ==, != Return values

False : false (boolean) True : true (boolean)

(e.g.)int a = 3, b = 1;a > 3a == ba != 3

Page 38: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Calculate and print out the result of "3

>= 4.5".

38

Page 39: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

39

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

Page 40: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Calculate and print out the result of "3

>= 4.5 and 2 < 5".

40

Page 41: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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 --n++n + 1 --n + 1n++ + 1 n-- + 1

41

Page 42: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

42

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.

Page 43: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 44: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 45: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 46: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

46

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)

Page 47: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 48: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

48

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

Page 49: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Print out the result of "(2 < 3) ? 3 : 4.0".

49

Page 50: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 51: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 52: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

52

Priority among OperatorsOperators 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 ternary

= += -= *= /= %= &= ^= |= <<= >>= right to left

Page 53: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 54: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

54

Session 3.Standard Input and Output

Page 55: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

55

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);

Page 56: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

56

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) { }

Page 57: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 58: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

58

Session 4.Control Flow

Page 59: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Structured Programming Three Control Structures

Sequence Division

if, switch Repetition

for, while, do while

Readability, Maintenance Do not use "jump" control.

59

Page 60: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

60

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;

}

Page 61: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

61

if - else (1) Syntax

if (expression)statement

elsestatement

The "expression" must return a boolean value.

(e.g.)int n = 3, a;if (n > 0)

a = 1;else

a = 0;

Extended Syntaxif (expression)

statementelse if (expression)

statement…else

statement

(e.g.)if (x < 0) i = -1;else if (x < 100) i = 0;else i = 1;

Page 62: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

if - else (2) A else is associated with the closest

previous else-less if.(e.g.)

if (n > 0) if (n > 0) if (a > b) if (a > b) z = a; z = a; else else z = b; z = b;

62

Page 63: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 64: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

switch (1) Syntax

switch (expression){

case constant-expression: statementscase constant-expression: statements…default: statements

} The return type of the expression should be one of

byte, char, short, or int. break, return

64

Page 65: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

65

switch (2)(e.g.)

switch (c){

case 'Y':case 'y':

answer = 1;break;

default:answer = 0;break;

}

Page 66: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 67: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

67

for Syntax

for (expression; expression; expression)statement

(e.g.)for (i = 0; i < 100; i++){

System.out.println(i);}

Page 68: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 69: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

69

while Syntax

while (expression)statement

(e.g.)i = 0;while (i < 100){

System.out.println(i);i++;

}

Page 70: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 71: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

71

do - while Syntax

dostatement

while (expression);(e.g.)

i = 0;do

System.out.println(i);while (i < 100);

Page 72: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 73: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 74: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 75: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 76: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

76

Session 5.Arrays

Page 77: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 78: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

78

Steps using an Array Declare an array variable Create an array object Use each element in the array

Page 79: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

79

Declaring an Array Syntax

type variable[ ], … ; type[ ] variable;

"type" is the type of each element.

(e.g.)int a[ ], b[ ];

double[ ] d;

Page 80: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

80

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" };

Page 81: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

81

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;

Page 82: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 83: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

83

Multi-dimensional Arrays

(e.g.)int[ ][ ] coords = new int[12][12];

coords[0][0] = 1;

coords[0][1] = 1;

Page 84: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

84

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.

Page 85: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

85

Session 6.Classes

Page 86: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 87: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Classes: Main Concepts Encapsulation(Data abstraction)

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

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

Page 88: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Homework Report on polymorphism

List and explain types of polymorphism.

88

Page 89: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

89

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

Page 90: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

90

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;

}}

Page 91: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

91

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.

Page 92: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

92

Classes: Declaring an Object type variable, … ;

(e.g.)String str;

MyDate d;

Page 93: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

93

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 StringString s = "abc"; // special treatment for String

Page 94: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

94

Classes: Using an Object variable.member

(e.g.)b = str.length();

d.set(2000, 12, 1);

Page 95: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 96: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

96

Classes : Members Constants Variables Methods

Page 97: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

97

Classes : Constants Named literal Keyword: final Must be initialized(e.g.)

class MyCircle{ final double pi = 3.141592;

final int CENTER = 0;}

Page 98: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 99: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

99

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;

Page 100: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

100

Classes : Methods (1) Instance Methods

return-type function-name(args){

...return(…);

} Class Methods

static return-type function-name(args){

...return(…);

}…class-name.function-name(…);

Page 101: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

101

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);

}}

Page 102: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

102

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"); }}

Page 103: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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)

U * V = (xu * xv, yu * yv) Method compareTo(MyPoint) Method print( )

Format: (x, y) Method String toString( )

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

Page 104: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Merge the two classes, Main and

MyPoint from the previous exercise, into the Main class.

104

Page 105: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 106: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

106

Classes : this To refer the object itself Class methods(static) can not use

"this".

(e.g.)t = this.x;

this.resetData(this);

return(this);

Page 107: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Classes: this Reasons why using this

To override scope this.year = year

To enhance readability this.set(2008, 9, 12);

To refer the object again set(2.3).print( );

107

Page 108: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

108

Classes : Scope Scope is an enclosing context where

values and expressions are associated. Local variables

Only in the function Instance or class variables

Only in the class Local variables have priority over the

instance or class variables.

Page 109: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Classes: thisclass MyCircle {

int radius;

MyCircle set(int r) {radius = r;return(this);

}

void print( ) {System.out.println(radius);

}}

109

Page 110: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

110

Classes : Argument passing Call by value

Primitive types Call by reference

Arrays Objects

Page 111: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

111

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);

Page 112: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

112

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);

Page 113: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

113

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]);}

}}

Page 114: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 115: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

115

Homework Complete the MyDate class, so that it

can be provided as a library.

Page 116: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

116

Session 7.Methods

Page 117: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

117

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) { … }}

Page 118: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

set(int x, int y) Not necessary thanks to implicit type conversion

set(double x, double y) set(String x, String y) Use Double.parseDouble

Method getX( ) and getY( ) Method multiplyTo(MyPoint V)

U * V = (xu * xv, yu * yv) Method toString( )

"(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

Page 119: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 120: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Declare MyPoint class, representing a coordinate, which has members like:

double variables x and y Overloaded constructors

MyPoint( ) MyPoint(double x, double y) MyPoint(String x, String y)

Overloaded Methods set set(double x, double y) set(String x, String y) Use Double.parseDouble

Method getX( ) and getY( ) Method multiplyTo(MyPoint V)

U * V = (xu * xv, yu * yv) Method toString( )

"(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

Page 121: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

121

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.

Page 122: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

122

Homework Provide a class for Bubble Sorting.

class BubbleSorting{

private int a[ ];public BubbleSorting( ) { … }public BubbleSorting(int b[ ]) { … }public void sort( ) { … }public void print( ) { … }

}

Page 123: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

123

Session 8.Inheritance

Page 124: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

124

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{ … }

Page 125: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

MyDate( ) MyDate(int year, int month, int day)

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( )

"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

Page 126: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

126

Inheritance : Overriding Two kinds of overriding

Variable overriding Method overriding

Variable 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

Page 127: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

127

Inheritance : Overridingclass 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);}

}

Page 128: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

128

Inheritance : Overriding Method overriding

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.

To refer the superclass method super.MethodName(args)

Method overriding is an important feature that facilitates polymorphism in the design of object-oriented programs.

Page 129: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

129

Inheritance : Overridingclass Super{

int aMethod(int a){ … }

}class Sub extends Super{

int aMethod(int a){ … n = super.aMethod(12); …}

}

Page 130: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

MyDate( ) MyDate(int year, int month, int day)

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( )

"YYYY/MM/DD:HH:MM:SS" Method test( ), which calls toString( ) and super.toString( ) consecutively and then prints out the two results.

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

Page 131: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

131

Inheritance : Overriding To call a constructor of super class

super(args) Constructor overriding must be at the

first line of a constructor.

Page 132: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

132

Inheritance : Overridingclass 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;

}}

Page 133: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

MyDate( ) MyDate(int year, int month, int day)

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( )

"YYYY/MM/DD:HH:MM:SS" Method test( ), which calls toString( ) and super.toString( ) consecutively and then prints out the two results.

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

Page 134: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

134

Inheritance : Virtual Functionclass 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( );

}

Page 135: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

MyDate( ) MyDate(int year, int month, int day)

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( )

"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

Page 136: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

136

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.

Page 137: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

137

Answer: YData (1)

class YDataInteger{ int value; YDataInteger(int value) { this.value = value; }}

Page 138: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

138

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.

Page 139: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

139

Answer: YData (2)class YDataInteger{ int value; YDataInteger(int value) { set(value); } void set(int value) { this.value = value; } void set( ) { set(0); }}

Page 140: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

140

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).

Page 141: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

141

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); }}

Page 142: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

142

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).

Page 143: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

143

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); }}

Page 144: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 145: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

145

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); }}

Page 146: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

146

Exercise: YData (6) Declare public String toString( ).

Page 147: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

147

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)); }}

Page 148: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

148

Example Regression

class YRegression class YLogisticRegression

class YMatrix class YMatrixM class YTransposedMatrix class YXMatrix class YLogisticXViMatrix

Page 149: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

149

Session 9.Inner Classes

Page 150: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

150

Inner Classes : Categories Nested Classes Inner Classes Local Classes Anonymous Classes

Page 151: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

151

Nested Classespublic 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( ));

}}

Page 152: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

152

Inner Classespublic 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( ));

}}

Page 153: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

153

Local Classespublic 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);

}}

Page 154: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

154

Anonymous Classespublic 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);

}}

Page 155: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

155

Session 10.Packages

Page 156: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

156

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.

Page 157: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

157

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.javaa/b/c/D.java

Page 158: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

158

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( );

Page 159: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

MyDate( ) MyDate(int year, int month, int day)

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( )

"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

Page 160: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 161: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

161

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

Page 162: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

162

Session 11.Modifiers

Page 163: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

163

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

Page 164: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Access Control of Members

164

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

Page 165: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise The previous table about access control

is incorrect. Correct the table by trial and error.

165

Page 166: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

166

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

Page 167: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 168: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise For the previous exercise about YData,

declare the method print( ) as an abstract method.

168

Page 169: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

169

Answer: YDatapublic 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); }}

Page 170: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

170

Session 12.Interface

Page 171: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Multiple/Single Inheritance Limit of single inheritance

Poor expressiveness Limit of multiple inheritance

Complexity Ambiguity

Java Single inheritance

For simplicity Interface

For expressiveness

171

Page 172: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

172

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( );}

Page 173: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

173

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( ) { … } …}

Page 174: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

174

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) { … }

Page 175: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

175

Interface: Inheritance Syntax

public interface sub-interface extends super-interface1, super-interface2, …

Multiple inheritance are allowed for interfaces.

(e.g.)public interface SubGrowable extends Growable

{

}

Page 176: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

176

Session 13.Exception Handling

Page 177: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Steps for Exception Handling Define an exception class Throw [Pass] (optional) Catch [& pass & catch …]

177

Page 178: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exception: Classes

Exception

IOException RuntimeException

FileNotFoundException ArithmeticException NullPointerException

178

Page 179: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

179

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); }

}

Page 180: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Declare InvalidValueException which is

a subclass of RuntimeException.

180

Page 181: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

181

Exception: Throwing Syntax

public type method(args) throws AnException

{

AnException e = new AnException(args);

throw e;

}

Page 182: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 183: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

183

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.

Page 184: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 185: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

185

Exception: Passing Syntax

public type method(args) throws AnException

{ … Methods which throw AnException …}

Page 186: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 187: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

187

Exception: Catching & Passing Syntax

public type method(args) throws AnException{ … try { … } catch (AnException e) { …

e.printStackTrace();…

throw e; }}

Page 188: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 189: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 190: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exception: Methods String getMessage( ) void printStackTrace( )

190

Page 191: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 192: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 193: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

193

Session 14.Stream

Page 194: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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 InputStream, OutputStream

Character Stream (supports Unicode) Reader, Writer

Bridge from byte streams to character streams InputStreamReader, OutputStreamWriter

import java.io.*

194

Page 195: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Byte Stream Input

InputStream( ) FileInputStream(File file) / FileInputStream(String fileName) BufferedInputStream(InputStream in) DataInputStream(InputStream in) ObjectInputStream(InputStream in)

Output 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

Page 196: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 197: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 198: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 199: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

199

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( )

Page 200: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

200

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( )

Page 201: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

201

Buffered Streamtry{

FileInputStream fis = new FileInputStream("test.dat");BufferedInputStream bis = new BufferedInputStream(fis);…bis.read( );bis.read(buf);…bis.close( );

}catch (IOException e) { }

Page 202: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

202

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

Page 203: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

203

Data Streamtry{

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) { }

Page 204: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

204

Buffered & Data Streamtry {

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) { }

Page 205: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

205

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( )

Page 206: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 207: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Buffered Reader/Writertry{

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

Page 208: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 209: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

PrintWritertry{

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

Page 210: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Copy a text file "a.txt" to another text file

"b.txt".

210

Page 211: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

211

Session 15.API

Page 212: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

API Specification

212

Page 213: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 214: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Print out a date in the format of

"MM/DD/YYYY".

214

Page 215: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 216: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Parse a string "123" to get int 123.

216

Page 217: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 218: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Parse a string "12.3" to get double 12.3.

218

Page 219: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 220: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Parse a string "123" to get long 123L.

220

Page 221: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 222: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 223: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Class Stack<E> extends Vector<E>

E peek() E pop() E push(E item)

223

Page 224: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 225: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Class Hashtable<K,V> V get(Object key) V put(K key, V value) int size() boolean isEmpty() void clear() Enumeration<K> keys()

225

Page 226: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 227: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 228: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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

Page 229: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Formatting Calendar

import java.util.*;import java.text.*;

Calendar c = Calendar.getInstance();DateFormat df = new

SimpleDateFormat("yyyy/MM/dd:HH:mm:ss");

System.out.println(df.format(c.getTime()));

229

Page 230: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Parsing Calendarimport 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

Page 231: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Exercise Build a NetBeans project called Test. Print out the current time. Print out the time after 13 hours and 55

minutes.

231

Page 232: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

232

Session 16.Serialization

Page 233: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

233

Serializtion 이란 ? 객체 직렬화 이전까지 파일이나 다른 스트림으로

객체를 기록하기 위해 단순 노동을 했어야 했던 것을 손쉽게 저장할 수 있도록 Java 에 추가된 도구

Page 234: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

234

Default Serialization (1)public class A implements Serializable{

int stat;transient int temp;public A( … ) { … }…

}

• java.io.Serializable 인터페이스는 메소드나 필드를 갖고 있지 않으며 , 단지 이 객체가 Serialize 해도 괜찮은지 아닌지만 판단하도록 표시

• transient 한정사는 Serialization 에 포함하지 말 것을 표시

Page 235: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

235

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) { }

Page 236: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

236

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) { }

Page 237: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

237

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

한다 .

Page 238: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

238

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( );

}}

Page 239: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

239

Session 17.Multi-threading

Page 240: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

240

Process & Thread Process

운영체제가 관리하는 작업의 단위 프로그램 실행이란 프로세스를 만들어서

사용하는 것 Thread

하나의 프로세스에 속하면서 프로세스가 가지고 있는 자원들을 다른 Thread 와 공유

Page 241: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

241

Multi-threading (1) Thread 클래스 확장

public class A extends Thread Runnable 인터페이스 구현

public class A implements Runnable public void run( )

(Note) class Thread implements Runnable

Page 242: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

242

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( );

}…

}}

Page 243: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

243

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( )

Page 244: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

244

Synchronization (1) 같은 자원에 서로 다른 Thread 가

동시에 접근할 때의 문제점 해결 synchronized 한정사 사용

한 Thread 만이 synchronized Block 을 수행할 수 있음

형식 synchronized type method(…) { … } … synchronized (object) { … }

Page 245: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

245

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( );

}}

Page 246: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

246

Thread Status Useful methods

start( ), sleep(long milisec), sleep(long milisec, int nanosec)

Do NOT use yield( ), destroy( ), stop( ), resume( ), suspend( )

sleep( ) throws InterruptedException 다른 Thread 들이 작업할 수 있도록 이 Thread 를

잠시 쉬게 하는 메소드 m_thread.sleep(100); m_thread.sleep(100, 250);

Page 247: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

247

Session 18.Networking

Page 248: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

248

TCP/IP

Server Client

Packageimport java.io.*;import java.net.*;

import java.io.*;import java.net.*;

Class & Methods

ServerSocket(int port)

Socket accept( );

Socket(String host, int port) InputStream getInputStream( ); OutputStream getOutputStream( ); void close( );

ExceptionsUnknownHostException

Page 249: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

249

Example of Serverimport 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);}

Page 250: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

250

Example of Clientimport 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);}

Page 251: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

251

HTTPimport java.net.*;Import java.io.*;

public URL(String fullURL) throws MalformedURLExceptionpublic InputStream openStream( ) throws IOExceptionpublic URLConnection openConnection( ) throws IOException

public abstract HttpURLConnection(URL url)public void setDoOutput(boolean dooutput)public OutputStream getOutputStream( ) throws IOExceptionpublic String getHeaderField(String name)public InputStream getInputStream( ) throws IOException

Page 252: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

252

Example of Web Browserimport 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);}

Page 253: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

253

Example of Web Browsertry{ 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);}

Page 254: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

254

Session 19.JDBC

Page 255: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

JDBC Java Database Connectivity DB 프로그래밍 순서

데이터베이스 생성 데이터베이스 테이블 생성 ( 필요에 따라 ) 데이터베이스 연결 설정

e.g. ODBC JDBC 프로그래밍

255

Page 256: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

데이터베이스 및 테이블 생성 데이터베이스 생성

MS Access *.mdb

데이터베이스 테이블 생성 Table design Data 입력

256

Page 257: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

데이터베이스 연결 설정

Page 258: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

데이터베이스 연결 설정

Page 259: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

데이터베이스 연결 설정

Page 260: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

데이터베이스 연결 설정

Page 261: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

데이터베이스 연결 설정

Page 262: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

데이터베이스 연결 설정

Page 263: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

데이터베이스 연결 설정

Page 264: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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();

Page 265: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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();

Page 266: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

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();}

Page 267: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Appendix

267

Page 268: 1 Java Dr. Yong Uk Song Dept. of MIS Yonsei University Wonju Campus

Names for SymbolsName 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