Vous êtes sur la page 1sur 90

JAVA

JAVA
/ /

-1.

JAVA

1
1. Java
1.1.

Java ?

Java 1991 Green Sun Microsystems


.
.
Start
++ .
James Gosling ++- .
Start- .
Oak , offise- Oak
. Oak
Sun Java .
Java .

. , Windows
MFC (Microsoft Foundation Classes)- . Mac
Mac OS Toolbox- .
//-
,
.
Internet- .

. Java
JVM /Java Virtaal Machine/ in-built . JVM

.
++- , Java . Java
.

, .
++-
.
.

.
1.2.

Java

Java 3 . Java
Java 1.0 , brokser-
. Java 1.1 , ,
. Java
Sun Java 2 Java 1.2.2-
.

-2.

JAVA

Java . Java
JDK /Java Devolepment Kotekit/ 1.0, 1.1, 1.2 . JDK-
http://java.sun.com/products/jdk .
Java- : Java Workshop,
Borland Jduilder, Symantec Visul Case, Visual Java /VJ++/, SuperCede .
1.3.

Java-

Java
.

Java
. Java
. Java
.
JVM Java Virtual Machine- . JVM

.
Java ,
. Java
.
Java 2 . Java
, interpret
.
Java /.class file/ .
.
, JVM- .
JVM , .
. class
. HTML-
.class .
.
. Java
, . Java- ,
HTML . Java
HTML .
Java
Java .
, ,

.

-3.

JAVA

----------------


(.java )

Java

00110100
01000100
01000010
01011000


(.class )

1.1 .

,
,
.
.
, File not found , .
!
Java- garbage collection exception handling
.
Garbage collection
daemon / , / thread
.
Daemon thread - / thread/
heap .
Exception handling :
Exception handling

.
,
Java
,
, ?

-4.

JAVA

, ,
. Java
Java

.
, , Java
. Java
,
.

. Java Java
. .
. Java
/, /
. /digital sign/
/hack/
.
,

Java .

. ,
. Java
, .
Java .
Distributed
Java .
Java ,
.

2
1.4.

Java

Java 2 , /
/
,
.
Java . Internet Explorer 3.1
- .

-5.

JAVA

, .
// ,
.
, .
,
/
/ .
1.4.1
Java
. ,
++- . .
.
JVM
. /initrating class/ . Pullic
, . JVM-
. main compiler-
.
.
.
public class SimpleApp {
public static void main(String args[ ]) {
System.out.println( );
}
}
JDK- . DOS editor,
notepad .
.java , SimpleApp.java
.
main() . public
main() , . main()
. Static main()
JVM main ( ) . void
main () .
System.ont.println() .
.
(javac) .
path=;c:\java\bi;c:\java\lib;c:\java2\include Java 2- Java
.
C:> javac SimplApp.java
byte .class .
C: > java SimpleApp

-6.

JAVA

1.4.2
- .
main . -
.
Import java..*;
Import java.awt.*;
Public class Apple extuds
{
public veid paint (graphics) {
g.drawstring C An apple a Day Keeps the Doctor Away, 50,50);
}
}
2 - .

(librory) . java.
paint ()
, java.- main
include . extends .
Paint (Graphics-) - , .
- .
. paint() Graphics - . -
drawString (String text, int posx, int posy) .
.java ,
.
Javac Apple.java
byte .class . .class
HTML .
HTML :
<html>
<head>
<title> The is Rumming </title>
</hend>
<body>
< code=Apple heigt=200_width=200>
</>
</html>
1.5.

Java

1.5.1

-7.

JAVA

xor

+
*
/
%
++
+=
-=
*=
/=
%=
-~
&
\
^
>>
>>>

Int no =1+1
Int no =1-1
Int no =1*1
Int no =1/1
Int no =1%1
no++ ++no
no+=4
no- =4
no* =4
no/ =4
no%=4
no- - - - no
~a
a&b
a\b

<<
==
!=
>
<
>=
<=

1.5.2
Java- 8 . , ,
.
.

Byte
Short
Int
Long
Double
fleat
char

8
16
32
64
64
32
16

-128 127
-32768 32767
-2147483647 2147483647
- 2 63 2 63 -1
1.7e 308 1.7e + 308
3.4e 038 3.4e +038
0- 65536



Java

Unicode


.
Char choice=1y 1;
Char trop = 27;

-8.

JAVA

boolean

True/false

Boolean flag=true;

1.5.3 (Statemant and Expressions )


. Java
.
Dear reply = y;
Int book no;
System.ont.println( resulting statemant g)
Java (semicolon) .
, {} . ,
.
---------------------------------{
int count=0;
------------------------------{
count=count+1;
------------------------------}
}
,
.
1.5.4 () (Variables and Literals)
.
:
Type identifier=value;
, boolean status=true; int heigt=60;
, lilly, tulip, 100, 5179, 79 .
1.5.5
: // / * * / . //
.
compiler
.
/ * * / .
.
1.5.6 (Scope)

-9.

JAVA

.
. :
Public class Visibility
{
public Static void main (String args [ ] ) {
block 1 :
// label
{
int gvar = 100;
block 2:
{
int lvar = 200;
system.out.println ( + gvar);
system.out,println ( + lvar);
}
}
gvar=gvar+1;
System.out.println ( + gvar);
Lvar =lvar+1; //
}
}
}
: Java-
.
, gvar block2 .
1.6

. Java
++ - .
1.7


. . .
Public class EnyBenus
{
public static void main (String args [ ])
{
String ebonus[ ] [ ] =new String [2][5];
Ebonus [0][0]= P.K.Roy ;

ebonus [1][4]= 5500;


for (int I=; i < 5; I ++)
{
System.out.println (Emplorgee name: + ebonus [0] [ i]);

-10.

JAVA

System.out.println (Bonus Receved: + ebonus[1][i]);


}
}
}
Java- ,
:
Type name[ ] = new type [no.of elements];
: int item_code [ ] = new int [10];
String week Days [ ]= new String [7];
New
. Java- String -
. ,
.
:
Float twoP_Array[ ] [ ]= new float [5][10];
. 2
.
Int list+[ ] [ ] = new int [2][ ];
List[0] = new int [6];
List[1] =new int [15]

3
2.
2.1.

Java
-

.

.
.
.
.

, .
.
.,
,
.
.
.
.
.

-11.

JAVA

,
.
.
.
.
. ,
, .
(, , .)
( ) .
() (
) .
.
, , , ,

, .
,
.
2.1.1
.

2.1.2

.
, Order Processing System- ,
. (item) , , ,
. ,
. Order Processing System-
, .

.
2.1.3

.
.
Order Processing System- .
, . :
a)
b) / /
c)
d)
e) .

-12.

JAVA

ItemNo
Description
Rate
Quantity on hand
Reorder Level

Print Details
Accept Details
Change QOH
Display Value
Reorder Status


,
.
2.1.4

.
sub-
. , order Processing System- Item
. .
Item Printer, Stationery, Floppy disk sub- .
sub- itemno, description, rate, qurantity on hand,
reorder level , super item- .
Printer sub /laserjet Inkjet/, . Stationory
Super . Floppy disk super
2 - . .

Item
Item No
Description
Rate
Quantity on hand
Reorder level

-13.

JAVA

Printer

Stationery

Floppy disk

2.1.5

Type
Pages Per Minute

Site

Capacity
Site

. , show Printer Floppydisk


.
2.2

. Item class-
Java .
Class Item {
Private
Private
Private
Private
Private

int itemno;
string description;
float rate;
int goh;
int roe;

Public void display () <


System.out.println (Item Details);
Sistem.out.println (. . . . . .. . . . );
Sistem.out.println (Item number
: + itemno);
Sistem.out.println (Description
: + description);
Sistem.out.println (Rate
: + rate );
Sistem.out.println (Quantityon hand : +
);
Sistem.out.println (Reoder level
: + roe);
Public void change QOH ( int qty, char Status) {
If (Status == A)
Qch=qch+qty;
Else
If (status = = S)
Qoh=qoh-qty;
}
public void accep+Details ( int ino, String desc, float rt, int qty, int reorder) {
itemno=ino;
description=desc;
rate=rt;
qoh=qty;
rol=roerder;
}
2.3

(Memory Management)

-14.

JAVA

Java .

. Java- .

.
.
Item I;

I= w Item () ;
.
.
.
.
,
.

Item
Assept Details
Display
Change QOH
Item A

Item B

1
Nuts & Botts
23.56
100
23

2
Hammer
75.89
156
50

Java -
. Java

.
.
, handl,
.

.
Finalite()

-15.

JAVA

finalitation . Finalite()
:
Protected void finalite () {
.
.
}
.
Finalite() . Finalite()
, .
,
.
Runtime
Runtime run-time . Run-time
Runtime . getRuntime()
run-time .
gc() .
.
.
.
Runtime r=Runtime, getRuntime();
r.gc();
2.4

Java
. : int- float , float-c double . Casting
.
(int8 flout8 boolean .) ,
(String, Point, Integer .)
.
2.4.1

. boolean true false
.
. ,
: int- long .
. .
,
. .
(data type)value
float int .
..
int i ;

-16.

JAVA

float f=6.7;
I=(int)f;
.
. I 6
, .
.
.
Int i =1078;
Double d;;

2.4.2
. 2
, .
sub .
.

. sub super
.
, sub .
sub super
. -
. sub super
. .
(class name) object
.: Item new Item ();
Printer P= new Printer();
I=P;
// , .
P=I;
// ,
P=(printer) I; //
2.4.3
vice versee Java-
.
.
Java . Java.long
. :
Integer int , Boolean, Byte8
Character, Long, Void, Double, Float . .

. : String int :
String str = nek String (4578);
Int i = Integer.Parse Int (str);
String- str Integer parse Int
.
4
2.5

-17.

JAVA


. .

. Item
.
Item() 1
Itemno=0;
Description = nek String ();
Rate = 0.0 f;
Goh = 0;
Rol =0;
}
.
:
Item I= new Item ();
Java default .
.
.
2.5.1
.
?
, .
. Item-
2 ,
.
Class Item {
Private
Private
Private
Private
Private

int itemno;
String description;
float rate;
int goh;
int rol;

Public void display () {


System. out. println (Item details);
System. out. println (Item details);
System. out. println (Item number
: + itemno);
System. out. println (Description
: + description);
System. out. println (Rate
: + rate);
System. out. println (Quantity on hand : + qoh);
System. out. println (Reoder level
: + rol);
}
public void change QOH (int, qty, char status) {
if (Status == A)
qoh = qoh + qty;

-18.

JAVA

else if (status == s)
qoh=goh qty;
}
public void accapt Details ( int ino, string dese, float rt, int qty, int reorder);
{
itemno = ino;
description = desc;
rate = rt
qoh = qty;
rol = reorder;
}
Item () {
// 1
Itemno = 0;
Deseription =
Rate = 0. 0 f;
Roh = 0;
Roe = 0;
}
Item (string str) { // 2
Itemno = 0
Description = str;
Rate = 0.0 f;
Roh = 0;
Roe = 0;
}
}
Item.Java
Import Item;
Class Try Item {
Public
void
(string args [ ] ) {
Item I=new Item (); // 1-
i.
display;
string d=new string (Nuts 2 Bolts);
Item I=new Item (d);
// 2-
i.
display;
/* , */
item k=new Item (1, d);
k.display();
}
}
Try Item.java
Item .
Default
2
.
2.5

== () .
:

-19.

JAVA

Class Compint {
Public strtic void main (string args [ ] ) {
Int x= 33;
Int y=33;
If ( x==y)
System.out.println (Equal);
Else
System.out.println (Not Equal);
, Equal . Integer

Class CompInteger {
Public static void main (String args [ ]){
Integer x= new Integer (33);
Integer y= new Integer (33);
If (x==y)
System.out.println (Equal);
Else
System.out.println ( Not Equal);
}
33 Not Equal
. == 2 .
, , Not Equal.

33

33

Equal
.
Integer y;
y = x;
33 .
.
Integer ,
. = -
.

-2033

JAVA

, 2 ==
. equals ()
.
:
Class CompInteger {
Public static void main (string args [ ]) {
Integer x= new Integer (33);
Integer y= new Integer (33);
If (x.equals (y))
System.out.println (Equal);
Else
System.out.println ( Not Equal);

2.6

.
.
Item 5 , 3 , 2 . Item
Printer- .
Import Item;
Class Printer extends Item {
String type;
Int ppm;
Printer () {
// 1
Super () ;
Type ;
Ppm=0;
}
Printer (int ino8 string desc, float rt, int qty, int reorder, string type, int ppm){
Super (ino, desc,rt, qty, reorder); // 2
This.type = type;

-21.

JAVA

This.ppm = ppm;
}
public void display () {
super.display (); // super display
system.out.println (Printer-
: + type);
system.out.println (
: + ppm);
Printer.java
Import java.lang.*;
Import Printer;
Class Try In herit {
Public static void main (String args [ ]){
Item I=new Item (1, Mouse, 500.89f 1200, 200);
i. display ();
Printer p=new Printer (2, Inkjet Printer, 10000.75f, 200.35, 6P, 6);
P. display () ;
}
}
Try Inherit.java
Super super . Printer
1- Super () Item super 2- super
(ino, desc, rt, qty, reorder) Item super
( 1) . Printer 2- super
(ino, desc, rt, qty, reorder) Item super
( 2) . Printer display display
5 2
. Sub
. Printer- 2 this
. this
. 2
(type) .
, .
this.type = type .
2.7


. 2 , static
.
Static .
:
2 :
Change QOH (int, char)
Change QOH (int)
: Change QOH (30);

-22.

JAVA

.

. 2
. ( int char)
.

.
Dynamic .
.
.
Item Printer . Printer Item
sub . (Item)
Item Ptinter
.
Import Ptinter;
Import java.io.*;
Class Try Poly {
Public static void main (string args [ ]) {
Item I;
Int ch =0;
While ( ch ! = P && ch! = N)
{
System.out.println( Item N, Printer P
);
Try {
Ch=System.in.read();
}Catch (I 0 Exception e) {
System.out.println (Error); }
}
if (ch==p)
I=new Println (1, Laser jet, 20000f, 100,25. III plus, 8);
Else
I=new Item (1, Mouse Logitech, 300f, 100, 20);
i.
display ();
}
}
(TryPoly.java)
2.8

Java
.
Java :
Java { class file name}
: TryPoly.class java TryPoly
:
Java TryPoly c1 c2 c3
c4 c5
1 , 2 ..
.
.

-23.

JAVA

TryPoly.java .

.
Java .
Java
main() .
. :
Public class TryMain Arguments {
Public static void main (string [ ] args)
{
int I =0;
for ( I=0; I < args.lugth; I ++) {
System.out.println ( + (I+1) + ; + args [i]) ;
}
}
}
.
TryPoly.java :
Class TryPoly 1 {
Public static void main (String args [ ]) {
Item :;
If (args. Length !=1) {
System.out.println ( );
System.exit (0); }
If (args [0]. Equals (P)) {
I=new Println (1, Laserjet, 20000 f, 100, 25, III plus, 8);
i.display () ;
}
else
if (args [0]. Equals (N)) {
I=new Item (1, Mouse logitech, 300f, 100, 20);
i.
display ();
}
else {
System.out.println ( .);
System.exit (0);
}
}
}
5
3.1

-24.

JAVA


.
.

.
, public, private, protected,
.

.


.

.
.
3.1.1 Default

. public
default .
3.1.2 Public
Public ,
.
3.1.3 Privite
, public
.
3.1.4 Protected
Protected
.

3.1.5 Static
static-
.
.
Static <type name> <variable>;
static-
. Static
. Static
static ,
, super .
Static static-
. static .
.

.

-25.

JAVA

Class Static_Block
{
Static int a;
Static
{
a=a+10;
}
public static void main (String args [ ])
{
System.out.println ( a- : +a);
}
}
main () static , a
main () .
3.1.6 Final
Final . final
,
. :
Final int radias =34
Final float pi =3. 1428f;
Float
f
.
final
, . Final
sub .
3.2

.

.
.
,
. run time
.
.,
.
,
.
,
.

.

-26.

JAVA

.
, , .

.

.
.
.
3 get.Payment
() Payment
, , 3
.
Abstruct class Payment
{
int file_Number;
String customer_Name;
String customer_Address;
Void accept_ Cust_Details ()
{

}
Payment ()
{
//
}
}
abstruct void get_Payment ();
//
class CC_Pymt extends Payment
{
void get_Payment ()
{
//
//
//
}
}
class Chq_Pymt extends Payment
{
void get_Payment ()
{
//
//
}
}
class Cach_Pymt extends Payment
{
void get Payment ()
{

-27.

JAVA

//
}
}
public class Restaurant
{
public static void main (string args[ ])
{
payment p.cc=new CC.Pymt ();
p-cc.accept_Cust_Details();
p-cc.get_Payment ();
Payment p.chq=new chq. Pymtc ();
p-chq.accept_Cust_Details ();
p-chq.get_Payment ();
Payment p.cach =new cach_Pymt ();
p-cach.acept_Cust_Details();
p-cach.get_Payment ();
}
}
main ( ) Payment .

get.Payment () .

6
3.3
prototype-
. .

.
.
Java .

. . ,
.
.
.

, .

. : radio , television 2
. . .
sound control .
2 .
.

-28.

JAVA

final static ,
() public .
inplements .
.
Interfase < interfase name >
{
//
// prototypes
{
class <class name > inplements <interfase - name>
{
//
//
//
}
prototype-
. Lettover (
) .
.
:
Class <class - name> inplements <interfase name 1>, <interfase name 2>
{
//
//
// 1
// 2
}
, , ,
. , , RA,
, , . ,
.
.
2 , , .
. HRA, , ,
, .
.
prototype- Calcpay
.
Clerk ( ) Manager ()
.

,
. ,
Employes .
Interfase Calc Pay
{
final status string company_Name = Supersoft ltd;

-29.

JAVA

public
public
public
public
public

int calc_HRA () ;
float calc_Tax ();
float calc_Bonus ();
float calc_Super_Animation ();
float calc_Gross ();

}
class Employse
{
protected int e_id;
string ename;
protected int basic;
Employse (int meid, String name, int mbasic)
{
e_id = meid;
ename = name;
basic = m basic;
}
}
class Clerk extends Employle implements CalcPay
{
Clerc (int seid, String sname, int sbasic)
{
super (seid, sname, sbasic);
}
public int calc_HRA ()
{
if (basic < 1000)
return (500);
else
return (900);
}
public float calc_Tax ()
{
float ani_sal = basic + calc_HRA () + calc_super_animation();
if (ani_Sal > 60000)
return ((float).10*ani.sal);
else
return 0;
}
public float calc_Bonus()
{
return ((float).08 * basic) ;
}
public float calc_Super.Animation()
{
return (0);
}
public float calc _Gross()
{
return (basic + calc_HRA () + calc_Bonus () calc_Tax () );

-30.

JAVA

}
void print.Solary ()
{
System.out.println ( \ n + Calcpay.companyName);
System.out.println ( Employse Number : + e_id)
System.out.println(EmployseName
: + ename );
System.out.println(Basicsolary
: + basic);
System.out.println(HousePentAllowance: + calc_HRA());
System.out.println (Bonus
: + calc_Bonus() );
System.out.println (Taxation
: + calc_Tax () );
System.out.println ( Cross Solary : + calc_Gross () );
System.out.println ( .th );
}
}
Class Manager extends Employse implements Calc Pay
{
Manager (int seid, String sname, int sbasic)
{
super (seid, sname. sbasic);
}
public int calc_HRA ()
{
if (basic < 6000)
return (3500);
else
return (5500);
}
public float calc_Tax ()
{
float ann_Sol = basic + calc_HRA() + calc_Super_Animation ()
if (ann_sol > 130000)
return ((float).30*ann.sol);
else
return ((float).20*ann.sol);
}
public float calc_Bonus ()
{
return (0);
}
public float calc_super_Annmation ()
{
return ((float).15-basic);
}
public float calc_Gross ()
{
return (basic + calc_HRA () +calc_Super_Annmation () calc_Tax () );
}
void print_Solary ()
{
System.out.println ( + CalcPay.company Name);

-31.

JAVA

System.out.println ( Employse Namber : + e_id );


System.out.println (Employse Name : + ename );
System.out.println (Basic Solary : + basic);
System.out.println (House Rent Allowance : +calc_HRA () );
System.out.println (Taxation : + calc_Tax () );
System.out.println (Superamnation : + calc_Super_Amnation ());
System.out.println (Gross Solary : + calc_Gross () );
System.out.println (.\n );
}
}
public class Payship
{
public static void main (String args [ ] )
{
Clerk c1=new Clerk (3648, Vinay Sharma , 800);
c1.print_ Solary ();
Manager m1 =new Manager (2619, S.K Lal , 7000);
M1.print_Solary ();
}
}
. : ifase
Ifase ofj 1= new Ifase () . Ifase
obj1=new Class1 Class 1 Ifase- .
runtime .
. :
Inforfase Ifase
{
public void show ();
}
class A implemens Ifase
{
public void show ()
{
system.out.println (a);
}
}
public class B
{
public staic void main (String args [ ])
{
Ifase obj1=new A();
{
public void show ()
{
system.out.println (c);
}
}

-32.

JAVA

obj1.show ();
obj2.show ();
}
}
Ifase show () .
, show ()
. Ifase obj1=newA ()
.
.
.
new Ifase ()- .
,
show ()
.
.
3.4 ? (Package)
.
.
.
3.4.1
.
4
.
sub
sub
sub
Sub
.


Sub

Sub

Sub

Sub

private
Yes

default
Yes

protected
Yes

Public
Yes

No

Yes

Yes

Yes

No

Yes

Yes

Yes

No

No

Yes

Yes

No

No

no

Yes

. sub
private sub
. sub , private

-33.

JAVA

.
sub private default
.
. Stack , Callstack
Stack . ,
. Stack
, CallStack . Mypackage Stack
. :
<drive :\javasource files\mypackage> .
c:\javasourcefiles\mypackage ( ).
Callstack.java c:\javasourcefiles
.
Stack.java c:\javasourcefiles\mypackage .
, public
. private . .
Stack.java ,
package . :
Package mypackage;
Stack mypackage (stack.class )
. .
Stack.class Stack.java- . \javasourcefiles
Classtack.java .
Callstack.java- import.mypackage* .
public , .
Java . , classpath
.
Java .
:
Set classpath=.; c:\Java\classes; c:\javasourcefiles
,
. public
. Default public- ,
.
:
Stack.java
Package mypackage;
Public class Stack
{
private int Stck [ ];
private int Stack_Ptr;
public Stack (int site);
{
Stck=new int [site];
Stack_Ptr=-1;
}

-34.

JAVA

public void push (int item)


{
if (stack_Ptr==Stck.lenth-1)
system.out.println (Stack is fule);
else
Stck [++Stack.Ptr]= item;
}
public int pop ()
{
if (Stack.Ptr <0)
{
system.out.println (Stack underflow);
return 0;
}
else
return stck [stack_Ptr--] ;
}
}
CallStack.java
Import mypackage.*;
Public class callstack
{
public static void main (String args [ ])
{
stack s1=new Stack (5);
for (int I=0; I<5; I++)
{
s1.push (i);
}
system.out.Println (The stack contains);
for (int I=0; I<5; I++)
{
system.out.println (s1.pop ());
}
}
}
: .
.

-35.

JAVA

Subject

Course

Application

Core

optional

Applicant

Student

-36.

JAVA

(object Modelling Technique)- ,

,
.
:

5 ( )
MDMC, OCO, C++ ( )
C, C++, OOADS, JAVA, NT, VNIX, VB,
VC, ORACLE
75%- admitted.
, , .
Public class Subject {
String sname;
Subject (String name ){
This.sname=name;
}
}
subject.java
public class CoreSubject extends Subject {
CoreSubject (String name) {
Super (name);
}
public void setName (String name) {
sname-name;
}
}
CoreSubject.java . Subject
Public class OptSubject extends Subject {
OpmSubject (String name) {
Super (name)
}
public void setName (string name) {
Sname=name;
}
}
OptSubject.java . Subject .
(.)
college. Student .
Applicant :
Applicant ()
Apply for course Applicant courseName
.

-37.

JAVA

Select Optional Subjects Applicant optional subject


.
Get Functions .

Course- :
Course ()
Set antrance qualifications
Set maximum students
Check course availibility
Check entrance qualifications .
Set number of students enrolled
Get number of students enrolled
:
Receive
Approve
, ,
Package college. Student;
Import java.util.Date;
Public class Applicant {
String name;
String courseName;
String optSub;
Long result;
String address;
Applicant (String name, String add, Long res) {
This.name=name;
Address=add;
Result=res;
Course Name = name;
Optsub = mull;
}
public void apply forCourse (String selCourse) {
Course Name = selCourse;
}
public void SelectOptSubject (String oSub) {
opt Sub=oSub;
}
public String getCourse () {
return CourseName;
}
public String get OptSub () {
return optSub;
}
public void get AppDet (String sname, String add) {
sname=name;
address= add;
}

-38.

JAVA

public long getResult () {


return result. Long Value () ;
}
}
Applicant.java
Package college.student;
Public class Course {
String name;
Static int num of St;
Static int ourr St;
Long qualPere;
CoreSubject cSub [ ];
OptSubject oSub [ ];
Course (String name, CoreSubject cS [ ], OptSubject oS [ ]) {
This.name=name;
CSub=cS;
OSub=oS;
}
public void setEEntranceQual (Long perc) {
qualPerc=perc;
}
public void SetMaxStudents (int uSt) {
numof=uSt;
}
public boolean check Course Avail () {
if ((curSt+1) < numofSt) {
return true;
}
else
return false;
}
public boolean checkEntrance Qual (Long perc) {
if (qualPerc.LongValue () > perc)
return false;
else
return true;
}
public void set CurrSt () {
//
curr St++;
}
public int getCurrSt() {
//
return curr St;
}
Course.java
Package College.student;

-39.

JAVA

Public class {
Static int apNum;
Applicant aplcnt;
Public void rcvAppl (Applicant a) {
ApNum++;
Aplcnt=a;
}
public boolean appApl(Course c) {
if (c.check CourseAvail () )
if (c. checkEntrancequal (aplcnt.getResult () ) )
return true;
else
return false;
else
return false;
}
}
.java

package college.student;
. College.student
. College student
.
3.4.3 Java
,
Java .

JAVA

Long

util

io

applet

awt

net

Java. Long Security Manager, System, Thrend . Java-


.
Java.util Date . .
Java.io / .
Java. ,

-40.

JAVA

Java.awt : GUI ,
Button, Label .
Java. Net :
.
7
?
4.1 - .
Java .
Java- . Microsoft IE, Netscape Navigator, Sun- Hot
Java
Java-enabled . Java
. Applicatoin
-
. Word wid, web
.
4.1.1 -
1. (- )
, , ,
.
-
y,
, , .
2.
.
3.
.
4. . , -
- . -
-
.
4.1.2 -
- , 1- .
HTML . main () .
- main () . -
. - 5
. init(), start(), stop (), destroy (), paint (),

-41.

JAVA

init

start
Paint ( )
Stop ( )

Destray ( )

Initialization
init () . . , ,

. -
init () .
Public void init () {
// .
}


- . Initialization
initialization ,
- .
. -
start () .
Public void start () {
// .
}

-42.

JAVA

Stop () -
. stop ()
.
Public void destroy()
<
// .
}

Destroy () -
. destroy () .
Public void destroy ()
{
// .
}

Paint () - . ,
, .- . Paint- .
Graphics , - awt
Graphics .
Public void paint (Graphics -) {
// .
}
4.1.3
- .
.
Import Java awt.Font
Import Java awt.Color
Import Java awt.Graphics
Public class Try extends java. . {
Font f=new Font (Garamond, Font.BOLD+Font. ITALIC, 30);
Public void paint (Graphics g) {
g. set Font (f);
g.set Color (Color.blue);
g. draw String (My firest , 10,40);
}
}
Try .java
Font.Bold Font.ITALIC Font g,blue Color
.
- HTML .
<html>
<title> Tosting </title>
</hend>
<body>
<p>

-43.

JAVA

<br>
< code = Try.class width=400 height =200 >
Java- .
</ >
</ body >
</ html >
- viewer
. Java 2-
viewer . viewer <html
file name >.
4.1.4 tag-
tag- . CODE tag java
, WIDTN - , HEIGHT .
< > tag- .
CODEBASE
CODE .
CODE - CODEBASE
. CODEBASE -
HTML .
Java Files folder-
Try.class
.
< code = Try.class codebase = / Java Files height =
300 width=300 >
< / >
ALIGN
.
ALIGN ALIGN = <value> ,
:
LEFT - .
RIGHT - - .
TEXTTOP
.
TOP - (, ,
.) .
ABSMIDDLE -
.
MIDDLE - .
BASELINE or BOTTOM -
.
ABSBOTTOM -
.
HSPASE VSPACE

-44.

JAVA

,
. .
:
< code = Trytinyj.class width=60 heigth=50 hspace=20 vspace=20 >
</ >
4.2

- tag- CODE
. .
. java ,
.
,
?
. ,
HTML
.
HTML PARAM tag . PARAM tag
< > </ > tag- . PARAM tag
2 . NAME ( ) VALUE ( ).
HTML TryParam.class Site 30
.
< code = TryParam.class width=400 height=200 >
<param name = site value =30 >
</ >
getParameter () .
String .
Site , 44
.
Import java.awt.Font;
Import java.awt.Color;
Import java.awt.Graphics;
Public class TryParam extends java.. {
Font f;
Int s;
Public void init () {
String textsite;
Textsite = getParameter () (site)
If (textsite == null)
S=44;
Else
S= Integer.parse_Int (textsite);
}
public void paint (Graphics g) {
f=new Font (Garamond, Font.BOLD, S);
g.set Font (f);
g.set Color (Color.blue);
g.drow String (My first , 10, 40);

-45.

JAVA

}
}
.

8
4.3

Graphics

- paint . , , , ,
.

.

0, 0

Monitor
Y

4.3.1
A (x1, y2), B (x2, y2)
g.drawLine (x1, y1, x2, y2)
.
4.3.2 ,
g.drawRect (10,40,200,100) (10, 40)
100 , 200 . FileRect ()
.

drawRoundRect (), file RoundRect ()
.
4.3.3

3D ,

Draw 3dRect (), Sill 3dRect ()


g.draw3dRect (10,20,200,100, true) .
.
4.3.4 ,

-46.

JAVA

DrawPolygon (), fillPolygon ()


drowPolygon() 2
:
DrawPolygon (int x [ ], int y [ ], int n)
x, y x, y
,
drawPolygon (Polygon p)
:
int x [ ] = { 20, 20, 70, 120 };
Int y [ ] = { 20, 150, 200, 150 };
L=x.length;
Polygon p=new Poligon (x,y,l);
p.addPount (1208 20);
g.arowPolygon (p);

addPoint()- .
4.3.5 , ,
Draw Oval (), fillOval (). , .
g.draw (20, 20, 100, 100) (20,20) 100
.

4.3.6 ,
. Drow Arc (), file Arc ()
.
g.draw Arc (20,20,100,20,0, -180) (20,20) 100 , 20
0 180 .

-47.

JAVA

4.3.7
Import
Import
Import
Import

java.
java.
java.
java.

awt.Font;
awt.Color
awt.Graphics;
awt.Polygon;

Public class Drawsmiley extends java.. {


Public void paint (Graphics g) {
Font f = new Font (Times Roman, Font.PLAIN, 30);
SetBackground (Color.pink); // pink .
//
g.setFont (f);
g.setColor (Color.red);
g.draw string (smiley, 80,50);
//
g. setColor (Color.block);
g.drawRoundRect (78,24,90,35,20,20);
//
g. setColor (Color.yellow);
g.filloval (100,100,200,200);
//
g. setColor (Color.black);
g.filloval (140,140,30,30);
g.filloval (225, 140,30,30);
//
g.drawline (200,180,200,220);
//
g.drawArc (170.230,60,20,180,180);
//
f=new Font (TimesRoman, Font. PLAIN, 24);

-48.

JAVA

g.setFont (f );
g.setColor (Color.red);
g.drawstring (Hi !! Im smiley , 335, 60);
//
g.setColor (Color.yellow);
g.draw Oval (328, 24,170,50);
//
int x [ ] = {327,260,340};
int y [ ] = {50,120,70};
int l = x.length;
Polygon p = new Polygon (x,y,l);
g.fill Polygon (p);
}
}
4.4

Font Color .
Font , , .
Font BOLD, ITALIC, PLAIN

: Font.BOLD+ Font.ITALIC
Font :
get Name ()
get Site () -
get Style ()
is Bold () Bold
is Italic () Italic
is Plain () Plain
4.4.1
, baseline,
ascent, descent, loading

Baseline
Ascent baseline
ascent- . : I a-
ascent-.

-49.

JAVA

Descent baseline
.
G. j . descent- (.
).
Hading Descent ascent
.
draw Chars () drawBytes()
.
Draw Chars (char arr [ ], int offset, int totalnumchars, int x, int y);
Draw Bytes() drawChars () .
byte : draw Bytes (byte arr [ ], int offset, int totalnumbytes, int x,
int y);
4.4.2 FontMetris
Awt
FontMetris .
, . FontMetris ,
new . , Font
getFontMetris () FontMetris .
Font f= new Font (TimesRoman, Font BOLD, 36);
FontMetris fm= get FontMetris (f);
String s= new String (Testing FontMetris);
Int h= fm.getHeight ();
Int sw= fm.StringWidht (S);
s StringWidth() .
getHeigth FontMetrics- .
FontMetrics- :
Get Ascent()
Get Leading ()
Get Height ()
Ascent +descent+leading space .
Get Max Ascent()
ascen-
Get Max Descent ()

.
Advance . :
char Width()
.
GetMax Advance ()
advance.
String Width()

Char Width () 3 : , offset ,

Bytes Width () 3 : , offset ,

-50.

JAVA

Get Widths() 236


4.4.3
Color :
RGB 0.0-c 1.0
Color c = new Color (0.01 F, 0F, 1F);
0- 255 RGB
Color c = new Color (64,64,64);
16-23 8-15
, 0-7 .
Color c = new Color (434);
// 1 , 1, 178
.
, , .
Color
Color .
Color , RGB .

Black
Blue

Dark Gray
Gray
Green
Eight Gray
Magenta
Orange
Pink
Red
White
Yellow


Magenta

0
0
0
64
128
0
192
255
255
255
255
255
255

0
0
255
64
128
255
192
0
200
175
0
255
255

0
255
255
64
128
0
182
255
0
175
0
255
0

4.5

Web . Java
Image . Web
.
.
Web Web Java- URL (Uniform Resource Locator)- .
URL . :
http://www.sun.com/images balloon.gif
URL :
URL u1= new URL (http://www.sun.com/images/balloon.gif);

-51.

JAVA

URL Image
. getImage () 2 :
GetImage (URL)
URL Web
.
Get Image (URL, String)
URL ,
http://www.sun.com/images balloon.gif-
.
URL u1= new URL (http:// new.sun.com/images/balloon.gif );
Image img=getImage (u1);

URL u1=new URL (http:/www.sun.com/images);


Image img= getImage (u1,balloon.gif);
- Web
.
- web .
2 .
GetDocument Base()
-

URL

.
:

http://www.sun.com/s try .html


http://www.sun.com/s/try.html URL
.
Get Code Base ()
- URL- : try.class apple-
http://www.sun.com/s URL- .
. Graphics drawImage()
. .
.
4.5.1
drawImage () 4 - Image ,
, , Image Ob server . Image Ob server


. ImageObserver
4 this .
This
.
, .

.
Import java.awt.Image;
Import java.awt. Graphics;
Import java.awt. Color;

-52.

JAVA

Public class Draw Image exttends java.. {


Image img;
Public void init() {
Ing=getImage (get Code Base (), Christinas Troes.gif);
}
public void paint (Graphics g) {
int w= ing.get Width (this);
int h= ing.getHeight (this);
g.draw Image (img, 200,10 w/2,h/2, Color.blue, this);
4.6

, -
. - .
.AU - , Java 3 Plotform-
.WAV, .AU, .AIFF, .MIDI, .RMF . Java
AudioClip . audio
, , .
Get AudioClip() - new
AudioClip() - .
play (), loop(), stop() ,
, .
, .
Import java.awt.Graphics;
Import java..Audio clip;
Public class TrySound extends java.. {
Audio Clip c1;
Public void init (){
C1=get AudioClip(getCodeBase(), that.hurts.au);
}
public void start () {
c1.play ();
}
}
4.7

Graphics copyArea()
.
6 :
(x,y)
,
,
(10,10)
copyArea() .
Import java.awt.Image;
Import java.awt.Graphics;

-53.

JAVA

Import java.awt.Color;
Public class CopyImage extends java.. {
Image iny;
Public void init () {
Ing = getImage (getCodeBase(), Christmas Trees.gif);
}
public void paint (Graphics g) {
g.drawImage (ing,10,10, Color.blue,this);
int w=iny.get Width (this);
int h= ing.get Height (this);
g.copyArea (10,10, w, h, w+20,10);
}
Clear Rect ()
. 4 .
(x,y)

g.clearRect (10,10,100,100);
9
4.8

Java 2D-

Java 2D Graphic ,
. Graphic
awt
, . awt . Java 2D
.
awt- Java 2D :
, : ,
, .
Anti-cliasing- .
Java 2D java.awt ,

.
4.8.1 2D
paint () Graphics
, Java 2D Graphics 2D .
Graphics 2D java.awt paint() Graphics
Graphics2D :
public void paint (Graphics g) {
Graphics2D g2D= (Graphics 2D) g;
//
}
4.8.2 Java 2D

-54.

JAVA

awt pivel .
.

. .

.

.
. Java2D
.

. Java2D
/ default
.

.
. Default inch-
72 . (72,72)
1 , 1 .
,
Java2D .
4.8.3
Graphics , .
drawString () . drawstring () Graphics2D
.
G2D.drawString (Hello Word , 10, 40);
setColor .
4.8.4
Awt API- (, .)
. Java2D
draw() . File ()
. ,
draw () file
.
jav.awt.geon.* - .
4.8.5
Line2D java.awt.geom
. Flout Double
. (10,10)-c (300,310)
:
Line2D l=new Line2D.Float (10,10,300,310);
g2D.draw (l);

-55.

JAVA

Point2D 2
:
Point2D p1=new Point2D. Float (10,10);
Point2D p2=new Point2D. Float (300, 310);
Line2D l=new line2D.Float (p1, p2);
g2D.draw (l);
4.8.6
Rectangle2D .
, ,
.
Rectang 2D r=new Rectangle2D.Float (20,20,150,100);
g2D.draw (l);
4.8.7

Ellipse2D , , .
4.8.8
- .
2 .
(40,40)-c (40,250)- (20,20) :
QuadCurve20 q=newQuadCurve2D.Float (40,40,20,20,40,250);
g2D . draw (q);
. (40,40)-c
(40,250)- (20,20)
.
(40,40)- (40,250)- (20,60) (150150)
.
Cubic Curve2D q=new Cubic Curve2D.Float (40,40,20,60,150,150,40,250);
g2D.draw (q);

4.8.9
, , .
. GenoralPath
. Generalpath
. draw . 8
.

-56.

JAVA

Import java.awt.*;
Import java.awt.geon.*;
Public class TryHex extends java.. {
Public void paint (Graphics g) {
Graphics2D g2D = (Graphics2D) g;
General Path =new General Path();
p.move To (60,20);
p.line To (140,20);
p.line To (180,60);
p.line To (140,100);
p.line To (60,100);
p.line To (20,60);
p.line To (60,20);
g.2D.draw (p);
}
}
4.8.10 Stroke ( )
Stroke . Java awt API
1 stroke . Java 2D
stroke
. stroke- Basic Stroke .
. :
Basic Stroke ()
Basic Stroke (float width,int cap, int join);
Basic Stroke (float width, int cap, int join float miterlimit)
Basic Stroke (float width, int cap, int join float miterlimit, fload [ ] dash, float
dash_phase )
Width strok-
Cap- strok- : CAP_BUTT, CAP_ROUND, CAP_
SQUARE.
CAP_BUTT stroke-
CAP_ROUND stroke- CAP_SQUARE
.


join Stroke . ( )
JOIN_BEVEL stroke- .

-57.

JAVA

JOIN_ROUND Stroke-

Miterlimit . Dash
dash_phase Stroke- . Dash
- , . Dash_phase
.
2 8- 5 dash_phase-,
10 dash_phase .
Import java.awt.*;
Import java.awt.geon.*;
Public class Dash extends java.. {

-58.

JAVA

Public void paint (Graphics g) {


Float [ ] av = new float [4];
av= [0]=15; av[1]=10; av[2]=5; av[3]=10;
g2D.setStroke (new Basic Stroke (10f, BasicStroke.
CAP_ROUND, Basic Stroke. JOIN_ROUND, 18 av, 5));
GeneralPath p=new General Path ();
SetBackground (Color.yellow);
G2D.setColor (Color.red);
p.moveTo (100,10);
p. Curve To (50,60,150,160,100,210);
p.move To(100,10);
p.curve To (150,60,50,160,100,210);
g2D.draw (p);
g2D.setstroke (new Basic Stroke (10f, Basicstroke.CAP_ROUND,
Basic stroke. JOIN_ROUND, 1, av, 10));
GeneralPath p1=new GeneralPuth();
Set.Backround (Color.yellow);
G2D.setColor (Color.red);
P1. Move To (200,10);
P1. Curve To (150,60,250,160,200,210);
P1. Move To (200,10);
P1. Curve To (250,60,150,160,200,210);
G2D.draw (p1);
}
}
4.8.11
.
, , texture
. setPaint()
, Paint .
Gradient Paint 2
. .
2 (0,0), (50,50) 50 .
(0,0) .
Cyclic Acyclic . Acyclic
. cyclic
.
.
Gradient Paint (float x1, float y1, Color c1, Float x2, float y2, Color c2, boolean
cyclic);
cyclic false (default
) .

-59.

JAVA

Gradient setPaint()
.
Import java.awt.*;
Import java.awt.gean.*;
Public class File extends java.. {
Public void paint (Graphics g) {
Graphics2D g2D= (Graphics2D) g;
GradienPaint grad =new Gradient Paint (0,0, Color.blue,
50,50, Color.krange,
);
g2D.setPaint (grad);
Rectangle2D r=new Rectangle2D.Float (10,10,100,100);
G2D.File(r);
TexturePaint (BufferedImage Fillpattern, Rectangle2D r);
FufferedImage
.
Image . Rectangle 2D
.
file pattern-
.
TINY.GIF
.
Import java.awt.*;
Import java.awt.geon.*;
Import java.awt.image.BufferedImage;
Public class FileImage extends java.. {
Public void paint (Graphics g) {
Graphics2D g2D= (Graphics2D) g;
G2D. setstroke (new BasicStroke (601,BasicStroke.CAP_ROUND,
Basicstroke.JOIN_ROUND));
GeneralPath p=new General Path ();
SetBackground (Color.yellow);
G2D.setColor (Color.red);
p.moveTo (50,50);
p. line To (300,300);
p.move To(300,50);
p.line To (50,300);
Imag ing=getImage (getCodeBase(), TINY.GIF);
BufferedImage bing=new BufferedImage (ing.getwidth (this),
ing.getHeight (this), BufferedImage.TYPE_INT_RGB);
Graphics2D temp=bing.create Graphics ();
Temp.drawImage (img, 0,0, this);
Revtange2D r=new Rectange2D.Float (0,0 ing.get width (this),
ing.getHeigth (this));
TexturePaint tp=new TexturePaint (bimg, r);
G2D.setPaint (tp);
G2D.draw (p);

-60.

JAVA

}
}

10
5.1 Exception Handling
Exception .
()
.
.
.

. Java runtime exception handling
. Excption handling
, . ,

.
exceptio- Throwable bnilt- sub .
Throwable 2 sub : Exception Error.
Exception
. Runtime Exception Exception- sub ,
exception- 0- . .
exception Error sub . :
runtime .
exception exception
. exception .

Throwable

Error

Exception

Lincage
Error

Class Not
Found
Runtime
Exception

Array Index
Out Of Bounds

Stack Over
Flow

-61.

JAVA

5.2

Exception- ?

Java Claus- exception- : try, catch, throw, throws, finally.


exception- exception-
exception
.
exception-
. exception-
, runtime
.
5.2.1 Try, throw, catch
Exception- try catch .
Exception-handling- :
Try
{
//
//
{
catch (<Exception Type Class> object1)
{
// exception-
}
Try.. catch exceptioyn- , exception-
, .
catch , .
catch . catch- exception-
.
, exception runtime
. exception-
. exception Number Format
Exception. ,
.
Class NumForm Excp
{

-62.

JAVA

public static void main (String arge[ ])


{
String str1=new String (text12);
Int mm1= Integer.parseInt(str1); //

System.out.printen (mm1);
}
}
:
Exception in thread main java.lang.NumberFormatException: taxt12
At java.long.Integer.parseInt (Compiled code)
At java.long.Integer.parseInt (Integer.java :458)
At mmfornexcp.main (numformexcp.java :6)
Str1 . Str1
NumberFormatException
. runtime
default exception handler- .
exception , ,
.
exception- :
Class NumFormExcp
{
public static void main (string args [ ])
{
try
{
string str1=new String (text12);
int num1=Integer.parseInt (str1);
system.out.println (num1);
}
catch (NumberFormatException e)
{
system.out.println (# # Wrong Number # # );
}
}
}
exception , ..
. exception- throw
class- . exception- ,
.
exception- , exception throw class- :
Try
{

-63.

JAVA

//
throw new Udef_Exception();
//
}
catch (Udef_Exception obj1)
{
system.out.println (User defined exception caught);
}
Udef_Exception exception- ,

. exception .
exception throw clause- . throw
clause- Udef_Exception- .
catch clause exception .
, throw clause-
exception- :
Class Throw Clause
{
public static void main (string args [ ])
{
try
{
throw new NullPointerException ();
}
catch (NullPointerException e)
{
System.out.println (Invalid reference use);
}
}
}
throw clause NullPointerException
exception- . NullPointerException exception
null .
, exception catch
.
throwable
. String, Date . throw-
.

11
5.2.2 Throws
try exception ,
catch . exception-

-64.

JAVA

.
exception- throws clause-
. Throws clause , .
exception-
. exception- .
exception-
throws clause , runtime
.
method_one ()
. exception , throws clause-
. catch clause . main
() , main () exception method_one ()-
, exception- throws clause
runtime .
Class <class name>
{
static void method_one() throws <exception_one>
{
throw new <exception one>
// method_one exsption-
.
}
public static void main (string args [ ])
{
try
{
method_one (); // main() exception- ,
// .
}
catch (<exception_one> object )
{
// exception-
}
}
}
. 2 : throwExcp()
main ()
Throw Excp() IllegalAccess Exception exception-
.
(IllegalAccessException
.) catch IllegalAccessException-
.
.
Class Throws_Clauses
{
static void throwExcp()

-65.

JAVA

{
try
{
throw new IllegalAccessException();
// exception
.
} catch (IllegalAccessException e ) // exception .
{
system.out.println(catch );
throw new IllegalAccessException(); // exception
.
}
}
public static void main (string args [ ])
{
throwExcp();
system.out.println (coes not reach here);
}
}
:
Throws_Clauses.java:12:Exception java.lang.IllegalAccessException
or it must throw new IllegalAccessException();

must caught,

. Throw Excp()
throws clause .
exception- , .
throwExcp() exception ,
, . main() exception- .
main() exception
. Throws clause
, exception-
exception-
.
Class Throws_Clauses
{
static void throwExcp() throws IllegalAccess Exception
{
throw new IllegalAccessException();
}
public static void main (string args [ ])
{
try
{
throwExcp();
}
catch (IllegalAccessException e )
{

-66.

JAVA

system.out.println(Exception caught);
}
}
}
:
Exception caught
5.2.3 Finally
Finally clause try , try- catch finally
, try- //.
Finally catch
.
:
Try
{
//
}
finally
{
//
}

try
{
//
}
catch (<exception> obj)
{
//
}
finally
{
//
}
Catch finally . Catch 0-
Arithmetic Exception . Catch
finally .
Class Finally_Block
{
Static void division ()
{

-67.

JAVA

try
{
int num=34, den=0;
int duot=num/den;
}
catch (ArithmeticException e)
{
system.ont.println(Divide by zero);
}
finally
{
system.ont.println(In the finally block);
}
}
public static void main (string args [ ])
{
division()
}
}
Exception handling-
.
. : , ,
. finally clause .
.
Class Write_To_Stream
{
public void open_Stream ()
{
//
}
public void writing_To_Stream ()
{
try
{
//
}
finally
{
//
}
}
public void close_Stream ()
{
//
}
public class IO
{
public static void main (string args[ ])

-68.

JAVA

{
// Write_To_Stream-
}
}
}
5.3

Catch clauses-

Try exception- .
try exception exception catch
. Exception
catch catch
. :
try
{
//
} catch (<exception_one> obj)
{
//
}
catch (<exception_two> obj)
{
//
}
catch (<exception_three> obj)
//
}
exception-
.
Exception exception .
exception- exception-
exception exception-
.
Class Gen_Exp
{
public static void main (String args [ ])
{
try
{
int num =34, den=0;
int quot = num/den;
} catch (Exception e)
{
system.ont.println(Error in the code);
}

-69.

JAVA

}
}
exception .
exception- catch .
5.4

try

Java exception built-


. java.long ,
. Built- exception
exception . exception
exception
, (validation) .
exception-
. exception .java ,
, exception ,
.
Class Validate_Range extendes Exception
{
String mesg;
Validate_Range ()
{
mesg=new String (Enter between 20 and 100);
}
public String to String ()
{
return (mesg);
}
}
public class My_Exception
{
public Static void main (String args [ ])
{
try
{
int x=10;
if (x<20 // x>100)
throw new Validate_Range();
catch (Validate_Range e)
{
system.ont.println (** +e);
}
}
}

5.5

Exception- ?

-70.

JAVA

Exception
. exception
. ,
. exception- :
exception handling-
. Exception- .
exception handling
.
exception handling
.
,
.
exception-
. Exception-

catch . , exception-
.
12
Java Mulmithreading
6.1

Multithreading

Multithreading thread 2
, thread - . Multithreading
,
. : ,
. Singlethreaded
, web
.

Program P

Thread
1

-71.

JAVA

multithreading event loop


. ,
.
polling- . polling

Thread
2

Thread
3


.
.
++ multithreading ,
. Microsoft windows, Apple
Maantegh event loop
.
6.1.1 Multithreading
Multithreading (tasks)
,
. Multithreading Single-processor
. thread -
.

. thread-

-72.

JAVA

.
thread- CPU time- . thread-
, . trhead
CPU time .
thread CPU- . thread thread- .

6.1.2. Multitasking Multithreading


/- multitsking , multitasking- multithreading . Multitasking multithreading .
Maltitasking- task heavy-weight ( ) . Heavy-weight
light-weight heavy-weight
. light-weight
.
multitasking , . J Builder Word
multitasking. Word , scroll
. multithreading.
6.1.3

Java- Thread (model)

Java multithread . ,
multithreading- . thread
. , animation
.
. animation
thread
. new , ready, running, inactive, finished. Thread new
. ready . runing .
Thread .
. thrad
inactive .

-73.

JAVA

New

Ready

Finishid

Running

Inactive

Thread

Multithreading thread CPU .

thread . Thread-
thread- . Thread- 1-
10 . 10 , 1 .
thread .
thread thread .
Thread , I/ 0
, pre-empted
. thread- ,

-74.

JAVA

thread .
thread
thread- pre-empted .
pre-emptive multi-tasking . thread
., .
Synchronization
Multithrasking asynchronous .
thread-
. thread-
. : 2 thread

.

Multithreading thread inter-process


. Thread thread- . Thread-
wait notify .
6.2

Thread

Thread Java 2 .
Thread ,Runmable .
Thread () run()
. Runnable
run() .
, main thread- .
6.2.1 Main Thread
Main Java thread-
. main thread ,
thread . thread thread-
. thread thread . Main thread
.
Main thread , thread
. Thread Thread currentThread ()
main thread- .
: main thread :
Class MainThread {
Public static void main (String args [ ]){
Thread t = Thread.currentThread();
System.ont.println(Current Thread : + t);
System.ont.println(Name : ++.getName());
System.ont.println( );
t.setName (New Thread);

-75.

JAVA

System.ont.println(After changing name);


System.ont.println(Current Thread : + t);
System.ont.println(Name : + t.get Name ());
System.ont.println( );
System.ont.println(This thread
first 10 numbers );
Try {
For (int I =1; I < = 10; I ++) {
System.ont.print (i);
Thread.sleep (1000);
}
} catch (Interrupted exception e) { }
}
}
6.2.2 Thread thread
Thread Thread sub .
run() , .
.
.
Class My Thread extends Thread
{
My Thread ( ) {
..
..
}
public void run () {
..
..
}
..
}

Class Example
{
public sta tic void main () {
My Thread t=new My Thread ();
.
t.Star t ();

h thread .
Thread thread .
Class PrintString 1 {
Public Static void main (String args [ ] ) {
String Thread1 t = new StringThread 1 (Java, 50);
t.Start ();
}
}
classes StringThread1 extends Thread {
private String str;
private int num;
StringThread1 (String s, int n ) {
Str = new String (s);

-76.

JAVA

Num = n ;
}
public void run () {
for (int I = 1; I c = num; I++)
system.ont.print(str+ );
}
}
6.2.3 Runnable thread
, thread Runnable
. thread ?
. thread sub
thread . Java
. Runnable

.
Runnable .
Class PrintString 2 {
Public Static void main (String args [ ] ) {
String Thread 2 t = new StringThread (Java, 50);
New Thread (+).Start ();
}
}
classes StringThread 2 implements Runnable {
private String str;
private int num;
StringThread 2 (String s, int num ) {
Str = new String (s);
Num = n ;
}
public void run () {
for (int I = 1; I c = num; I++)
system.ont.print(str+ );
}
}
Thread
thread t.Start () . String Thread1 Thread
sub , thread- .
Runnable thread Thread PrintString2
. String thread 2
. String Thread 2 run()
.
Runnable , StringThread 3
Thread .
Class PrintString 3 {
Public Static void main (String args [ ] ) {

-77.

JAVA

New string Thread 3 (Java, 50);


}
}
class StringThread 3 implement Runnable {
private String str;
private int num;
StringThread3 (String s, int n ) {
Str = new String (s);
Num = n
Thread t =new Thread (this);
T. start();
}
public void run () {
for (int I = 1; I c = num; I++)
system.ont.print(str+ );
}
}

6.2.4 thread ,
3 thread - Java- 100 , Cafe- 100
, 150- .
Class MultiThread {
Public Static void main (String args [ ] ) {
new Thread(new StringThread (Java,100)).Start ();
new Thread(new StringThread (Cafe,100)).Start ();
new Thread(new PrimeThread (150)).Start ();
}
}
classPrimeThread inylementsRunnable {
private int Castval;
primeThread ( int n ) {
Castval= n;
}
public void run () {
int I, j;
booloon flag;
for (I=2; I<= n; I++) {
flag = false ;
for ( j2; j<=i/2; j++)
if (i%j==0)
flag=true;
if (flag==false)
system.ont.print (it+ );
}
}

-78.

JAVA

}
class String Thread implements Runnable {
private string str;
private int num;
stringThread (String s, int n) {
str = new String (s);
num = n;
}
public void run () {
for (int i=1; i<=num; i++)
System.ont.print (str+ );
}
}
}
6.3

Thread-

Thread MIN_PRIORITY. NORM_PRIORITY, MAX_PRIORITY


1,5,10 . Thread
default- NORM_PRIORITY- .
Java thread thread-
. 2 thread- CPU
round-robin . StringThread
. 4 thread 5,6,7,8
.
Import String Thread;
Class PriorityThread {
Public static void main (String args [ ] ) {
Thread t 1=new Thread (new String Thread (Java, 25));
Thread t 2=new Thread (new String Thread (Cafe, 25));
Thread t 3=new Thread (new String Thread (Symantic, 25));
Thread t 4=new Thread (new String Thread (Platform2, 25));
t1.setPriority (Thread.NORM_PRIORITY);
t1.setPriority (Thread.NORM_PRIORITY +1);
t1.setPriority (Thread.NORM_PRIORITY+2);
t1.setPriority (Thread.NORM_PRIORITY+3);
t1.start ();
t 2.start ();
t3.start ();
t4.start ();
}
}
Thread- 25 . Pleatform 2
thread , .

-79.

JAVA

13
6.4 synchronization
. 2
thred- , .
monitor inter-process . Monitor
1 thread-
. 1 thread- thread- thread . Monitor
thread-
. Java- monitor .
.

monitor- . thread
thread-
.
. 2 Accout
.(account number balance) Negative Amount
Exception, Insufficient Fund Exception 2 . 2
0- ,

. Account

.
Get balance- .
Set balance - .
Deposit - , .
0- Negative Amount
Exception .
With draw- , . 2
Exception- . 0- Negative Amount
Exception , Insufficient
Fund Exception.
Class account1
Int account no;
Float balance;
Account (int ac, float bal){
Account no=ac;
Balance=bal;
}
float get balance () {
return balance;
}
void set balance( float balance){
balance= bal;
}
void deposit (float amount) throw negative Amount Exception{
if (amount < 0)
throw now Negative Amount Exception() ;
balance = balance +amount ;
}

-80.

JAVA

void with draw (float amount) throw Negative Amount Exception, Insufficient
Fund Exception {
if (amount < 0)
throw now Negative Amount Exception();
if (balance < amount )
throw now Insufficient Fund Exception();
balance = balance amount;
}
class negative amount exception extend exception{
negative amount exception () ;
super (negative amount);
}
}
class insufficient fund exception extend exception{
insufficient fund exception();
super (Insufficient Fund);
}
}
import account;
class nosync {
public static void main ( string args [ ] );
account a1 = new account (1,1000)
account a2 = new account (1,0 )
thread +1 [ ] =new thread {100 }
thread +2 [ ] =new thread {100 }
threadgroup g1 = new threadgroup(group1)
threadgroup g2 = new threadgroup(group2);
for ( int I= 0; I<100; I ++){
t1 [ I]= new thread (g1, new transforthread ( a2,a1,1), t1)
t1 [ I].star+ ( );
}
for ( int I= 0; I<100; I ++){
t2 [ I]= new thread (g2, new transforthread ( a2,a1,1), t2)
t2 [ I].star+ ( );
}
while ( true) {
if ( g1. activecount ( )==0)&& ( g2. activecount ( )==0)
break;
system.out.println (balance in account1+ a1.getbalance( ) );
system.out.println (balance in account2+ a2.getbalance( ) );
}
}
}
class transferthread extends thread1
account from account, to account;
float amount;
transferthread (account a1, account a2, float amt){
fromaccount = a1;
toaccount = a2;

-81.

JAVA

amount = amt;
}
public void um ( ) {
transfer ( fromaccount, toaccount, amount);
}
void transfer ( account from, account to, float amt) {
float formprior = from.get balance ( );
float toprier = to. Get balance ( );
try {
sleep (1000)
} catch ( interrupted exception e ) { }
try {
to deposit (amt);
from.withdraw (amt)
} catch (negative amount exeption e ) {
from.set balance (fromprior );
to,setbalance (toprior);
}
catch (insufficientfund exeption e){
from.set balance (from prior);
to.setbalance( toprior);
}
}
}
. Threadgroup
. Threadgroup thread- . Thread -
thrad-
. thread 2
. +1;+2 g1 g2 2 .
group1, group2 . 1-2 re1
100 thread- g1 .
g2 . .
thread- . threadgroup
thread- activecount .
Thread transferthread .
thread run .
Thread-
. 2 thread-
synchronized .
transfer synchronized .
transfer .
Synchronized void transfer (account from accoun to float amt)
synchronized thread
monitor- . thread- thread-
.
6.5 inter thread communication
synchronized thread-
.
.
. notify .

-82.

JAVA

wait- thread- .
thread- wait-
notify all .
synchronized .
.produser consumer-
. 2 . put get. Put
, get . Produser
, thread .
Consumer
thread- . .
Class queen 1
Int n;
Synchronized int get () {
System out printin ( got: +n);
Return n;
}
synchronized void put ( int n) {
this.n=n;
system.out.println (put:+n);
}
}
class produser implements runnable{
queen q;
produser (queen q){
this.q=q;
new thread (this, produser).start+( );
}
public void run ( ) {
int i=0;
while ( true) {
q.put (I++);
}
}
}
class consumer implements runnable {
queen q;
produser (queen q){
this.q=q;
new thread (this, produser).start+( );
}
public void run ( ) {
while( true) {
q.get ( )
}
}
}
class interthread {
public static void main ( string args) {
queen q= new queen( );

-83.

JAVA

new produver (q);


new consumer (q);
}
}
:
put :27
get :27
put :28
get :28
get :28
put :29
get :29
put( ) get( ) synchronized . 28
2 . synchronized
. consumer 2 producer consumer
.
. producer 28 , consumer 2
.

.
.
Class queen {
Int n;
Boolean flay= false;
Synchronized int get ( ) {
If ( flay==false )
Try {
Wait ( );
} catch ( interrupted exception e ) { }
system.ant.printen (got:+n );
flag= false;
modify ( );
return n ;
}
synchronized void put (int n) {
if (flay== true)
try{
wait ( );
} catch (iterruped exception e) { }
this.n = n;
flag=true;
system.out.println ( put:+n);
modify( );
}
}
6.6 Thread animation
animation , , frame-
. frame . Frame

. Frame .

-84.

JAVA

Animation
.

inport java.util.Gregorian calendar;


import java.text.dateformat;
import java.awt.x
public class clock extends java .{
int xcontre ycentre, clock radins;
dateformat df;
gregoriancalendar col;
public void init ( ){
df=dateformat.getdatetime instance ( );
clockradins=(int) ((getsize( ).width( )*0.5*0.7)
xcentre= (getsize( ).width( )/2;
ycentre= (getsize( ).width( )/2;
}
public void point (graphics g){
g.setcolor (color.black);
g.draworal (vcentre.clockradins, ycentre-clockradins, 2*clockradins);
g.drawstring (12, xcentre-5, ycentre-clockradins);
g.drawstring(3, xcentre+dookradins, ycentre+3);
g.drawstring(6, xcentr-2, ycentre+ dookradins+10);
g.drawstring(3, xcentr- dookradins -10, ycentre+3);
col= new Gregorian calendar;
int s= (int ) col.get (Gregorian calendar.second);
int strength= (int) (dookradins*0.9);
int secondx= (int) (math.cos((s/60.0)+2*math.pi-math.pi/2)*slenght+xcentre);
int secondy= (int) (math.sin || s/60)*2*math.pi-math.pi/2)*slenght+ycentre);
g.setcolor (color.green);
g.draw.line (xcentre. Ycentre, secondx, secondy);
int m=(int)col.get (Gregorian calendar~minute);
int m length= (int) (calendar radius*0.8);
int minutex=(int)(math.cos((m/60.0)*2*math.pi-math.pi/2)*mlenght+xcentre);
int minutey= (int) (math.sin((m/60.0)*2*math.pi-math.pi/2)*mlenght+ycentre);
g.setcolor( color.blue);
g.drawlink(xcentre, ycentre, minutex, minutey);
int h= (int) col.get (Gregorian calendar.hour_of_day);
int hlenght=(int)( dookradius*0.7);
konble hourangle=(h/12.0)*2*math.pi+(m/60.0)*(2*math.pi/60.0)-math.pi/2;
int hourx=(int) (math.cos (hourangle)*hlenght+xcentre);
int houry=(int) (math.sin (hourangle)*hlenght+ycentre);
g.setcolor (color.red);
g.drawline(xcentre, ycentre, hourx, houry);
string today= ds.format(col.gettime() );
font metrics sin =g.setfontmetrics();
g.drawstring(today,(getsize().widthsin.stringwidth
(today))/2,
ycentre+clockradius+30);
}
}

-85.

JAVA

, . Animation thread . Thread- ,


gnimation . Thread-
.
1. Implements runnable class-
2. Thread
3.Thread - start ,

4.Thread- - stop
5.hread- run , repaint
.
,
animation .
Inport java.out.x;
Public void start( ) {
If (t==null) {
T=new thread (this);
t.start( ) ;
}
}
public void run( ) {
htread this thread=thread.currentthread( );
while (t==thisthread) {
repaint ( );
try{
thread.sleep (1000);
}catch (interrupte1exception e) { }
}
}
public void stop ( ) {
if (T!=null)
t=null;
}
}
- . Thread
. - start thread- , . Stopt
Thread null thread- .thread-
start run .run point -
. while (+==thisthread) .
Internet intranet- gpplet-
inport java.awt.image;
import java..*;
public class Myanimator extends implements runnable {
MediaTracker mediatracker=null;
Image imagae[ ]=new image [3];
Int index;
Thread ani=null;
Public void init( ) {
Mediatracker=new mediatracker (this);

-86.

JAVA

For (int I=0; I++) {


Image [I]=get image( getdocument base ( ),fr+I+jpg);
Mediatracker.addimage (image[I],0);
}
}
public void start( ) {
if (ani==null {
ani=new thread (this);
ani.start ( );
}
}
public void stop ( ) {
if (ani!=null) {
ani.stop ( ) ;
ani.null :
}
}
public void run ( ) {
for (;;) {
if ( index<3)
index++;
else
index=0;
repaint ( );
try {
ani.sleep (1000);
} catch (exception e) { {
}
}
public void paint (graphics g) {
if ( mediatravker.check ID (0,true))
g.drawimage (image index, 0,0,this);
}
public void update( graphics g) {
paint (g);
}
{
mediatracker . Mediatracker java.awt
images media
. Mediatracker imageobserver . addimage ,
. ID .
.
ID- . check ID(0,true) 0
, load flag
. Animaation-
fro.jpg frd.jpg fr2.jpg. - html
file
<
code= myanimator.class width=500, hight=500>

-87.

JAVA

</>
Intranet server myanimator.class fro.jpg frd.jpg
fr2.jpg html : NT server
innetpub\viewroot .
/html . :
http://163.122.882170/animation.html
163.122.88.170 .
internet- webserver-
. ftpserver name .
C:\mydir>ftp 163.122.88.170
Connected to 163.122.88.170
User:
Password:
Ftp>bin
ftp>put byanimator.class
ftp>put animation.html
ftp>put fr0.jpg
ftp>put fr1.jpg
ftp>put fr2.jpg
ftp>byl
ftp
. fit . put file name
. Layout bye enter
.
Internet
http://siteaddress/html.filename .

Animation . .
.
.
color
.
Import java.awt,a;
Public class flash extends java...implements runnable {
Font f;
Color colore [ ]=new color [150];
Thread t=null;
Public void init ( ) {
F= new font (timeroman, font.bold,28);
}
public void start ( ) {
if (t==null){
t= new thread (this);
t.start;
}
}
public void stop( ) {
if (t!=null)
t=null;
}
public void paint (graphics g) {

-88.

JAVA

g.setfont (f);
g.drawstring (welcome to java2 platform:,10,40);
}
public void run ( ) {
float c=0.0f;
for (int I=0; I<colors length; I++){
if (I<50)
colors [I]=color.get HSBcolor (c,1.0f,1.0f);
if (I>=50 xx I<100)
colors [I]=color.get HSBcolor (0.0f,c,1.0f,);
if (I>=50 xx I<100)
colors [I]=color.get HSBcolor (1.0f,0.0f,c);
if (;%50==0)
c=0.0f
else
c=c+0.2f;
}
int I=0;
thread thisthread=thread.currentthread ( );
while ( t==thisthread) {
setforeground (colors [ I]);
repaint ( );
I++;
If (I==colors.length)
I=0;
Try{
+.sleep (10);
}catch (interrupted exception e ) { }
}
}
}
}
color getHSBcolor .
6.7 Thread animation-
animation thread animation thread
import java.awt.*
import java..audioclip;
publc class imageanim extends java...implements runnable;
image pics [ ] =new image [10]
image currimage
audioclip c1;
thread timage;
public void init ( );
string picsource [ ] ={t1.gif, t2.gif, t3.gif, t4.gif, t5.gif, t6.gif, t7.gif,
t8.gif, t9.gif, t10.gif,
for int I=0; I<10;I++);
Add() , add()
, . :
Public BorderLayout ();

-89.

JAVA

Public BorderLayout (iint horizontal gap, int vertica gap)


:
Import java.awt.*;
Import java..*;
Public class borderlayout extends
{
BorderLayout b=1 new BorderLayout ();
Button est, wst, nrth, sth;
Text Area cen;
Public void init ()
{
est =new Button (East);
wst =new Button (Wst);
nrth =new Button (North);
stn =new Button (South);
cen =new Text Area ();
set Layout (L1);
add (East, est);
add (West, wst);
add (North, nrth);
add (South, sth);
add (Center, cen);
}
}

7.3.3

Card Layout

-90.

Vous aimerez peut-être aussi