Sie sind auf Seite 1von 70

Website: www.dap-papei.

gr
E-mail: dap.papei@yahoo.gr
Facebook: https://www.facebook.com/dap.papei
Twitter: https://twitter.com/dap_papei

... ....

Java

1. Java
Java (object oriented)
.
1991 Sun Microsystems

.
C++ -
.

Java
Java
Java (
) .
Java Virtual Machine (JVM)
.
(.. C, C++, PASCAL)

. ,
.

,
Windows Macintosh. ,
(source code)
.
, Java
, bytecode.
, .
Java Virtual Machine (JVM) Java bytecode. JVM

bytecode (java bytecode to
native code translation, ).
Java, Java
(.. C++).
, Just In Time (JIT) compilers
scheduling JVM, Java
( Java 90%
C++),
.

Java 1

C++ Java.


(source code) (source code)

C++ compiler Java compiler

Java Bytecode
(Native code)

Java Virtual
Machine (JVM)


C++
(CPU)
Java
C++
. :
Java C++
Java Bytecode Native code
Portable
( JVM)

Java
Web, Applets Web

(Procedural Structured
Programming)
C, PASCAL, FORTRAN
.
(code-centric ).

, .

(Object-Oriented Programming)
(C++, Eiffel, Smalltalk
Java) .
(data-centric)
.

Java 2

.

.

.

. , , , .
. .
/,

.
,
.
,
. ,
( ).

. ,
( .. , , ).
.
,
:
Encapsulation ()

.
Polymorphism ()

,
.
Inheritance ()

.
,
.

Java 3
2. Java
, Java
.
, , .

.

.
-' - .
:
type var;

type var .
Java
( ).


,
. ,
, loop for/while/do if/else/switch.
:
type var1;
if () {
// var1 ().
// var2 ().
type var2;
// var2 ()
}
// var1 ()
// var2 ()


Java C C++
( Java C++).
, C++
Java
.
Java pointers.

Java 4
Java:
( bytes)
byte 1 -128 127
short 2 -32768 32767
int 4 -2147483648 -2147483647
long 8 -9223372036854775808 -9223372036854775807
float 4 1.4 * 10-45 3.4 * 1038
double 8 4.9 * 10-324 1.8 * 10308
bool 1 true / false
char 2 -
String -

byte, short, int, long


, float, double (.
). bool true false.
char C/C++ 2 bytes
Unicode (UTF-16 ).
:
int an_integer;
an_integer = 10;
long a_long = an_integer *1000;
double verysmallnumber = 0.000000000003;
bool am_i_hungry = false;
char alpha = 'a';
String text = this is a text;

(constants)

, .
( ) final. ,
final double pi = 3.1415;

(operators)

.
. 4 Java (
, ).

Java 5


+
-
*
/
%
++
--

,
(
, ). :
int x = 10;
x++; // x 11
x--; // 10


.

==
!=
>
<
>=
<=


& AND ()
| OR ()
^ XOR ( )

Java 6

&& Short-circuit AND
|| Short-circuit OR
! NOT ()

& && ,

.
,
(alpha == true) & (beta == 1)


(alpha == true) .
&&, (false)
,
.
.



.
. :
int x = 4;
x = 10;
x += 20; ( x = x + 20, 30)
x /= 10; ( x = x / 10, 3).


x += y x = x + y
x -= y x = x - y
x *= y x = x * y
x /= y x = x / y
x %= y x = x % y
x &= y x = x & y
x |= y x = x | y
^= x = x ^ y

Java 7
(Expressions)
, ,
.
Java (int, long, double, bool, )
String.
:
int b = 10, i;
i = 2*b*b; ( )
if (b * b <= 100 && i > 0)
System.out.println(The expression is true);

Java 8
3.

.

.

if
if
:
if ()
{
;
}
else
{
;
}

if ,
:
if (x == 1) {
System.out.println(x is one.);
} else if (x == 2) {
System.out.println(x is two.);
} else if (x == 3) {
System.out.println(x is three.);
} else if (x == 4) {
System.out.println(x is four.);
} else {
System.out.println(x is not between 1-4.);
}

switch
switch
.
switch, :
switch (x) {
case 1;
System.out.println(x is one.);
break;
case 2;
System.out.println(x is two.);
break;
case 3:
System.out.println(x is three.);
break;
case 4:
System.out.println(x is four.);
break;
default:

Java 9
System.out.println(x is not between 1-4.);
break;
}

break. break
break switch.
.
switch (x) {
case 1;
System.out.println(x is one.);
case 2;
System.out.println(x is two.);
case 3;
System.out.println(x is three.);
case 4;
System.out.println(x is four.);
System.out.println(x is between one and four.);
break;
case 5;
System.out.println(x is five.);
case 6;
System.out.println(x is six.);
case 7;
System.out.println(x is seven.);
case 8;
System.out.println(x is eight.);
System.out.println(x is between five and eight.);
break;
default:
System.out.println(x is not between one and eight.);
break;
}

for
for (loop) .
for,
( C/C++).
:
for ( ; ; ) {
;
}

(initialization) loop
(condition). ,
(iteration)
. , ...

Java 10
:
for (int i = 1; i < 20; i += 3) {
System.out.println(i);
}

:
1
4
7
10
13
16
19

,
for.
';'. :
int x = 10;
for (; x < 5; x++) {
System.out.println(x);
}

double y = 20000; // (y = pi)


for (; y >= 10.0;) {
// y
// y.
// for loop y 10.0
System.out.println(y);
y = Math.sqrt(y);
}

for (;;) { // infinite loop


wait_for_signal();
}

while
while for
,
:
while () {
;
}
:
bool exit_from_loop = false;
while (exit_from_loop = false) {
//
read_bytes(file1);
//
write_bytes(file2);

Java 11
if (file_empty(file1) == true)
exit_from_loop = true;
}

do/while
do/while while, ,
loop
.
do {
;
} while ();

:
int x = 10;
do {
System.out.println(x);
x++;
} while (x <10);

:
10

loop
(x < 10).

break/continue
loop
. .. infinite loop,
(signal) (.. Control-C).
for (int i = 1; i < 20; i += 3) {
if ( i*i > 100)
break;
System.out.println(i);
}

:
1
4
7

break loops, for, while, do/while.


break continue,
iteration loop. iteration.
:
for (int i = 1; i < 20; i += 3) {
// ()
if ( i % 2 = 0)

Java 12
continue;
System.out.println(i);
}

:
1
7
13
19

Java 13
4.Classes

Class: Car

Instance of Car Instance of Car Instance of Car


Instance of Car Object:
Object: Object:
Object: Ferrari Modena
Audi TT Bertona Bella
Jaguar XK8

Java
.

(instance) . ,

. , ,
, ,
,
(, , , ).
( /
). , .
Java ( C++ Java)
class. ,
Car:
class Car
{
(/)
(/)
}

member variables

. ,
: , ,
. ,
,
.

Java 14
Car, :
class Car
{
//
float steering_angle;

// (0 = , 100 = !)
float gas_pedal;

// (0 = , 100 = !)
float break_pedal;

// (0 = ,
// 100 = !)
float clutch;

// ( : 0, 1,2,3,4,5,
// 0 = , -1 = )
int gear;

// ,
//
float acceleration, speed, rpm;
}


, .
,
. ,
,
, float.
, , Car.

. '
interface . interface
(member methods).

member methods
(methods) ,
()
.
,
. ,
, ,
,
.

Java 15
Car :
// , <relative_angle>
// .
void turn_wheel(float relative_angle);

//
void press_gas_pedal(float amount);

//
void press_break_pedal(float amount);

//
void press_clutch_pedal(float amount);

// . true
// false (.. 5 ).
bool change_gear(int new_gear);

// ,
//
float get_acceleration();
float get_speed();
float get_rpm();

,
(float) get_*(), bool
change_gear(). void
.
,
' .


,
.
(implementation).
, turn_wheel() :
void turn_wheel(float relative_angle)
{
steering_angle += relative_angle;
if (steering_angle <= -720.0)
steering_angle = -720.0;
if (steering_angle >= 720.0)
steering_angle = 720.0;
}


, 2
.
, (.. ),

.

Java 16
new
, -
(instances) . , new
Java.
new , ,
(reference) .
(
). new :
Car acar = new Car();
Car anothercar = new Car();

acar anothercar
new.
. :
Car acar;
acar = new Car();

( )
, :
// acar
acar.steering_angle

// anothercar
anothercar.steering_angle

// acar 13.4 .
acar.turn(13.4);

// acar
float speed = acar.get_speed();

// anothercar 32
anothercar.turn(-32.0);

// anthercar
bool result = anothercar.ghange_gear(-1);

( ).
Java
.
','.

Constructors
new, Java,
,
, (constructor).
.
,

Java 17
,
SQL, (sockets) server
.

( ,
void).
, Car, :
Car()
{
steering_wheel = 0.0;
gas_pedal = 0.0;
break_pedal = 0.0;
float clutch = 0.0;
int gear = 0;
acceleration = 0.0;
speed = 0.0;
rpm = 0.0;
}

, (initialization)
.
,
.
,
(engine_cc: , engine_hp: ) ,
:
Car(int cc, int hp)
{
engine_cc = cc;
engine_hp = hp;
//
}

.
constructor overloading
Java, method overloading (
).

Destructors? Garbage collection Java


C++,
(destructors). C++, ,
( delete)
(
, , threads,
, ). Java ,
!
Java (garbage collection)

Java 18
,
. ,

(.. C++).

this
,
,
. ,
.
this
(
). this, turn_wheel()
:
void turn_wheel(float relative_angle)
{
this.steering_angle += relative_angle;
if (this.steering_angle <= -720.0)
this.steering_angle = -720.0;
if (this.steering_angle >= 720.0)
this.steering_angle = 720.0;
}

this
,
.

Method Overloading
,
.
/ .
, turn_wheel()
int float. C
/,
:
void turn_wheel_int(int relative_angle)
{
this.steering_angle += (float) relative_angle;
if (this.steering_angle <= -720.0)
this.steering_angle = -720.0;
if (this.steering_angle >= 720.0)
this.steering_angle = 720.0;
}

void turn_wheel_float(float relative_angle)


{
steering_angle += relative_angle;
if (steering_angle <= -720.0)
steering_angle = -720.0;
if (steering_angle >= 720.0)

Java 19
steering_angle = 720.0;
}
, .
turn_wheel_int() :
void turn_wheel_int(int relative_angle)
{
turn_wheel_float((float) relative_angle);
}

,
,
debugging,
. Object-
Oriented Java C++ Method
Overloading. method overloading,
.
, :
void turn_wheel(float relative_angle)
{
steering_angle += relative_angle;
if (steering_angle <= -720.0)
steering_angle = -720.0;
if (steering_angle >= 720.0)
steering_angle = 720.0;
}

void turn_wheel(int relative_angle)


{
turn_wheel((float) relative_angle);
}

turn_wheel()
.
' ' , ( void
) .

Java 20
5.

Java
, .
C/C++, Java .
, ..
(
Java) , (
C/C++).

.
C/C++.
:
type table[];

, new:
table = new type[size];

:
type table[] = new type[size];

type
(bool, byte, short, int, long, float, double,
char, String) ( Java ). size
table.
C/C++,
table[i], i .
C/C++ Java
(0) size-1. A 10
A[0] A[9].
:
int data[] = new int[10];
int i;
System.out.println(Size of array data: + data.length);
for (i = 0; i < data.length; i++) {
data[i] = i*i;
System.out.println(data[ + i + ] = + data[i]);
}

:
Size of array data: 10
data[0] = 0
data[1] = 1
data[2] = 4
data[3] = 9
data[4] = 16
data[5] = 25

Java 21
data[6] = 36
data[7] = 49
data[8] = 64
data[9] = 81

length
.
,
,
:
int dataset[] = { 22, 3, 54, 43, 199, 20, 20, 67, 7, 80 };

new
dataset.
.



Java, .
, :
int twodim[][] = new int[4][4];
int i, j, counter = 1;
for (i = 0; i < twodim.length; i++) {
for (j = 0; j < twodim[i].length; j++) {
twodim[i][j] = counter;
counter++;
System.out.print(twodim[i][j] + );
}
System.out.println();
}

:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

,
:

1 2 3 4
5 6 7 8
twodim[1][2]
9 10 11 12
13 14 15 16
twodim[3][1]

Java 22
Strings
strings
System.out.println(). strings
, Java strings ,
String.
println(),
String,
, new.
String str = new String(Hello);
System.out.println(str);

String :
String str2 = Another string;
System.out.println(str2);

String ,
String.
:

boolean equals(String str) true String
.
int length() ( ) String.
char charAt(int index)
index String.
int compareTo(String str) String.
(. compareTo())
str,
, ,
String
str.
int indexOf(String str) str String.

, -1.
int lastIndexOf(String str String.
str)
, -1.

strings Java:
String str1 = Hello there, from Java!;
String str2 = One two three four;
String str3 = Java strings are cool!;
String str4 = new String(str3);
int index, result;

System.out.println(str1 is + str1.length() + characters long.);

Java 23
for (int i=0; i < str2.length(); i++)
System.out.print(str2.charAt(i) + |);
System.out.println();

if (str3.equals(str4))
System.out.println(str3 == str4);
else
System.out.println(str3 != str4);

if (str3.equals(str2))
System.out.println(str3 == str2);
else
System.out.println(str3 != str2);

result = str3.compareTo(str1);
if (result < 0)
System.out.println(str3 < str1);
else if (result == 0)
System.out.println(str3 == str1);
else
System.out.println(str3 > str1);

index = str1.indexOf(Java);
if (index)
System.out.println('Java' exists in str1 in position + index);
else
System.out.println('Java' does not exist in str1);

index = str2.indexOf(Java);
if (index)
System.out.println('Java' exists in str2 in position + index);
else
System.out.println('Java' does not exist in str2);

index = str3.indexOf(Java);
if (index)
System.out.println('Java' exists in str3 in position + index);
else
System.out.println('Java' does not exist in str3);

:
H|e|l|l|o| |t|h|e|r|e|,| |f|r|o|m| |J|a|v|a|!|
str3 == str4
str3 != str2
str3 > str1
'Java' exists in str1 in position 18
'Java' does not exist in str2
'Java' exists in str3 in position 1

Java 24
6.

Java. ,

.

main()
Java, , C/C++,
/ main().
, main() ,
. Java:
class Example {
public static void main(String args[]) {
System.out.println(hello everyone);
}
}

public, static void ,


args[].
void
. main()
.
public
,
. main()
( ).
, static
. ,
Example new,
main(). ,
main(), main()
Java.

.java
(source code)
(compilation unit) Java,
.java.
. ,
, Java
.
javac (java compiler), :
(source code directory)# javac Example.java (UNIX/Linux)

C:\(source code directory)\> javac Example.java (Windows)

Java ( java bytecode,


),

Java 25
. java bytecode .class.

.class
.class Java Virtual Machine (JVM).
JVM , java.
(source code directory)# java Example (UNIX/Linux)
hello everyone

C:\(source code directory)\> java Example (Windows)


hello everyone

.class Example.
.java, compiler java .class.
.class
.java .

.jar
,
.java .class,
, .class
.
.
, Java .class
JAR (Java Archive) .jar.
jar (
Windows UNIX/Linux):
C:\(source code directory)# jar cvf classes.jar MyClass1.class
Another.class

classes.jar
:
C:\(source code directory)\> java classes.jar

jar zip
.

args[] main()
main() args[],
String. argc
argv[] C/C++. ,
(DOS/Command Prompt
Windows, shell Linux).

:

Java 26
class ArgsExample {
public static void main(String args[]) {
for (int i=0; i < args.length; i++)
System.out.println(args[i]);
}
}

ArgsExample.java
javac :
# javac ArgsExample.java

# java ArgsExample hello mate what's up?


hello
mate
what's up?

(hello, mate what's up?)


.
(space,
tab) ,
( what's up?
).

Java 27
7.

Java
.

( Java JVM).
,
.
:

.

.
/ .
.

.
(
main()).

.

:
1 class ArgsExample {
2 public static void main(String args[]) {
3 for (int i=0; i < args.length; i++) {
4 if (args[i].equals(-file) == true) {
5 if (i+1 < args.length)
6 System.out.println(FILE: +args[i+1]);
7 }
8 }
9 }
10 }

1-3 : ,
main() loop for. 4
equals() String - args[]
-file. ( equals()
true) ( i+1
, 5)
( 6). args[].
javac,
:

Java 28
# javac ArgsExample.java
# java ArgsExample one -file two three -file
FILE: two

args[] :

args[0] one
args[1] -file
args[2] two
args[3] three
args[4] -file

args.length
args.length = 5.
, :

i args[i] args[0].equals(-file) i+1 < args.length Print?


0 one false - no
1 -file true true yes
2 two false - no
3 three false - no
4 -file true false no

- i+1 < args.length


,
5 for loop ( i ).
if 5 if 4
true.

References
equals()
String.
==, int ;
Java, (bool, int, long, float, ),
,
( , String)
(instance). ,
str String,
. pointers
references C/C++.
, string:

Java 29
String a, b;
a = Hello;
b = a;
String c = new String(a);


.
a c
Hello Hello

a b
string Hello. b a,
. b,
a. c,
a
c. c, a .

Encapsulation
Person
, .. , , email
. ..
, , .
class Person
{
//
String Firstname_, Lastname_;
int Age_;
String Telephone_;
String Email_;

// constructor
Person(String fname, String lname, int age, String tel,
String email)
{
Firstname_ = new String(fname);
Lastname_ = new String(lname);
Age_ = age;
Telephone_ = new String(tel);
Email_ = new String(email);
}
}

_. ,
,

.

Java 30
,
:

Person bilbo = new Person( Bilbo, Baggins, 111, +306970123456,


bilbobaggins@theshire.net);

, bilbo
Bilbo Baggins, 111 . 306970123456 email bilbobaggins@theshire.net.
.
bilbo,

. , email email_
telephone_. :
bilbo.Firstname_ = ;
bilbo.Lastname_ = ;
bilbo.Age_ = 3;
bilbo.Email_ = this is definitely not a valid email address;
bilbo.Telephone_ = yeah, try to call this;

!!!

;
Java
,
.
, main() public
.
, public
. ,
private. private

( ). ,
. Person,
private, :
class Person
{
//
private String Firstname_, Lastname_;
private int Age_;
private String Telephone_;
private String Email_;
...


!
.
, .
.

Java 31
,
,
( getter/setter ).
, Person get/set
(age_ email_):
// Return the age
int getAge()
{
return Age_;
}

// return the Email address


String getEmail()
{
return new String(Email_);
}

// method to set the age of the person


bool setAge(int Age)
{
// check if given Age is non-negative (> 0)
if (Age > 0)
{
Age_ = Age;
return true;
} else
return false;
}

// method to set the email address


bool setEmail(String Email)
{
// call a helper method to check the validity of the email
// address (if it's in the form x@y.z).
// Ideally, the email address should be a class on its own.
if (isValid(Email) == true)
{
Email_ = new String(Email);
return true;
} else
return false;
}

.
email , ,
email ( x@y.z).

. ..
,
. O,
,
(.. setTelephone()).

Java 32
Inheritance

. ,
.
,
Person . Person
, .. ,
, ,
/ .
Person

( ).
,
.
/ , ;

. Person
(Clerk)
(Teacher).
Person.
Person.
(
):
class Clerk extends Person
{
private String JobTitle_;
private String CompanyName_;
private String JobAddress_;
private String JobEmail_;
private String JobTel_;
private String JobFax_;
private String JobDescription_;

public Clerk(String fname, String lname, int age, String tel,


String email, String jobtitle, String companyname,
String jobaddress, String jobemail,
String jobtel, String jobfax,
String jobdescription)
{
Firstname_ = new String(fname);
Lastname_ = new String(lname);
Age_ = age;
Telephone_ = new String(tel);
Email_ = new String(email);
JobTitle_ = new String(jobtitle);
CompanyName_ = new String(companyname);
JobAddress_ = new String(jobaddress);
JobEmail_ = new String(jobemail);
JobTel_ = new String(jobtel);
JobFax = new String(jobfax);
JobDescription_ = new String(jobdescription);

Java 33
}
// get/set
// ...
...

//
// .
String getInfo() {
return new String(getFirstname()+ +getLastname()
+ works at +CompanyName_
+, at +JobAddress_
+.\n Email: +getEmail()+\n
+Tel: +JobTel_);
}
}

, Teacher:
class Teacher extends Person
{
private String Title_;
private String School_;
private String SchoolAddress_;
private String SchoolTel_;
private String CourseName_;
private String CourseDescription_;

public Teacher(String fname, String lname, int age, String tel,


String email, String title, String school,
String schooladdress, String schooltel,
String coursename, String coursedescription)
{
Firstname_ = new String(fname);
Lastname_ = new String(lname);
Age_ = age;
Telephone_ = new String(tel);
Email_ = new String(email);
Title_ = title;
School_ = school;
SchoolAddress_ = schooladdress;
SchoolTel_ = jobtel;
CourseName_ = coursename;
CourseDescription_ = coursedescription;
}
// get/set
// ...
...

//
// .
String getInfo() {
return new String(getFirstname()+ +getLastname()
+ teaches +CourseName_+ at +School_
+, +SchoolAddress_+.\n
+Email: +getEmail()+\n

Java 34
+Tel: +SchoolTel_);
}
}

get() Person
( private).
private,
. .
;
:
Person bilbo = new Person( Bilbo, Baggins, 111, +306970123456,
bilbobaggins@theshire.net);
Clerk sam = new Clerk( Samwise, Gamgee, 33, +30697654321,
samgamgee@theshire.net,
Gardener, Baggins Inc.,
Bag End, Hobbiton, The Shire,
gardener@baggins.com,
+302103456789, +302103456780,
Garden Dept. Director);
Teacher pippin = new Teacher( Peregrin, Took, 27, +30690090090,
pippin@theshire.net, Dr.,
King's College, Hobbiton,
+30210000001, Philosophy,
Deal with the important matters of life, eg. what do we
eat?);

,
,
( ):
System.out.println(bilbo has email address: + bilbo.getEmail());

:
bilbo has email address: bilbobaggins@shire.net

:
System.out.println(sam works as a + sam.getJobTitle() + at +
sam.getCompanyame());

:
sam works as a Gardener at Baggins Inc.

, :
System.out.println(pippin teaches + pippin.getCourseName() + at +
pippin.getSchool());
:
pippin teaches Philosophy at King's College

Java 35
, :
System.out.println(sam's private telephone is + sam.getTel());
System.out.println(pippin is + pippin.getAge() + years old);

:
sam's private telephone is +30697654321
pippin is 27 years old
Person !!!
!
,
(code reusability).
,

, .

Polymorphism

; ,
getInfo(),
. ,
Person, getInfo().
getInfo() Person, .. :
String getInfo() {
return new String(getFirstname()+ +getLastname()
+is +getAge()+ years old);
}

: getInfo()
;
. getInfo()
.
, :
System.out.println(bilbo.getInfo());
System.out.println(sam.getInfo());
System.out.println(pippin.getInfo());


Bilbo Baggins is 111 years old
Samwise Gamgee works at Baggins Inc., at Bag End, Hobbiton, The Shire.
Email: gardener@baggins.com
Tel: +302103456789
Peregrin Took teaches Philosophy at King's College, Hobbiton.
Email: pippin@theshire.net
Tel: +30210000001

; (
getInfo()) . Person
getInfo() (Bilbo Baggins is 111 years old)

Java 36
Clerk Teacher .
, getInfo() Clerk, getInfo()
sam Samwise Gamgee is 33 year old.
Clerk
getInfo(), , .
Method Overriding
.

//
.

. (bilbo, sam, pippin).
Person who[3];
who[0] = bilbo;
who[1] = sam;
who[2] = pippin;
for (int i=0; i < who.length; i++)
System.out.println(who[i].getInfo());

,
Person
. sam Clerk pippin
Teacher. who;
Person, Clerk Teacher .
Clerk Person, Teacher
Person. Clerk Teacher.
Clerk Teacher Person,
. Person, getInfo()
.
(
);
super (
). super
( constructor
). .
getInfo() Teacher :
public Teacher(String fname, String lname, int age, String tel,
String email, String title, String school,
String schooladdress, String schooltel,
String coursename, String coursedescription)
{
super(fname, lname, age, tel, email);
Title_ = title;
School_ = school;
SchoolAddress_ = schooladdress;
SchoolTel_ = jobtel;
CourseName_ = coursename;
CourseDescription_ = coursedescription;
}

Java 37
String getInfo() {
return new String(super.getInfo()
+ and teaches +CourseName_+ at +School_
+, +SchoolAddress_+.\n
+Email: +getEmail()+\n
+Tel: +SchoolTel_);
}

(initialize)

. , getInfo(),
. ..
getInfo() Person,
getInfo() Teacher,
Person super.
method overriding
. ,
. ( )
(method overloading)
.

Abstract Classes

.
,
method overriding.

' .
.

.
( )
. :
abstract class Car {
...
// . true
// false (.. 5 ).
abstract bool change_gear(int new_gear);
...
}

class FerrariModena extends Car {


...
bool change_gear(int new_gear) {
//
}
...
}

Java 38
Final Classes
method overriding,
, .
(..
, /, ),

.
( )
.
.

final. final overriding
. final,
'
.
:
class A {
final int amethod() {
// sample code
}
}
class B extends A {
int amethod() { // !!! !
// different code
}
}

final:
final class A {
// class internals
}

class B extends A { // !!! !


// class internals
}

final ,

( const C++).
class myfinal {
final int x = 1; // int x 1
//
}

Object
Java '
.
,

Java 39
. Object
:


boolean equals(Object ob) true Object
.
Object clone() ,
clone().
Class getClass()
getClass().
String toString() /
String.

System.out.println(),
. overload.

Java 40
8.Exceptions
( !)
.
bugs ( ),
( , ,
, ) (..

).


/ (crash).


. ,
.
(C, PASCAL)
.

. ,
,
,
:
fc = open(.dat);
if (fc == 0 && errno != 0)
println(error);
success = read(fc, buffer);
if (success) {
// do stuff
}
success = write(fc, buffer);
if (success) {
// again, do stuff
}

, .
,
. ,
. ,

(
).
, ,

,
.
C, PASCAL, FORTRAN.

.

Java 41
C++ Java
, exceptions.

. ( ),
exceptions ,
,
. :
(try)
(exception)
(catch). , :
try {
fc = open(.dat);
read(fc, buffer);
// do stuff
write(fc, buffer);
// do stuff
} catch (Exception e) {
println(error);
}

(: , Java
, )
catch exception
(catch). Java exception
Exception , e
. Exception
exception, ,
, . :

String getLocalizedMessage() String exception

String getMessage() String exception.
String toString() toString() ..

System.out.println().
void printStackTrace()
( exception)
.


Exception .
..
( )
.
Exception ( Exception)
.
exceptions Java:

Java 42
Exception
ArithmeticException (..
).
ArrayIndexOutOfBoundsException
.
ArrayStoreException
.
NegativeArraySizeException .
NullPointerException null .
NumberFormatException String
.
StringIndexOutOfBoundsException String
.
UnsupportedOperationException .
ClassNotFoundException .
IllegalAccessException
.
InstantiationException
(instance) .
NoSuchFieldException .
NoSuchMethodException .

exception catch.
, :
class ExceptionTest {
public static void main(String args[]) {
int val = -5;
int nums[] = new int[10];

for (int i=0; i < nums.length; i++, val++)


nums[i] = val;

for (int i=0; i < 2* nums.length; i++) {


try {
// 10 nums[i]
System.out.println(10 / nums[i]);
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception :"
+ e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("non-existant elements, at pos:"
+ e.getMessage());
}
}
System.out.println(Program continues to run...);
}

Java 43
}
javac, java:
$ java ExceptionTest
-2
-2
-3
-5
-10
Arithmetic Exception :/ by zero
10
5
3
2
non-existant elements, at pos: 10
non-existant elements, at pos: 11
non-existant elements, at pos: 12
non-existant elements, at pos: 13
non-existant elements, at pos: 14
non-existant elements, at pos: 15
non-existant elements, at pos: 16
non-existant elements, at pos: 17
non-existant elements, at pos: 18
non-existant elements, at pos: 19
Program continues to run...

,
. exceptions,
:
$ java ExceptionTest
-2
-2
-3
-5
-10
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionTest.main(ExceptionTest.java)

,
,
, ,
.

Exceptions throws
exceptions
exceptions. Java
exception
( main()). exceptions
, .
exception , . main:
:
public static void main(String args[]) throws java.io.IOException {

Java 44
9.Java
, Java
, .
Java ,
, ..
String
.
,
, .. C
(memory mapped files) (structs)
/. C++
(streams).
, , Java.

I/O Streams
streams ,

. , Java

, byte (byte streams)
(character streams). , byte streams
,
.
, character streams ,
(.. ISO-8859-7, UTF-8)
Unicode.
, character streams byte streams.

Byte Streams
byte streams
InputStream OutputStream.

(.. , (pipes), ).
InputStream
OutputStream.
Java.
byte streams.

InputStream ()
byte stream (input).
OutputStream ()
byte stream (output).
BufferedInputStream Stream buffer .
BufferedOutputStream Stream buffer .
ByteArrayInputStream Stream bytes.

Java 45

ByteArrayOutputStream Stream bytes.
DataInputStream Stream (raw) bytes.
DataOutputStream Stream (raw) bytes.
FileInputStream Stream .
FileOutputStream Stream .
FilterInputStream Stream .
FilterOutputStream Stream .
PipedInputStream Stream (pipe).
PipedOutputStream Stream (pipe).
PrintStream Stream print() println
().
PushBackInputStream Stream .
RandomAccessFile Stream .
SequenceInputStream Stream
streams , .

streams Java System.out


, System.in System.err ( stderr
C). System.in (instance) InputStream System.out
System.err PrintStream ('
print() println()).

InputStream & OutputStream


InputStream :

int available() bytes
stream.
void close() stream .
int read() byte stream
int, -1
.
int read(byte buffer[]) bytes (
buffer[],
buffer.length)
buffer.
bytes , -1
.

Java 46

int read(byte buffer, int bytes (
offset, int maxBytes) maxBytes)
buffer, offset.
bytes
, -1
.
long skip(long numBytes) ( ) numBytes bytes
stream ,
bytes .
1 InputStream

OutputStream:

void close() stream .
void flush()
void write(int b) stream byte b. b
int, casting
byte .
void write(byte buffer[]) buffer (
buffer.length) stream .
void write(byte buffer, buffer (
int offset, int maxBytes) maxBytes) offset,
stream .
2 OutputStream

,
InputStream OutputStream read() write() .
.

(I/O) , Java,
exception ( the method throws an exception).
InputStream, OutputStream
(package) Java java.io, Exceptions
, Exception java.io,
IOException. , java.io.IOException.
Java packages: Java ,

. ,
(C, C++).
,
.

Java 47
Java , ,
, , .
, , java.io.

import,
, :

import java.io.*;


java.io ( ) .

InputStream OutputStream,
( copy
DOS cp UNIX). CopyFile
:
C:\> java CopyFile file1.dat file2.dat

file1.dat file2.dat. file2.dat ,


.
(Usage).
import java.io.*;

class CopyFile {
// main() IOExceptions
public static void main(String args[]) throws IOException {
int i;
FileInputStream fin;
FileOutputStream fout;

// block try
try {
//
try {
fin = new FileInputStream(args[0]);
} catch (FileNotFoundException exc) {
System.out.println(Input file not found: + args[0]);
return;
}

//
try {
fout = new FileOutputStream(args[1]);
} catch (FileNotFoundException exc) {
System.out.println(Error opening output file: + args[0]);
return;
}
// ,
// args[] exception.
} catch (ArrayIndexOutOfBoundsException exc) {
System.out.println(Usage: CopyFile From To);
return;

Java 48
}

//
// :
try {
do {
i = fin.read();
if (i != -1) //
fout.write(i); // fin
} while (i != -1);
} catch (IOException exc) {
System.out.println(File error);
}

//
fin.close();
fout.close();
}
}


FileInputStream FileOutputStream, .

copy. Linux Pentium III/ 700 Mhz,
56 MB cp 11 .
, 4 44 !!!

read() write()
buffer. ,
:
// 2
// blocks . 16384 bytes
//
//
int bufsize = 16384;
byte buffer[] = new byte[bufsize];

//
// :
try {
do {
// buffer, i
// bytes .
i = fin.read(buffer);
if (i != -1)
// fin
// fout bytes buffer
// read()
fout.write(buffer, 0, i);
} while (i != -1);
} catch (IOException exc) {
System.out.println(File error);
}

Java 49
.
8,6 !
.
byte streams
(..
ByteArrayOutputStream,
(pipe) PipedInputStream, ).
.

Streams
, Java
, streams (character streams).
' InputStream
OutputStream .
() Reader Writer
streams :


Reader ()
character stream (input).
Writer ()
character stream (output).
BufferedReader Stream buffer .
BufferedWriter Stream buffer .
CharArrayReader Stream .
CharArrayWriter Stream .
FileReader Stream .
FileWriter Stream .
FilterReader Stream .
FilterWriter Stream .
InputStreamReader Stream bytes .
LineNumberReader Stream .
OutputStreamWriter Stream bytes.
PipedReader Stream (pipe).
PipedWriter Stream (pipe).
PrintWriter Stream print() println().
PushBackReader Stream .
StringReader Stream String.
StringWriter Stream String.

Java 50
, Reader Writer,
InputStream OutputStream,
:

int available() bytes
stream.
void close() stream .
int read()
stream int, -1
.
int read(char buffer[]) (
buffer[],
buffer.length)
buffer.
, -1
.
abstract int read(char (
buffer, int offset, int maxChars)
maxChars) buffer, offset.

, -1
.
long skip(long numChars) ( ) numChars
stream ,
.
3 Reader

Writer:

abstract void close() stream .
abstract void flush()
void write(int ch) stream ch. ch
int,
casting char .
void write(char buffer[]) buffer (
buffer.length) stream .
abstract void write(char buffer (
buffer, int offset, int maxChars) offset,
maxChars) stream .
void write(String str) String str stream .

Java 51

void write(String str, int String str (
offset, int maxChars) maxChars) offset,
stream .
4 Writer
, stream
. ,
(
FileReader) BufferedReader.

( type DOS more/less UNIX).
PrintWriter.
System.out.println(), ,
(
, ).
import java.io.*;

class PrintFile {
public static void main(String args[]) {
//
FileReader fr;
BufferedReader br;
PrintWriter pw;
String str;

//
// .
if (args.length == 0)
System.out.println("Usage: PrintFile <file>...");

// block exceptions
try {
// PrintWriter
pw = new PrintWriter(System.out, true);

// , FileReader.
// FileReader, BufferedReader.
for (int i=0; i < args.length; i++) {
fr = new FileReader(args[i]);
br = new BufferedReader(fr);

// BufferedReader,
// . , PrintWriter
while ((str = br.readLine()) != null)
pw.println(str);
}
} catch (IOException e) {
System.out.println("File error: " +e);
}
}
}

Java 52
10.
Java.

, Java
Streams. Java
/stream Internet,

.

. java.net
TCP/IP UDP. ,
: URL, URLConnection, Socket, and ServerSocket
TCP, DatagramPacket, DatagramSocket, and MulticastSocket
UDP.

URL
(
HTTP, HTTPS, FTP, ),
web browsers. URL Uniform Resource
Locator.
, www.mysite.net, URLs
:
http://www.mysite.net/
http://www.mysite.net/pages/article.html

URL
:
URL mysite = new URL("http://www.mysite.net/pages/");
URL mysiteArticle = new URL(mysite, "article.html");
URL mysiteForm = new URL(mysite, "form.html");

, URL
(constructor) :
URL(URL baseURL)
URL(URL baseURL, String relativeURL)

URL
string, Exception MalformedURLException.
try {
URL myURL = new URL(. . .)
} catch (MalformedURLException e) {
. . .
// Exception
. . .
}

Java 53
URL, URL
.
:


String getProtocol() (http, ftp).
String getHost() , ..
www.mysite.net.
String getFile() , ..
/pages/article.html.
String getPort() ( 80
http 21 ftp).
String getRef()
( '#').

, URL.

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

public class ParseURL {


public static void main(String[] args) throws Exception {
URL aURL = new URL("http://java.sun.com:80/docs/books/"
+ "tutorial/index.html#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("host = " + aURL.getHost());
System.out.println("filename = " + aURL.getFile());
System.out.println("port = " + aURL.getPort());
System.out.println("ref = " + aURL.getRef());
}
}

:
protocol = http
host = java.sun.com
filename = /docs/books/tutorial/index.html
port = 80
ref = DOWNLOADING

URLConnection
URL,
URLConnection, HTTP.
URL
' .

Java 54
URLConnection
URLConnection :
import java.net.*;
import java.io.*;

public class URLConnectionReader {


public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null)


System.out.println(inputLine);
in.close();
}
}

openConnection() URL,
URLConnection yc.

www.yahoo.com, Streams (.
). , BufferedReader
InputStream www.yahoo.com.
URLConnection InputStream
getInputStream() ,
.

URLConnection
, HTML Internet

server ( ).
browser, CGI (
Perl/PHP/ASP/),
HTML. POST (POST METHOD)
HTML. Java
URL,
. ,
:
URL (, URL)
URL ( URLConnection)
URLConnection
stream (OutputStream).
(input stream) CGI server.
stream .

Java 55
stream .
-
Sun Java. HTML
browser .
import java.io.*;
import java.net.*;

public class JavaSearch {


public static void main(String[] args) throws Exception {

if (args.length != 1) {
System.err.println("Usage: java JavaSearch <string>");
System.exit(1);
}

String msg = URLEncoder.encode(args[0], "ISO-8859-1");

URL baseurl = new URL("http://onesearch.sun.com/");


URL url = new URL(baseurl, "search/developers/index.jsp");

URLConnection connection = url.openConnection();


connection.setDoOutput(true);

PrintWriter out = new PrintWriter(


connection.getOutputStream());
out.println("qt=" + msg);
out.close();

BufferedReader in = new BufferedReader(


new InputStreamReader(
connection.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null)


System.out.println(inputLine);

in.close();
}
}

:
if (args.length != 1) {
System.err.println("Usage: java JavaSearch <string>");
System.exit(1);
}

String msg = URLEncoder.encode(args[0], UTF-8);


, UTF-8
msg ( String).
msg CGI (

Java 56
browser ),
.
URLEncoder.
URL,
, URLConnection
:
URL baseurl = new URL("http://onesearch.sun.com/");
URL url = new URL(baseurl, "search/developers/index.jsp");

URLConnection connection = url.openConnection();


connection.setDoOutput(true);

stream
PrintWriter:
PrintWriter out = new PrintWriter(c.getOutputStream());

(
CGI script) getOutputStream()
UnknownServiceException.
stream
server.
stream .
PrintStream ( ..
System.out):
out.println("qt=" + msg);
out.close();

println().
. Java
.
(.. sockets TCP/IP,
packets, )
.
CGI script ,
HTML ( browser).
InputStreamReader,
- ( readline()):
BufferReader in = new BufferedReader(
new InputStreamReader(c.getInputStream()));
String inputLine;

while ((inputLine = in.readLine()) != null)


System.out.println(inputLine);
in.close();

(System.out)
.

Java 57
URL

, CopyFile. URL
CopyFile.
FileInputStream ,
URL URLConnection.

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

public class URLConnectionReader {


public static void main(String[] args) throws Exception {
URL from;
FileOutputStream fout;
int i;

try {

try {
from = new URL(args[0]);
} catch (MalformedURLException exc) {
System.out.println("Error opening URL: " + args[0]);
return;
}

try {
fout = new FileOutputStream(args[1]);
} catch (FileNotFoundException exc) {
System.out.println("Error opening output file: " + args[0]);
return;
}
// ,
// args[] exception.
} catch (ArrayIndexOutOfBoundsException exc) {
System.out.println("Usage: URLConnectionReader From To");
return;
}

URLConnection yc = from.openConnection();
InputStream fin = yc.getInputStream();

//
// :
int bufsize = 8192;
byte buffer[] = new byte[bufsize]; //
// 2
//
// blocks

try {
do {
i = fin.read(buffer);
if (i != -1) //

Java 58
fout.write(buffer, 0, i); // fin
} while (i != -1);
} catch (IOException exc) {
System.out.println("File error");
}

in.close();
}
}

Sockets
sockets
TCP/IP, Internet,
. sockets
URLConnection, Java
(.. C/C++)
sockets streams. Java
Socket, socket (client)
ServerSocket, sockets
/ (server).
ServerSocket,
Socket.
server
server.
( EchoClient), server
echo. echo
.
7 (port 7).
EchoClient Echo server socket,
. server
client .
server
client. , FTP, HTTP ,
client server
(.. ).
EchoClient:
import java.io.*;
import java.net.*;

public class EchoClient {


public static void main(String[] args) throws IOException {

Socket echoSocket = null;


PrintWriter out = null;
BufferedReader in = null;

try {
echoSocket = new Socket("server", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);

Java 59
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: servername.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: servername.");
System.exit(1);
}

BufferedReader stdIn = new BufferedReader(


new InputStreamReader(System.in));
String userInput;

while ((userInput = stdIn.readLine()) != null) {


out.println(userInput);
System.out.println("echo: " + in.readLine());
}

out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}

.
try.
Socket server PrintWriter BufferReader Socket.
echoSocket = new Socket("server", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));

Socket echoSocket.
Socket ,
.
server,
server .
, IP DNS
(FQDN). 7 ( echo).
PrintWriter
BufferReader Socket. Reader Writer
Unicode.
socket PrintWriter
BufferedReader.
.
loop while,
(System.in) ,

Java 60
BufferedReader.
socket PrintWriter:
String userInput;

while ((userInput = stdIn.readLine()) != null) {


out.println(userInput);
System.out.println("echo: " + in.readLine());
}

readLine(),
(stdIn) socket (in).
readLine() server client.
, echo: .
end-
of-input. loop
:
out.close();
in.close();
stdIn.close();
echoSocket.close();

.
PrintWriter BufferedReader socket,
BufferedReader
socket, server.
. socket
streams .
,
echo.
server (
server). server
client
( )
. :
socket.
stream stream socket.
streams server.
streams.
sockets.

Java 61
11. (JDBC)
Java
Java
SQL (Oracle, DB2, MS SQL, MySQL, PostgreSQL, ODBC, ).

(
API, ) Java
API
, .



, . : )
(driver) ) .


.
, JDBC-ODBC,
:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");



. ,
jdbc.DriverXYZ,
:
Class.forName("jdbc.DriverXYZ");



,
:
Connection con = DriverManager.getConnection(url,
myLogin", "myPassword");

,
url, .
JDBC-ODBC, url jdbc:odbc:.
(DSN) . ,
, ODBC
myBase url jdbc:odbc:myBase.
myLogin
myPassword, , ..
Fred Fl1ntst0n3. :

Java 62
String url = "jdbc:odbc:myBase";
Connection con = DriverManager.getConnection(url, "Fred", "Fl1ntst0n3");

JDBC ( Sun)
,
, jdbc:
(.. acme, url
jdbc:acme).
.
DriverManager ,
getConnection(),
JDBC.

. con.


.
BIKES
.
BIKES:
BIKE_NAME SUP_ID PRICE SALES TOTAL
Yamaha XT 500 101 5.000,00 0 0
KTM Adventurer 650 49 7.300,00 0 0
Kawasaki KLE 500 150 5.300,00 0 0
Honda TransAlp 650 101 7.900,00 0 0
Susuki VStrom 650 49 7.000,00 0 0
BMW FS 650 150 8.900,00 0 0

(BIKE_NAME)
VARCHAR ( 32 ).
(
) .
, SUP_ID, INTEGER.
, PRICE,
FLOAT. SQL NUMERIC DECIMAL
,
.
, SALES TOTAL,
, INTEGER.
, SUPPLIERS,
:

Java 63
SUP_ID SUP_NAME STREET CITY ZIP
101 313 13131
49 7 76767
150 1 10000

BIKES SUPPLIERS SUP_ID,



SELECT. SUP_ID SUPPLIERS
.
BIKES , .

SELECT.
BIKES
.:
CREATE TABLE BIKES ( BIKE_NAME VARCHAR(32), SUP_ID INTEGER,
PRICE FLOAT, SALES INTEGER, TOTAL INTEGER )

( , JDBC
.)
JDBC,
String. Java ( )
string ,
'+'.:
String createTableBikes = "CREATE TABLE BIKES " +
"(BIKE_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " +
"SALES INTEGER, TOTAL INTEGER)";

JDBC
SQL JDBC
Statement. Statement SQL
,
.
Statement, executeQuery() SELECT
executeUpdate()
. Statement :
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE BIKES ( BIKE_NAME VARCHAR(32), SUP_ID
+ INTEGER, PRICE FLOAT, SALES INTEGER, TOTAL INTEGER)");

, stmt
executeUpdate().
String SQL BIKES,
:
stmt.executeUpdate(createTableBikes);

Java 64

BIKES
. executeUpdate()
SQL:
Statement stmt = con.createStatement();
stmt.executeUpdate ( "INSERT INTO BIKES " +
"VALUES ('Yamaha XT 500', 101, 5000, 0, 0)");

BIKES .
Statement
.
stmt.executeUpdate ( "INSERT INTO BIKES " +
"VALUES ('KTM Adventurer 650', 150, 7300, 0, 0)");
stmt.executeUpdate ( "INSERT INTO BIKES " +
"VALUES ('Kawasaki KLE 500', 150, 5300, 0, 0)");
stmt.executeUpdate ( "INSERT INTO BIKES " +
"VALUES ('Honda TransAlp 650', 150, 7900, 0, 0)");
stmt.executeUpdate ( "INSERT INTO BIKES " +
"VALUES ('Susuki VStrom 650', 150, 7000, 0, 0)");
stmt.executeUpdate ( "INSERT INTO BIKES " +
"VALUES ('BMW FS 650', 150, 8900, 0, 0)");

SUPPLIERS.



SELECT. ,
SQL :
SELECT * FROM BIKES

:
BIKE_NAME SUP_ID PRICE SALES TOTAL
--------------- ------ ------- ----- -----
Yamaha XT 500 101 5000,00 0 0
KTM Adventurer 650 49 7300,00 0 0
Kawasaki KLE 500 150 5300,00 0 0
Honda TransAlp 650 101 7900,00 0 0
Susuki VStrom 650 49 7000,00 0 0
BMW FS 650 150 8900,00 0 0

, :
SELECT BIKE_NAME, PRICE FROM BIKES

:
BIKE_NAME PRICE
--------------- -------
Yamaha XT 500 5000,00
KTM Adventurer 650 7300,00
Kawasaki KLE 500 5300,00

Java 65
Honda TransAlp 650 7900,00
Susuki VStrom 650 7000,00
BMW FS 650 8900,00


7100 :
SELECT BIKE_NAME, PRICE FROM BIKES WHERE PRICE < 7100

The results would look similar to this:


BIKE_NAME PRICE
--------------- -------
Yamaha XT 500 5000,00
Kawasaki KLE 500 5300,00
Susuki VStrom 650 7000,00

SQL ,
SQL. Java
ResultSet JDBC.

ResultSet
,
executeUpdate()
, SELECT, executeQuery().
executeQuery()
ResultSet. executeQuery()
:
ResultSet rs = stmt.executeQuery(SELECT BIKE_NAME, PRICE FROM BIKES");

rs SELECT,
.
. JDBC 1.0
( ),
JDBC 2.0 3.0
. , 1.0
.

next
next() ResultSet.
next(), (cursor)

( ).

ResultSet ( SQL
executeQuery()). ResultSet
, next()
ResultSet.

Java 66
getXXX
,
.
, CREATE TABLE,
Java.
(..
encoding, ISO-8859-7, TIMESTAMP). Java

( ).
, BIKE_NAME
SELECT ( VARCHAR), getString()
ResultSet, PRICE getFloat().
executeQuery(), ResultSet,
next(), getXXX() .
,
.
String query = "SELECT BIKE_NAME, PRICE FROM BIKES";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString("BIKE_NAME");
float n = rs.getFloat("PRICE");
System.out.println(s + " " + n);
}

:
Yamaha XT 500 5000,0
KTM Adventurer 650 7300,0
Kawasaki KLE 500 5300,0
Honda TransAlp 650 7900,0
Susuki VStrom 650 7000,0
BMW FS 650 8900,0

JDBC getXXX()
.
,
ResultSet.
1, 2, .
:
String s = rs.getString(1);
float n = rs.getFloat(2);


,
.
JDBC SQL.
:

Java 67

SQL
getByte() TINYINT SMALLINT, INTEGER, BIGINT, byte
REAL, FLOAT, DOUBLE, DECIMAL,
NUMERIC, BIT, CHAR, VARCHAR,
LONGVARCHAR
getShort() SMALLINT TINYINT, INTEGER, BIGINT, REAL, short
FLOAT, DOUBLE, DECIMAL,
NUMERIC, BIT, CHAR, VARCHAR,
LONGVARCHAR
getInt() INTEGER TINYINT, SMALLINT, BIGINT, int
REAL, FLOAT, DOUBLE, DECIMAL,
NUMERIC, BIT, CHAR, VARCHAR,
LONGVARCHAR
getLong() BIGINT TINYINT, SMALLINT, INTEGER, long
REAL, FLOAT, DOUBLE, DECIMAL,
NUMERIC, BIT, CHAR, VARCHAR,
LONGVARCHAR
getFloat() REAL TINYINT, SMALLINT, INTEGER, float
BIGINT, FLOAT, DOUBLE, DECIMAL,
NUMERIC, BIT, CHAR, VARCHAR,
LONGVARCHAR
getDouble() FLOAT, DOUBLE TINYINT, SMALLINT, INTEGER, double
BIGINT, REAL, DECIMAL, NUMERIC,
BIT, CHAR, VARCHAR, LONGVARCHAR
getBoolean() BIT TINYINT, SMALLINT, INTEGER, boolean
BIGINT, REAL, FLOAT, DOUBLE,
DECIMAL, NUMERIC, CHAR,
VARCHAR, LONGVARCHAR
getString() CHAR, VARCHAR TINYINT, SMALLINT, INTEGER, String
BIGINT, REAL, FLOAT, DOUBLE,
DECIMAL, NUMERIC, BIT,
LONGVARCHAR, BINARY, VARBINARY,
LONGVARBINARY, DATE, TIME,
TIMESTAMP
getDate() DATE CHAR, VARCHAR, LONGVARCHAR, Date
TIMESTAMP
getTime() TIME CHAR, VARCHAR, LONGVARCHAR, Time
TIMESTAMP
getTimestamp TIMESTAMP CHAR, VARCHAR, LONGVARCHAR, Timestamp
() DATE, TIME

getString

SQL (
SQL3). (
) String,
. .

Java 68

7 , Susuki VStrom
650, 4 BMW FS 650. SALES TOTAL
BIKES UPDATE SQL.
:
String updateString = "UPDATE BIKES SET SALES = 7 " +
"WHERE BIKE_NAME LIKE 'Susuki VStrom 650'";
stmt.executeUpdate(updateString);

VStrom,
String updateString = "UPDATE BIKES SET SALES = 4 " +
"WHERE BIKE_NAME LIKE 'BMW FS 650'";
stmt.executeUpdate(updateString);

BMW.
BIKES :
BIKE_NAME SUP_ID PRICE SALES TOTAL
--------------- ------ ------- ----- -----
Yamaha XT 500 101 5000,00 0 0
KTM Adventurer 650 49 7300,00 0 0
Kawasaki KLE 500 150 5300,00 0 0
Honda TransAlp 650 101 7900,00 0 0
Susuki VStrom 650 49 7000,00 7 0
BMW FS 650 150 8900,00 4 0

TOTAL .
:
String updateString = "UPDATE BIKES SET TOTAL = TOTAL + 75";
stmt.executeUpdate(updateString);

TOTAL (
Susuki VStrom
BMW FS).

:
String query = "SELECT BIKE_NAME, SALES, TOTAL FROM BIKES " +
"WHERE SALES > 0";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String name = rs.getString(BIKE_NAME);
int sold = rs.getInt(SALES);
int tot = rs.getInt(TOTAL);
System.out.println(name+: Sold + sold +
bikes this week, + tot + in total);
}

:
Susuki VStrom 650: Sold 7 bikes this week, 7 in total
BMW FS 650: Sold 4 bikes this week, 4 in total

Java 69

Das könnte Ihnen auch gefallen