0% found this document useful (0 votes)
4 views

Java Assignment2

Uploaded by

darkdevilmukilan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Assignment2

Uploaded by

darkdevilmukilan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

A SSiJnnen-2

Involvedin eating obsectS


StepS

Command lne neut

ConsoS
vSib

A Muthlevel nhentane.

Creake
5 ho Packaees re

ep tion handling

ge Shve
88 cho vattex gtream
i r e a d d a l a

) total

Creating objects
from the
defined class.
s. Usinga
created
Objects are objects. All ated object
created o
number of
create any
class we can variables.
space
Memory space
Memory forsthe
for
instance
only durina ohi.
can u s e
the
allocated
variables will be
instance

creation.

Steps to create objects


object creation are
The steps to be followed for

i) Declare the object


The general form for object declaration is

classname objl, obj2 . . .


. objn;
Where
classname already defined class name
obj1... objn- name of the object. User defined
name
3.06

When this statement is executed,


memory space will
b ereated
ecreated for each object to hold the starting address of the
instance variables.he tigure given below shows this
obj 1 obj 2 obj n

O--O
Create memory space
(i)
After object declaration, we must allocate memory
sOace for the instance variables for each object. This is done
with the help of new operator. The general form is

objl new classname ( )


new classname ( );
obj2

objn= newclassname ()

Where
declared objects
obj1.. .objn- already
defined class
classname
-
already run
during
allocate memory
to
new key word
time memory
executed,
the
are stating
these
statements

created
and the
When
variables
will be space
memory
instance
space for the allocated
shows
this
the already
address is stored in
below

The figure given


laration.

ng object decla
3.07
obj1
[ var1
var2

varn
instance
objn variables
var1
var2

varn

Example
i) class examplel a

int x;
int y

X ax

64 bit
y a.y 2

cxamplel a;
anew examplel ()
Command line input

Command line arguments are parameters that are


aassed to the program from the command line. These are
passed

08sed at
passed at thetime of running the program. The general form
is
C> java classname arguments to be passed

where
- key word
java
class nanme name of the main class
arguments to be passed - list of arguments separated by

blank space.
Execution procedure
The structure of main method is

public static void main (String args [)


where

public access specifier


words
static, void, main
-

key
class
String
- a r r a y name
args
string objects ans
of
and is em
String args [] is an array
command line is
ls
Any argument passed
We
through
can access the array elements and
stored
use thein t
and yso"
array.
the program.

Example
(i) C» java Sample God Loves you

This command line has three arguments and are


storeda
args [0] -->God

args [1]->Loves
args [2] - - you

The length of the array can be found using args.lengh


(i) Program to add 5 numbers using command line.
class Sum

Public static void


main(String arg[])

String s;
int sum;

intm arg.length;
for(i-0; im;it+)
3.34

sum + Integer.parselnt(arglil)
System.out.println("Sum = " +sum);

Running
sum 5 7 3 2 1
C:java
The output is
Sum= 18
narameters
h e Supet er( )must
Super) muSt match
matcn the
arguments in the constructor defined in the superciass.
Multilevel inheritance

A class derived from other derived class is called


multilevel inheritance. The figure given below shows the
multilevel inheritance.
3.43

uperclass
employee
empno

e m p n a m e

t e a c h e

deptname

totalwork

multilevel inheritanca
load

NSSofficer

NSSunitno.

t o t a l s t r e n g t h

alled
called teacher is derive
deriy
subclass
a
example inherits all te
In our
This sub class
from a super
class
employee.

c l a s s employee
(empno a
properties
of the super (deptname, total
won
propertiesS
its o w n NSS
empname) plus another sub class called
class
From this sub properties
and class). contains all the
This class N
officer is derived. plus
and teacher)
is properties of employee
teacher (that
unit no and total strength)
own properties (NSS

Deriving a sub class

The general form is


lae name extende name 1

class name? extends name2

class namen extends namen-1

Where
Ciass, extends keyword
name2, name3 namen name of the sub classes

name1 name of the super class


3.62
Visibility control
The variables
and methods
isible
isible to
to the class itself. If defined inside class are
a
we want to make these visibl
access)
(access) to
subclasses or other visi
Kages access modifiers
packages a c classes or
packages or
or other
are used. The types
otn
moditiers are, access
es of access

() public

(i) protecteed

(i) friendly (default)


(iv) private

(v) private protected

public access
The general form is,

public datatype variablename;


(or)
public returntype methodname)

where

public keyword
public can be accessed in
vanable or method defined as
the,
same class

(i) same
package
class in the
sub package
(i) same

classes
in the
other
(ii)
in other pACkages
classes
other
(v) packages
other
in
(V)sub class
() protected access

form is
The general
protected datatype variablename;

(or)
protected returntype membername()

method defined as protected ca


The variable or
accessed in the,
same class
(i)
subclass in the same package
(ii)
in the same package
(ii) other classes

(iv) sub classes in other packages

(ii) friendly access (default)


o
variable
that
If modifiers are not given,
form is,
becomes friendly access. The general
3.64

datatype variablename;
(or)
retumtype methodname()

The variable or method defined as friendly can be


accessed in the,
i) same class

)subclasses in same package

G) other classes in the same package


protected access
(v) private
The general form is,

variablename;
private protected datatype
(or)
methodname)
private protected returntype

The variable or method defined


as private protected
can be accessed in the,

) same class

subclasses in the same package


i)
(i)
subclasses in other packages
(ii)
3.65

(v) private access

The general form is,

private datatype variablename;


(or)
private returntype methodname(
{

The variable or method defined


accessed only in the same class.
as private can be

Interfaces
(ii) student

Creating9 package
The following steps are followed to create our
packages.

(i) Declare the name of the package using the keyword


package. The general form is

package packagename;
Where

package keyword
packagename valid package name

(i) Define the class to be added in the package. It is


better to define the class public
3.83

The general form of a package is


package packagename;

public class name

(i) Create a sub directory under the directory with tha


name of the package. The general form for creating
sub directory is

C:jdk1.3bin>md packagenameJ
C:jdk1.3tbin>cd packagename J

C:jdk1.3tbin\packagename>
Store the source file as classname java in the
(iv) .

created subdirectory with the package name.

(v) Compile the file. This creates the .class file in the
subdirectory.
(vi) lf we want to create another package within this
package, store the source file in a subdirectory within
the already created subdirectory. By following tnis
we can create hierarchy of
packages as shown belo
3.84

class1,class2,..classn
class1,class2,..classn

class1,class2,...classn

package3

package2

package1

of
command to create the above hierarchy
(vi) The DOS
package is,

C>md package1

C>cd package1
C:/package1>md package2

C/package1>cd package2
C:/package1/package2>md package3
as shown
required classes
in the packages
Add the
in the above figure.
A 06

s of exception handling
n s i c so fe x

The structure given below shows


preptiom
eption handling the basics o

try

statements for checking the errors

catch (Exceptionclassl objl)

statements for handling the error

catch(Exceptionclass2 obj2)

statements for handling the error.

catch Exceptioonclassn objn)

for handling the


error
statements

finally
before exiting
Statements to be executed
4.06

Where
- Keywords
try, catch and finally
Exception class1, Exceptionclass2 Prede fined exceptir
Exceptionclassn classes that can ar
a specitic excepton
Ifan exception occurs within the statementsin
the
block, it is thrown automatically. The thrown
caught by the corresponding catch block. Thenexception
it evee
the statements for handling the
exeote
exception(error).
The finally block statements will be
executed bete
exiting the exception handler.

Try block

The general form of try block is

try
{
statement 1;

statement n;

Where

try keyword
Statementswho
statement 1, can crealean

exception
statementn
4.07

This block is used to test the


program statements or
ingle statement for run time errors(exception). If an
single sta
a
e v e n

ero
found, the try block throws the error and is caught by
efiock. In a program there can be any number of try
h block.

calch

DOCks.

Throwingaan exception

Normally the exceptions are thrown by the try block


natically(implicit).
But with the help of the statement
U t o n

t h r o w

throw
the exceptions explicitly. This is called
The general form is
can
we exception.
an
throwing

try

--

throw exception object

Where
- keyword
try, throw
exception class
Exception object already defined
object.
ITuication between threadsS). a pite

Byte stream classes


Byte stream classes provides
operations in bytes. A byte stream can befacilities to do i¢
of data used with anu.
including binary data. Since the any yse
unidirectional, they can transmit data bytes in streams are
one directio
only. Therefore there are two
abstract classes name
InputStream and outputStream to do read and
write
operations.
These abstract classes contain
several subclasses
to handle different 1/O
devices.
) InputStream class
inputstream is an abstract class and is used to sutrear
input data in bytes. This class contains number of meti
to do input operations. If error occurs it throws IOException
The table given below lists the methods.
4.45

Method Description
i n ta v a i l a b l e ( )
This method gives the nurnber of bytes
of input currently available for reading

v o i dc l o s e ( )
This method is used to close the input
SOurce

This method is used to read a byte from


int r e a d ( )
input stream

This method is used to read an array


read(byte b[ ])
int of bytes into b array
This method is used to read m bytes
read(byte b[ ],
int into b array starting from nh byte.
int n, int m)

long skiplong n) This method is used to ignore (skip) n|


bytes of input

This method is used to go


back to the
void reset()
begining of the stream
( i 1 ) O u t p u l S t r e a m c l a s s e s

(ii)
OutputStream is an abstract class and is
data in bytes. This class contains
USed to
steam output
operations. If error occurs
it
numbe
methods to do output
below lis the
throws G
Exception.
The table given methods
Method Description
This method is used to close the
voidclose()
stream
output
This method is used to clear the outpu
void flush()
buffers.
This method is used to write a sirgje
void write(int b)
to an output stream.
byte
This method is used to write a butifer
void write(byte b[ ]})
array b of bytes to an output stream
This method is used to write bytes
m
void write(byte b[ ], | from n
int n, int m) from buffer array b starting

byte.
Character stream classes
are used to do
l/o operato
Character classes.
stream
character

in 16 bit unicode characters. There are two types


of

stream classes. They are

(i) Reader (i) Writer


i Rede
A.47
Method
abstract oid
closeOThis methodDescription
Is used
sed to
source. close input
int read( )
This method is
used to return an
integer representation
available character from ofthethe next
input stream. -1 will be invoking
end of file is returned when
reached.
int read(char b[ ]) This method is used to
read up to
b.length characters into the
array b. Then it returns the buffer
number of characters that actual
were
successfully read. -1 will be
returned
when end of file is reached.
abstract int read This method is used to read m
(char b[ ], int n, characters into buffer b starting from
int m) nth index.
boolean read() This method return true if the next input
is not waiting else false.
Voidreset() This method resets the pointer to the
previous set mark.
long skip(long n) This method skips n input characters
and returns the number of characters

1) Writer
skipped.
m
4.48

Method Description
method is used to close the
abstract void close( ) This
output stream.

abstract void flush(O|This


method is usedto clearthe outni
buffers.

void write(int b) This method is used to write a single


character to an output stream.

void write(byte b[ ]) This method is used to write an buffer


of character to an output stream.
array
write m
write(byte b[ ]. This method is used to
void characters from buffer array b starting
int n, int m)
from n character.

You might also like