Sei sulla pagina 1di 90

OOPS Through JAVA 1

1. Program for printing the roots of Quadratic equation


Description:
In this program we are finding the roots of the quadratic equation. Depends
upon the value of the determinant we are printing the nature as well as the
corresponding roots. The particular part is explained below:
public static void main ( String args[] ) :

Every program begins with the main() method. All the Java applications
begin execution by calling main(). The full meaning of each part of this is:
public:
The public keyword is an access specifier, which allows the programmer to
control the visibility of class members. When a class member is preceded by
public, then that member may be accessed by code outside the class in which it is
declared. main( ) must be declared as public, since it must be called by code
outside of its classe when the program is started.
static:
The keyword static allows main( ) to be called without having to instantiate
a particular instance of the class. This is necessary since main ( ) is called by the
JVM before any objects are made.
void:
The keyword void simply tells the compiler that main ( ) doesn’t return a
value.
String args [ ]:
In main ( ) , there is only one parameter, albeit a complicated one. String
args [ ] declares a parameter named args, which is an array of instances of the
class String. args receives any command-line arguments present when the program
is executed.
Math . sqrt ( ):
OOPS Through JAVA 2

sqrt ( ) is a member of the Math class, to compute the square root of its
argument. Its arguments are of type double.
switch case:
switch is a multi-way decision making decision control statement. The
switch statement tests the value of a given variable or expression against a list of
case values and when a match is found, a block of statements associated with that
case is executed. The general form of it is :
switch ( expression )
{
case value – 1 : block – 1
break;
case value – 2 : block – 2
break;
………
default : default – block
break;
}
statement – x ;

After the switch statements terminates statement – x will be executed. The


expression must be of type byte,short,int or char each of the values specified in the
case statements must be of a type compatible with the expression. Each case
value must be a unique literal. Duplicate case values are not allowed.
OOPS Through JAVA 3

Program:
class Equation
{
int a , b , c , ch ;
double e , d , r1 , r2 ;
Equation ( int x , int y , int z )
{
a = x ;
b = y ;
c = z ;
}
public void value ( )
{
d = ( b * b ) - ( 4 * a * c ) ;
e = Math.sqrt ( d ) ;
if ( d == 0 )
ch = 1 ;
else
if ( d > 0 )
ch = 2 ;
else
if ( d < 0 )
ch = 3 ;
switch ( ch )
{
case 1:
System.out.println ( " Roots are
Real & Equal " ) ;
r1 = -b / ( 2.0 * a ) ;
r2 = r1 ;
System.out.println ( " R1 : " + r1 +
" R2 : " + r2 ) ;
break;
case 2:
System.out.println ( " Roots are
Reals and Unequal " ) ;
r1 = ( -b + ( e/ ( 2 * a ) ) ) ;
r2 = ( -b - ( e/ ( 2 * a ) ) ) ;
System.out.println ( " R1 : " + r1 +
" R2 : " + r2 ) ;
break;
default:
System.out.println ( " Roots Are
Imaginary " ) ;
}
}
public static void main(String[] args)
OOPS Through JAVA 4

{
Equation roots = new Equation ( 1 , 4 , 4 ) ;
roots . value ( ) ;
}
}
OOPS Through JAVA 5

Output:

2. Program to print the FIBONACCI series


OOPS Through JAVA 6

Description:
In this program we are printing the FIBONACCI series. The explanation
about it is given below:
Integer data type:
Java defines four interger types: byte, short, int, and long. All of these are
signed, positive and negative values. Java doesn’t support unsigned integer. The
width of an integer types should not be thought of as the amount of storage it
consumes but rather as the behaviour it defines for variables and expressions of
that type.
byte: The smallest integer tye is byte. This is signed 8-bit type that has a range
from -128 to 127. It is especially useful when you’re working with a stream of data
from a network or a file. E.g. byte b , c ;
short: short is a signed 16-bit type. It has a range from -32768 to 32767.
E.g. short s , t ;
int: The most commonly used integer type is int. it is signed 32-bit type that has a
range from -2147483648 to 2147483647. These variables are commonly employed
to control loops and to index arrays.
long: The long is a signed 64-bit type and is useful for those occasions where an
int type is not large enough to hold the desired value. The range of a long is quie
large.
Methods:
A class with only data fields and without methods that operate on that data
has no life. Methods are similar to the functions of C/C++. It is a set of instructions
or code used to perform some particular task or operation. Methods are declared
inside the body of the class but immediately after the declaration of instance
variable. The general form of a method declaration is
type methodname ( parameter – list )
{
OOPS Through JAVA 7

method – body ;
}
Method declaration have four basic parts:
1. The name of the method
2. The type of the value the method returns
3. A list of parameters
4. The body of the method
In this program we have used methods like void change ( ) & void display (). They
have no return values and no parameters.
for loop:
It is a loop control statement. The general form of the for statement is:
for ( initialization; condition; iteration )
{
// body
}
When the loop first starts, the initialization portion of the loop is executed. Next,
condition is evaluated. It test the loop control variable against a target vlue. If true,
then body of loop is executed, else it will terminate. Next, the iteration portion of
the loop is executed where the increments or decrements the loop control variable
takes place.E.g. for ( i = 10 ; i > 0 ; i-- )

Program:
OOPS Through JAVA 8

class Fibnocii
{
int f1 , f2 , f3 ;
Fibnocii ( )
{
f1 = -1 ; f2 = 1 ; f3 = f1 + f2 ;
}
void change ( )
{
f1 = f2 ;
f2 = f3 ;
f3 = f1 + f2 ;
}
void display ( )
{
System.out.println ( f3 ) ;
}
}
class Series
{
public static void main(String[] args)
{
Fibnocii fib = new Fibnocii ( ) ;
System.out.println ( " Fibnocii sereis upto 10
rows are.... " ) ;
for ( int i = 1 ; i <= 10; i++ )
{
fib.display ( ) ;
fib.change ( ) ;
}
}
}

Output:
OOPS Through JAVA 9

3. Program to print the PRIME number


OOPS Through JAVA 10

Description:

JOptionPane.showInputDialog:
JOptionPane makes it easy to pop up a standard dialog box that
prompts users for a value or informs them of something.
While the JOptionPane class may appear complex because of the large number
of methods, almost all uses of this class are one-line calls to one of the static
showXxxDialog methods shown below:

Method Name Description


showConfirmDialog Asks a confirming question, like yes/no/cancel.
showInputDialog Prompt for some input.
showMessageDialog Tell the user about something that has happened.
showOptionDialog The Grand Unification of the above three.

Integer.parseInt :

public static int parseInt(String s)


throws NumberFormatException
Parses the string argument as a signed decimal integer. The characters in the string
must all be decimal digits, except that the first character may be an ASCII minus
sign '-' ('\u002D') to indicate a negative value. The resulting integer value is
returned, exactly as if the argument and the radix 10 were given as arguments to
the parseInt(java.lang.String, int) method.
Parameters:
s - a String containing the int representation to be parsed
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer.
System.out.println ( ):
OOPS Through JAVA 11

println ( ) displays the string which is passed to it. The line begines with
System.out. System is a predefined class that provides access to the system and out
is the output stream that is connected to the console.
if statement :
It is a decision control statement. The general form of a simple if statement
is
if ( test expression )
{
statement – block ;
}
statement – x ;
The statement-block may be a single statement or a group of statements. If
the expression is true the statement block will be executed otherwise the statement
block will be skipped and the execution will jump to the statement – x ;

Program:
import java.io.*;
import javax.swing.*;
OOPS Through JAVA 12

class Prime
{
public static void main(String[] args) throws
IOException
{
String sn = JOptionPane.showInputDialog ( "
Enter Number : " ) ;
int max = Integer.parseInt ( sn ) ;
int i= 1 , n ;
System.out.println ( " Prime No. upto " +
max ) ;
System.out.println ( i ) ;

for ( n = 2 ; n <= max ; n++ )


{
for ( i = 2 ; i <= n; i++ )
{
if ( n % i == 0 )
break ;
}
if ( i == n )
System.out.println ( n ) ;

}
}

Output:
OOPS Through JAVA 13

4. Program to print the sort the list of names


OOPS Through JAVA 14

Description:
In this program we are sorting the list of names like “Software”,
“Networking”, & “Database”. Its each part is explained below:
String Class:
It represents a sequence of characters in Java. In Java, String are class
objects and implemented using two classes, namely, String & StringBuffer. A Java
string is an instantiated object of the String class. Java strings, as compared to C
strings, are more reliable and predictable. This is basically due to C’s lack of
bounds-checking. It can be declared and created as follows:
String stringname ;
stringname = new String ( “String” ) ;
compareTo ( ) :
For sorting applications, you need to know which is less than, equal to, or
greater than the next. A string is less than another itf it comes before the other in
dictionary order. A string is greater than another if it comes after the other in
dictionary order. The String method campareTo() serves this purpose. It has the
general form as:
int compareTo ( String str )
Here, str is the String being compared with the invoking String. The result of the
comparison is returned and is interpreted, as shown here:
Less than zero : The invoking string is less than str.
Greater than zero : The invoking string is greater than str.
Zero : The two strings are equal.

Others methods related to String class are:


String length:
The length of a string is the number of characters that it contains. To
obtain this value, call the length ( ) method, shown here:
OOPS Through JAVA 15

int length ( ) ;
E.g.
System.out.println ( s . length ( ) ) ;
String Concatenation:

In general, Java does not allow operator to be applied to String


objects. The one exception to this rule is the + operator, which concatenates
two strings, producing a String object as the result. This allows you to chain
together a series of + operator. For Example, the following concatenates three
strings:
String age = “9” ;
String a = “He is “ + age + “ years old. “ ;
System.out.println ( a ) ;

Program:
class SortString
OOPS Through JAVA 16

{ static String str [] =


{ "Software","Network","Database"
} ;
public static void main(String[] args)
{
System.out.println ( " String sorted as... ")
;
for ( int i = 0 ; i < str.length ; i++ )
{
for (int j = i + 1 ; j < str.length ; j++
)
{
if ( str [ j ] . compareTo ( str [ i
]) < 0 )
{
String t = str [ i ] ;
str [ i ] = str [ j ] ;
str [ j ] = t ;
}
}
System.out.println ( str [ i ] ) ;
}
}
}

Output:
OOPS Through JAVA 17

5. Program to find the Palindrome of String


OOPS Through JAVA 18

Description:
In this program we are finding String Palindrome i.e. a String whose reverse
is same as the original string like “LIRIL”. In the program we are using “modern”,
“malayalam”, & “madam”. Out of this, except “modern”, other two are STRING
PALINDROME. The description of each is given below:
Characters:
In java, the data type used to store characters is char. However, C/C++
beware: char in Java is not same as char in C/C++. In that it is 8-bit wide. This is
not the case in java. Instead, Java uses Unicode to represent characters. Unicode
defines a fully international character set that can represent all of the character
found in the world’s human languages. For this purpose, it requires 16 bits. Thus,
in Java char is a 16-bit type. The range of a char is 0 to 65536. there is no negative
chars.

The break Statement:


The break statement has two forms: labeled and unlabeled. You saw the
unlabeled form in the previous discussion of the switch statement. An unlabeled
break statement terminates the innermost switch, for, while, or do-while
statement, but a labeled break terminates an outer statement. The break
statement terminates the labeled statement; it does not transfer the flow of control
to the label. Control flow is transferred to the statement immediately following the
labeled (terminated) statement.
An identifier followed by colon ( : ) is called labeled if it is called by
postponing the break statement it is called as Labelled Break.
length( ):
The length of a string is the number of characters that it contains. To obtain
this value, call the length ( ) method, shown here:
int length ( )
The following fragment prints “3”, since there are three characters in the string s:
OOPS Through JAVA 19

char chars[] = { ‘a’ , ‘b’ , ‘c’ } ;


String s = new String (chars) ;
System.out.println ( s.length ( ) ) ;

Program:
OOPS Through JAVA 20

class Palindrome
{
public static void main(String[] args)
{
char words [] [] = { { 'm','o','d','e','r','n'} ,
{
'm','a','l',’a’,’y’,'a','l','a','m'
}
,{ 'm','a','d','a','m'} } ;
int i , j, n, wordlen ;
int wordcount = words.length ;
int charcount ;
System.out.println ( " The Given words are ..\n "
) ;
for ( i = 0 ; i < wordcount ; i++ )
System.out.println ( ( new String ( words [ i]
) ) + " " ) ;
System.out.println ( ) ;
for (i = 0; i < wordcount; i++ )
word:
{
charcount = words [ i ] . length ;
for ( j = 0 , n = charscount - 1 ; j < n ;j++
, n--)
if ( words [ i ] [ j ] != words [ i ] [
n ] )
{
System.out.println ( ( new String(
words[ i ] ) ) + "
: is NOT a PalindromE
" ) ;
break word;
}
System.out.println ( ( new String ( words
[ i ] ) ) + " : is a Palindrome " ) ;
}
}
}

Output:
OOPS Through JAVA 21

6. Program to calculate and print Matrix Multiplication


OOPS Through JAVA 22

Description:
In this program we are finding the Matrix multiplication using two for loops.
The description of the program is given below:
Arrays:
An array is a group of like-typed variables. To create an array, you first must
create an array variable of the desire type. The general form of a one-dimensional
array declaration is:
type var-name[ ] ;
Here, type declares the base type of the array. The base type determines the data
type of each element that comprises the array. Thus the base type for the array
determines what type of data the array will hold. For example, the following
declares an array name month_days with the type “array of int” ;
int month_days [ ] ;
new operator:
It is a special operator that allocates memory. The general form of new as it
applies to one-dimensional arrays appears as follows:
array-var = new type [ size ] ;
here, type specifies the type of data being allocated, size specifies the number of
elements in the array, and the array-var is the array variable that is linked to the
array. That is, to use new to allocate an array, you must specify the type and the
number of elements to allocate. The elements in an array allocated by new will
automatically be initialize to zero. This example allocates a 12 – element array of
integers and links them to month_days.
Month_days = new int [ 12 ] ;
After this statement executes, month_days will refere to an array of 12
integers further, all elements in the array will be initialized to zero.
Multidimensional Arrays:
In Java, multidimensional arrays are actually arrays of arrays. These, as you might
expect, look and act like regular multidimensional arrays. However, as you will
OOPS Through JAVA 23

see, there are a couple of subtle differences. To declare this variable, specify each
additional index using another set of square brakets. For example, the following
declares a two-dimensional array variable called twoD
int twoD [] [] = new int [4] [5] ;
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is
implements as an array of arrays of int.

Program:

class MatMul
{
OOPS Through JAVA 24

public static void main(String[] args)


{
int m1 [] [] = { { 5 , 4 , 7 } , { 3 , 5 , 8 } } ;
int m2 [] [] = { { 1 , 3 , 5 } , { 4 , 2 , 6 } ,
{3, 5 , 7 } } ;
int m3 [] [] = new int[2] [3] ;
int i , j , k ;
for ( i = 0 ; i < 2 ; i++ )
for ( j = 0 ; j < 3 ; j++ )
{
m3[ i ] [ j ] = 0 ;
for ( k = 0 ; k < 3 ; k++ )
m3 [ i ] [ j ] += m1 [ i ] [ k ] * m2 [k]
[ j];
}
System.out.println( " Matrix 1... \n " ) ;
for ( i = 0 ; i < 2 ; i++ )
{
for ( j = 0 ; j < 3 ; j++ )
System.out.print ( " " + m1 [ i ] [ j
]);
System.out.println ( ) ;
}
System.out.println( " Matrix 2... \n " ) ;
for ( i = 0 ; i < 3 ; i++ )
{
for ( j = 0 ; j < 3 ; j++ )
System.out.print ( " " + m2 [ i ] [ j
]);
System.out.println ( ) ;
}
System.out.println( " Resultant Matrix... \n " ) ;
for ( i = 0 ; i < 2 ; i++ )
{
for ( j = 0 ; j < 3 ; j++ )
System.out.print ( " " + m3 [ i ] [ j
]);
System.out.println ( ) ;
}
}
}

Output:
OOPS Through JAVA 25

7. Program to find balance of an account using PACKAGE


OOPS Through JAVA 26

Description:
In this we are making a MyPack package for class Balance. Its description is
given below:
Package:
Packages are containers for classes that are used to keep the class name
space compartmentalized. It is defined as a collection of classes. Packages are
similar to the directories and classes within a packages are similar to files in the
directory.
Creating Package:
To create a package, you choose a name for the package (naming
conventions are discussed in the next section) and put a package statement with
that name at the top of every source file that contains the types (classes, interfaces,
enumerations, and annotation types) that you want to include in the package.
The package statement (for example, package graphics;) must be the first
line in the source file. There can be only one package statement in each source file,
and it applies to all types in the file.

Note: If you put multiple types in a single source file, only one can be public,
and it must have the same name as the source file. For example, you can define
public class Circle in the file Circle.java, define public
interface Draggable in the file Draggable.java, define public
enum Day in the file Day.java, and so forth.
You can include non-public types in the same file as a public type (this is strongly
discouraged, unless the non-public types are small and closely related to the public
type), but only the public type will be accessible from outside of the package. All
the top-level, non-public types will be package private.
Accessing a Package:
The import statement can be used to search a list of packages for a particular
class. The general form of import statement for searching a class is as follows:
OOPS Through JAVA 27

Import package1 [ .package2 ] [ .package3 ] . classname ;


Here, package1 is the name of the top level package,, package2 is the name of the
package that is inside the package, and so on. The following is an example of
importing a particular class:
import firstPackage . secondPackage . MyClass ;

Program:

package mypack;
class Balance
OOPS Through JAVA 28

{
String name;
double bal;
Balance(String n,double b)
{
name=n;
bal=b;
}
void show()
{
if(bal<0)
System.out.println("-->");
System.out.println(name+":$"+bal);
}
}
class Accbal
{
public static void main(String args[])
{
Balance current[]=new Balance[3];
current [0]=new Balance("jack",123.3);
current [1]=new Balance("jill",157.02);
current [2]=new Balance("jitom",-12.33);
for(int i=0;i<3;i++)
current[i].show();
}
}

Output:
OOPS Through JAVA 29

8. Program to Read data from File and print it


OOPS Through JAVA 30

Description:

Reading and Writing Files:

Java provides a number of classes and methods that allow you to read and
write files. In Java, all files are byte-oriented, and Java provides methods to read
and write Bytes form and to a file. However Java allows you to wrap a byte-
oriented file stream with in a character-based object.

Two of the most often-used stream classes are FileInputStream and


FileOutputStream, which create byte streams linked to files. To open a file, simply
create an object of one of the classes, specifying the name of the file as an
argument to the constructor. While both classes support additional, overridden
constructors, the following are the true forms that will be using :

FileInputStream(String file name) Throws FileNotFoundException

FileOutputStream(String file name) Throws FileNotFoundException

Here, file name specifies the name of the file that want to open. When create
a input stream, is the file does not exist, then FileNotFound Exception is thrown.
For output streams, if the file cannot be createdm, then FileNotFoundException is
thrown. When an output file is opened, any preexisting file by the same name is
destroyed.

In earlier versions of Java, FileOutputStream() threw an IOException when an .

.output file couldnot be created. This was changed by Java 2.

When you are done with a file, you should close it by calling close(). It is defined
by both FileInputStream and FileOutputStream, as shown here :

Void close() throws IOException


OOPS Through JAVA 31

To read from a file, you can use a version or read() that is defined within
FileInputStream. The one that we will use is shown here :

Int read() throws IOException

Each time that it is called, it reads a single byte from the file and returns the byte as
an integer value. Read() returns – 1 when the end of the file is encountered. It can
throw an IOException.

Unlike some other computer languages including c and c++, which use error
codes to report file errors, Java uses its exception handling mechanism. Not only
does this make file handling cleaner, but it also enables Java to easily differentiate
the end-of-file condition form file errors when input is being performed. In c/c++,
many input functions return the same value when an error occurs and when the end
of the file is reached.( That is, in c/c++, an EOF condition often is mapped to the
same value as an input error.) This usually means that the programmer must
include extra program statements to determine which event actually occurred. In
Java, errors are passed to your program via exceptions, not by values returned by
read(). Thus, when read() returns-1, it means only one thing : the end of the file has
been encountered.
OOPS Through JAVA 32

Program :
import java.io.*;

public class ReadFile

{
public static void main(String[] args) throws
IOException
{
FileInputStream fis = new FileInputStream (
"file.txt" ) ;
int k ;
int i = 1 ;
System.out.println ( i ) ;
i = 2 ;
while ( ( k=fis.read() ) != -1 )
{
if ((( char ) k ) == '\n' )
{
System.out.print ( (char) k ) ;
System.out.print ( i ) ;
i++ ;
}
System.out.print ( (char) k ) ;
}
fis.close ( ) ;
}
}
OOPS Through JAVA 33

OUT PUT :-
OOPS Through JAVA 34

9. Program to print list of files , search files and rename file of the
Folder ( directory )

Description:
In this program we are reading a file from a specific folder and find its
various attributes like Is it a File? What is the Length of File? Is It a Directory?
What is the FileName? What is the PathName?.. and many more. The description
about this is given below:
File:
Files are a primary source and destination for data within many programs. A
directory in Java is treated simply as a FILE with one additional property – a list of
filenames that can be examine by the list( ) method.
The following are the constructors can be used to create File objects.

File ( String directoryPath )


File ( String directoryPath , String filename )
File ( File dirObj , String filename )
File ( URL uriObj )

Various Methods used in Files are:

1. getName
public String getName()
Returns the name of the file or directory denoted by this abstract pathname. This
is just the last name in the pathname's name sequence. If the pathname's name
sequence is empty, then the empty string is returned.
Returns:
The name of the file or directory denoted by this abstract pathname, or the
empty string if this pathname's name sequence is empty

2. getPath
public String getPath()
OOPS Through JAVA 35

Converts this abstract pathname into a pathname string. The resulting string uses
the default name-separator character to separate the names in the
name sequence.
Returns:
The string form of this abstract pathname
3. isDirectory
public boolean isDirectory()
Tests whether the file denoted by this abstract pathname is a directory.
Returns:
true if and only if the file denoted by this abstract pathname exists and is a
directory; false otherwise
4. isFile
public boolean isFile()
Tests whether the file denoted by this abstract pathname is a normal file. A file is
normal if it is not a directory and, in addition, satisfies other system-dependent
criteria. Any non-directory file created by a Java application is guaranteed to be a
normal file.
Returns:
true if and only if the file denoted by this abstract pathname exists and is a
normal file; false otherwise .
5. lastModified
Returns the time that the file denoted by this abstract pathname was
last modified.
OOPS Through JAVA 36

Program:

import java.io.*;

class FileDemo
{
public static void main(String[] args)
{
File fpath = new File ( "C:/" ) ;
File fname = new File ( fpath, "file.txt" ) ;
System.out.println ( " Path of Directory : " +
fname.getPath
( ) ) ;
System.out.println ( " Name of File : " +
fname.getName
( ) ) ;
System.out.println ( " Size of the File : " +
fname.length ( ) )
;
System.out.println ( " Is " + fpath.getName ( ) +
"
is a directory ? " +
fpath.isDirectory
( ) ) ;
System.out.println ( " Is " +fname.getName ( ) + "
is
a file ? " + fname.isFile ( ) )
;
System.out.println ( " Is the file - "
+fname.getName ( )+ " - exists ? "+ fname.exists ( ) ) ;
System.out.println ( " Is the directory - "
+fpath.getName ( )+ " - exists ? "
+fpath.exists ( ) ) ;
System.ou t.println ( " Modified on - " +
fpath.lastModified ( ) ) ;
String dirlist [ ] = fpath.list ( ) ;
int l = dirlist.length ;
System.out.println ( " \n Directory of " +
fpath.getName ( ) + "..\n" )
;
for ( int i = 0 ; i < l ; i++ )
System.out.println ( dirlist [ i ] ) ;
File newname = new File ( "newfile.txt" );
fname.renameTo ( newname ) ;
System.out.println ( " Is the file " +
fname.getName
OOPS Through JAVA 37

( ) + " exists ? " +


fname.exists
( ) ) ;

}
}
OOPS Through JAVA 38

Output:
OOPS Through JAVA 39

10. Program to read a file and print no. of words, characters in it

Description:
In this program we are reading a TXT file and find its various
attributes like no. of words, characters and lines in a file. Its description is given
below:
FileInputStream:

A FileInputStream obtains input bytes from a file in a file system.


FileInputStream is meant for reading streams of raw bytes such as image
data. For reading streams of characters, consider using FileReader.

FileInputStream has the following constructors:

FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the
file named by the File object file in the file system.

FileInputStream(FileDescriptor fdObj)
Creates a FileInputStream by using the file descriptor fdObj, which
represents an existing connection to an actual file in the file system.
FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the
file named by the path name name in the file system.

There are different methods belongs to FileInputStream as mentioned below:

int available()
Returns an estimate of the number of remaining bytes
that can be read (or skipped over) from this input stream
without blocking by the next invocation of a method for this
input stream.
OOPS Through JAVA 40

void close()
Closes this file input stream and releases any system
resources associated with the stream.
protected void finalize()
Ensures that the close method of this file input
stream is called when there are no more references to it.
FileChannel getChannel()
Returns the unique FileChannel object associated
with this file input stream.
FileDescriptor getFD()
Returns the FileDescriptor object that
represents the connection to the actual file in the file system
being used by this FileInputStream.

int read()
Reads a byte of data from this input stream.
int read(byte[] b)
Reads up to b.length bytes of data from this input
stream into an array of bytes.
int read(byte[] b, int off, int len)
Reads up to len bytes of data from this input stream
into an array of bytes.

Program:
import java.io.*;
class FileAttribute
OOPS Through JAVA 41

{
public static void main(String[] args)
{
int lines = 1 , words = 1 , chars = 1 ;
if ( args.length == 0 )
{
System.out.println ( " No file given at
CommandLine " ) ;
System.exit ( 0 ) ;
}
File f1 = new File ( args [ 0 ] ) ;
try
{
int ch ;
FileInputStream fins = new FileInputStream
(f1);
while ((ch = fins.read ( ) ) != -1 )
{
chars++ ;
switch ((char) ch)
{
case '\t':
case ' ' :
words++;
break;
case '\n':
words++;
lines++;
}
}
}
catch (IOException ioe)
{
System.out.println ( " IO Problem " ) ;
}
System.out.println ( args[ 0 ] + " file contains
..\n\n" + chars +" Characters\n"+ words +"
Words\n"+ lines +" Lines" ) ;
}
}

Output:
OOPS Through JAVA 42

11. Program for implementing STACK

Description:
OOPS Through JAVA 43

In this program we are printing the two stack elements using the concept of
Stack (of data structure). The description of various methods of this program is
given below:

Classes:

The class is at the core of Java. It is the logical construct upon which the
entire Java language is built because it defines the shape and nature of an object.
As such, the class forms the basis for object-oriented programming in Java.

A class is declared by use of the class keyword. Classes can get much more
complext. A simplified general form of a class definition is shown here:

class classname {

type instance-variable1;

type instance-variable2;

//……

type instance-variableN;

type methodName1 ( parameter-list) {

// body of method

type methodName2 ( parameter-list) {

// body of method

//……

type methodNameN ( parameter-list ) {

// body of method

}
OOPS Through JAVA 44

The data, or variable, defined within a class are called instance variables.
The code is contained within methods. Collectively, the methods and variables
defined within a class are called member of the class. All the methods have same
general form as main ( ).

Accessing members of class:

Accessing members of a class is only possible by using an object. An object


of a class is created by using a new operator which allocated memory for each
object. It can also access by its name if that class contains static variable or
method. The general form of accessing variables or methods is given below:

classname classobj = new classname ( ) ;

classobj . variable = values ;

classobj. methods ( ) ;

Program:

class Stack
OOPS Through JAVA 45

{
int s[] = new int [10 ] ;
int top ;
Stack ( )
{
top = -1 ;
}
void push ( int item )
{
if (top == 9 )
System.out.println ( " Stack Overflow " ) ;

else
s [++top] = item ;
}
int pop ( )
{
if ( top < 0 )
{
System.out.println( " Stack Underflow " ) ;
return 0 ;
}
else
return s [ top-- ] ;
}
}
class StackTest
{
public static void main(String[] args)
{
Stack mystack1 = new Stack ( ) ;
Stack mystack2 = new Stack ( ) ;
for ( int i = 0 ; i < 10 ; i++ )
{
mystack1.push ( i ) ;
}
for ( int i = 10 ; i < 20 ; i++ )
{
mystack2.push ( i ) ;
}
System.out.println( " Elements in MyStack1 : " ) ;
for ( int i = 0 ; i < 10 ; i++ )
{
System.out.println ( mystack1.pop ( ) ) ;
}
System.out.println("\n Elements in MyStack2 : " );
for ( int i = 0 ; i < 10 ; i++ )
OOPS Through JAVA 46

{
System.out.println ( mystack2.pop ( ) ) ;
}
}
}

Output:
OOPS Through JAVA 47

12. Program to print String on an Applet


Description:
OOPS Through JAVA 48

In this program we are printing a String “HelloINDIA” or “HelloJava”


based upon the parameter passed to applet. The description about this is discussed
below:

Applet:

An applet is a special kind of Java program that a browser enabled with Java
technology can download from the internet and run. An applet is typically
embedded inside a web-page and runs in the context of the browser. An applet
must be a subclass of the java.applet.Applet class, which provides the
standard interface between the applet and the browser environment.

Swing provides a special subclass of Applet, called


javax.swing.JApplet, which should be used for all applets that use Swing
components to construct their GUIs.

Life Cycle of an Applet:

Basically, there are four methods in the Applet class on which any applet
is built.

init: This method is intended for whatever initialization is needed for your
applet. It is called after the param attributes of the applet tag.

start: This method is automatically called after init method. It is also called
whenever user returns to the page containing the applet after visiting other pages.

stop: This method is automatically called whenever the user moves away from
the page containing applets. You can use this method to stop an animation.

destroy: This method is only called when the browser shuts down normally.

Thus, the applet can be initialized once and only once, started and stopped
one or more times in its life, and destroyed once and only once.

getParameter :
OOPS Through JAVA 49

It returns the parameter associated with paramName. Null is returned if the


specified parameter is not found.

drawString :

Inside paint ( ) is a call to drawString ( ), which is a member of the Graphics


class. This method outputs a string beginning at the specified X,Y location. It has
the following general form:

Void drawstring ( String message , int x , int y )

Here, message is the string to be output beginning at x,y. In a Java Window, the
upper-left corner is location 0,0.

After you enter the source code for SimpleApplet, compile in the same way
that you have been compiling programs. How ever, running SimpleApplet involves
a different process. Infact, there are two ways in which you can run an applet.

Executing the applet within a Java-compatible Web Browser.

Using an applet viewer, such as the standard SDK tool, appletviewer. An


applet viewer executes your applet in a window. This s generally the fastest and
wasiest way to test your applet
OOPS Through JAVA 50

Program:

import java.awt.*;
import java.applet.*;

public class Hello extends Applet


{
String str ;
public void init ( )
{
str = getParameter ( "String" ) ;
if ( str != null )
str = "Java" ;
str = "Hello" + str ;
}
public void paint ( Graphics gr )
{
gr.drawString ( str, 10, 100 ) ;
}
}

/*
<applet code = Hello.class width = 400 height = 200>
<param name = "String" value = "INDIA">
</applet>
*/
OOPS Through JAVA 51

Output:
OOPS Through JAVA 52

13. Program to illustrate how run-time POLYMORPHISM is


achieved
or Dynamic Method Dispatch
Description:

Dynamic Method Dispatch :-

If there were nothing more to method overriding than a name space


conversion, then it would be, at best, an interesting curiosity, but of little real
value. Method Overriding forms the basis for one of Java’s most powerful
concepts : Dynamic Method Dispatch. Dynamic method dispatch is the
mechanism by which a call to an overridden method is resolved at run time, rather
than compile time. Dynamic method dispatch is important because this is how java
implements run-time polymorphism.

Lets begin by restating an important principle : a superclass reference


variable can refer to a subclass object. Java uses this fact to resolve calls to
overridden methods at run time. Here is how, When an overridden method is called
through a super class reference, Java determines which version of that method to
execute based upon the type of the object being referred to at the time the call
occurs. Thus, this determination is made at run time. When different types of
objects are referred to, different versions of an overridden method will be called.
In other words, it is the type of the object being referred to ( not the type of the
reference variable ) that determines which version of an overridden method will be
executed. Therefore, if a super class contains a method that is overridden by a
subclass, then when different types of objects are referred to through a superclass
reference variable, different versions of the method are executed.

Why Overridden Methods ?

Overridden methods allow Java to support run-time polymorphism.


Polymorphism is essential to object-oriented programming for one reason : it
OOPS Through JAVA 53

allows a general class to specify methods that will be common to all of its
derivatives, while allowing subclasses to define the specific implementation of
some or all of those methods. Overridden methods are another way that Java
implements the “One interface, Multiple Methods” aspect of polymorphism.

Part of the key to successfully applying polymorphism is understanding that


the superclasses and the subclasses from a hierarchy which moves from lesser to
greater specialization. Used correctly, the super class provides all elements that a
subclass can use directly. It also defines those methods that the derived class must
implement on its own. This allows the subclass the flexibility to define its own
methods, yet still enforces a consistent interface. Thus, by combining inheritance
with overridden methods, a superclass can define the general form of the methods
that will be used by all of its subclasses.

Dynamic, run-time polymorphism is one of the most powerful mechanism


that object-oriented design brings to bear on code reuse and robustness. The ability
of existing code libraries to call methods on instances of new classes without
recompiling while maintaining a clean abstract interface is a profound powerful
tool.

Applying Method Overriding :-

The program creates a superclass called Figure that stores the dimensions of
various two-dimensional objects. It also defines a method called Area() that
computes the area of an object. The program derives two subclasses. The first is
Rectangle and the second is Triangle. Each of these subclasses overrides area()
so that it returns the area of a rectangle and a triangle respectively.
OOPS Through JAVA 54

Program:
class A

{
void callme ( )
{
System.out.println ( " Inside A's callme method
" ) ;
}
}
class B extends A
{
// override callme ( )
void callme ( )
{
System.out.println ( " Inside B's callme method "
) ;
}
}
class C extends A
{
// override callme ( )
void callme ( )
{
System.out.println ( " Inside C's callme method "
) ;
}
}
class Dispatch
{
public static void main(String[] args)
{
A a = new A ( ) ;
B b = new B ( ) ;
C c = new C ( ) ;
A ref ;
ref = a ;
ref.callme ( ) ;
ref = b ;
ref.callme ( ) ;
ref = c ;
ref.callme ( ) ;
}
}
OOPS Through JAVA 55

Output :-
OOPS Through JAVA 56

14.Program to make CALCULATOR application using


applets
Description:

Grid Layout :-

GridLayout lays out components in a two-dimensional grid. When you


istantiate a Grid Layout, you define the number of rows and columns. The
constructors supported by GridLayout are shown :

GridLayout()

GridLayout(int numRows,int numColumns)

GridLayout(int numRows,int numColumns,int horz,int vert)

The first creates a single column grid layout. The second form creates a
GridLayout with the specified number of rows and columns. The third form allows
you to specify the horizontal and vertical space left between components in horz
and vert, respectively. Either numrows or numColumns can be zero. Specifying
numRows as zero allows for unlimited-length columns. Specifying numcolumns
as zero allows for unlimited-length rows.

Using Insets :-

Sometimes we will want to leave a small amount of space between the


container that holds components and the window that contains it. To do this,
override the getInsets() method that is defined by Container. This function returns
an Insets object that contains the top, bottom, left and right insert to be used when
the container is displayed. These values are used by layout manager to insert the
components when it lays out the window. The constructor for Inset is :
OOPS Through JAVA 57

Insets(int top,int left,int bottom,int right)

These values passed in top,left,bottom and right specify the amount of space
between the container and its enclosing window.

The getInsets() method has this general form :

Insets GetInsets()

When overriding one of these methods, you must return a new Insets object
that contains the inset spacing you desire.
OOPS Through JAVA 58

Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class CalculatorPanel extends JPanel implements

ActionListener
{
private JTextField display ;
private double arg = 0 ;
private String op = "=" ;
private boolean start = true ;
public CalculatorPanel ( )
{
setLayout ( new BorderLayout ( ) ) ;
display = new JTextField ( "0" ) ;
display.setEditable ( false ) ;
add ( display , "North" ) ;
JPanel p = new JPanel ( ) ;
p.setLayout ( new GridLayout ( 4 , 4 ) ) ;
String buttons = "789/456*123-0=+" ;
for ( int i = 0 ; i < buttons.length ( ) ;i++)
addButton ( p , buttons.substring ( i,i+1
)) ;
add ( p , "Center" ) ;
}
private void addButton ( Container c , String s )
{
JButton b = new JButton ( s ) ;
c.add ( b ) ;
b.addActionListener ( this ) ;
}
public void actionPerformed ( ActionEvent evt )
{
String s = evt.getActionCommand ( ) ;
if ( '0' <= s.charAt ( 0 ) && s.charAt ( 0 )
<='9' || s.equals (
"." ) )
{
if ( start)
display.setText ( s ) ;
else
display.setText ( display.getText (
) +s ) ;
start = false ;
}
OOPS Through JAVA 59

else
{
if ( start )
{
if ( s.equals ( "-" ))
{
display.setText ( s ) ;
start = false ;
}
else
op = s ;
}
else
{
calculate ( Double.parseDouble (
display.getText ( ) )
) ;
op = s ;
start = true ;
}
}
}
public void calculate ( double n )
{
if ( op.equals ("+"))
arg += n ;
else if ( op.equals ("-"))
arg -= n ;
else if ( op.equals ("*"))
arg *= n ;
else if ( op.equals ("/"))
arg /= n ;
else if ( op.equals ("="))
arg = n ;
display.setText ( " " +arg ) ;
}
}

public class CalculatorApplet extends JApplet


{
public void init ( )
{
Container contentPane = getContentPane ( ) ;
contentPane.add ( new CalculatorPanel ( ) );
}
}
OOPS Through JAVA 60

/*
<applet code = "CalculatorApplet.class" height = 500
width = 400 >
</applet>
*/
OOPS Through JAVA 61

Output:
OOPS Through JAVA 62

15. Program to perfrome Mouse Event


Description:

Handling Mouse Events :

To handle mouse events must implement the MouseListener and the


MouseMotionListener interfaces. It displays the current coordinates of the Mouse
in the Applet’s status window. Each time a button is pressed, the word “Down” is
displayed at the location of the mouse pointer. Each time the button is released the
word “UP” is shown. If a button is clicked, the message “Mouse Clicked” is
displayed in the upper left corner of the applet display area.

As the mouse enters or exits the applet window, a message is displayed in


the upper-left corner of the applet display area. When dragging the mouse, a * is
shown, which tracks with the Mouse Pointer as it is dragged. Notice that the two
variables, Mouse X and Mouse Y, store the location of the Mouse when a mouse
pressed, released, or dragged event occurs. These coordinates are then used by
Paint() to display Output at the point of the occurrences.

The MouseEvents class extends Applet and implements both the Mouse
Listener and MouseMotionListener interfaces. These two interfaces contain
methods that receive and process the various types of Mouse events. Notice that
the Applet is both the source and the Listener for these events. This works because
Component, which supplies the addMouseListener() and
addMouseMotionListener() methods, is a superclass of Applet. Being both the
source and the listener for events is a common situation for Applets.
OOPS Through JAVA 63

Inside init(), the applet registers itself as a listener for mouse events. This is
done by using addMouseListener() and addMouseMotionListener(), which are
members of Component.

Void ddMouseListener(MouseListener ml)

Void addMouseMotionListener(MouseMotionListener mml)

Here, ml is a reference to the object receiving mouse events, and mml is a


reference to the object receiving mouse motion events. In the program the same
object is used for both.

The applet then implements all of the methods defined by the


MouseListener and MouseMotionListener interfaces. These are the event
handlers for the various mouse events. Each method handles its event and then
returns.
OOPS Through JAVA 64

Program:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
public class MouseEventsHandle extends Applet
implements MouseListener, MouseMotionListener
{
String txt = "Nothing" ;
int x = 10 , y = 30 ;
public void init ( )
{
addMouseListener ( this ) ;
addMouseMotionListener ( this ) ;
}
public void mouseClicked ( MouseEvent me )
{
txt = "Mouse Clicked" ;
repaint () ;
}
public void mouseEntered ( MouseEvent me )
{
txt = "Mouse Entered" ;
repaint ( ) ;
}
public void mouseExited ( MouseEvent me )
{
txt = "Mouse Exited" ;
repaint () ;
}
public void mousePressed ( MouseEvent me )
{
txt = "Mouse Pressed" ;
setForeground ( Color.red ) ;
repaint ( ) ;
}
public void mouseReleased ( MouseEvent me )
{
txt = "Mouse Released" ;
setForeground ( Color.red ) ;
repaint ( ) ;
}
public void mouseDragged ( MouseEvent me )
{
txt = "Mouse Dragged" ;
setForeground ( Color.magenta ) ;
repaint ( ) ;
OOPS Through JAVA 65

}
public void mouseMoved ( MouseEvent me )
{
txt = "Mouse Moved " ;
setForeground ( Color.blue ) ;
repaint ( ) ;
}
public void paint ( Graphics grp )
{
grp . drawString ( txt , 20 , 40 ) ;
showStatus ( "Mouse Event Handling..... " ) ;
}
}

/*
<applet code = "MouseEventsHandle.class" width = 400
height = 500>
</applet>
*/
OOPS Through JAVA 66

Output:
OOPS Through JAVA 67

16. Program to perform MultiThreading by implementing


Runnable interface
Description:

Using MultiThreading :

It is a concept in which a program is divide into two or more subprograms


or, which can be executed at the same time. The part of a program or subprogram
is called a thread and each thread executes separately. Multithreading ais a
powerful programming technique that enables to write efficient programs by
making maximum use of the CPU because the CPU idle time can be reduce to a
minimum.

It is useful in a number of ways. It enables the programmers to do multiple


things at a time. They can divide a large program into threads and execute them in
parallel. It is very much important in a networked environment in which Java
operates.

Multithreading can be done in two ways:

1. By implementing Runnable interface

2. By extending Thread class.

The key to utilizing this support effectively is to think concurrently rather


than serially. For example, when you have two subclasses within a program that
can execute concurrently, make them individual threads. With the careful use of
multithreading, you can create very efficient programs. A word of caution is in
order, However : If you create too many threads, you can actually degrade the
performance of your program rather than enhance it. Remember, some overhead is
associated with context switching. If you create too many threads, more CPU time
will be spent changing contexts than executing the program.
OOPS Through JAVA 68

Program:
class NewThread implements Runnable
{
String name ;
Thread t ;
NewThread ( String threadname )
{
name = threadname ;
t = new Thread ( this , name ) ;
System.out.println ( " NewThread: " + t ) ;
t.start ( ) ;
}
public void run ( )
{
try
{
for ( int i = 5 ; i > 0 ; i-- )
{
System.out.println ( name + " : " +
i ) ;
Thread.sleep ( 1000 ) ;
}
}
catch ( InterruptedException e)
{
System.out.println ( name + " interrupted
" ) ;
}
System.out.println ( name + " exiting... " ) ;
}
}

class MultiThreadDemo
{
public static void main(String[] args)
{
new NewThread ( "One" ) ;
new NewThread ( "Two" ) ;
new NewThread ( "Three" ) ;
try
{
Thread.sleep ( 10000 ) ;
}
catch (InterruptedException e)
{
System.out.println ( " Main Thread
Interrupted " ) ;
OOPS Through JAVA 69

}
System.out.println ( " Main Thread Exiting....
" ) ;
}
}
OOPS Through JAVA 70

Output:
OOPS Through JAVA 71

17. Program to implement Thread InterCommunication for


Producer and Consumer
Description:

Interthread Communication :

The use of the implicit monitors in Java objects is powerful, but you can
achieve a more subtle level of control through inter process communication. This
is especially easy in java.

Multithreading replaces event loop programming by dividing your tasks into


discrete and logical units. Threads also provide a secondary benefit : they do away
with polling. Polling is usually implemented by a loop that is used to check some
repeatedly. Once the condition is True, appropriate action is taken. This wastes
CPU time. For example consider the classic queuing problem, where one thread is
producing some date and another is consuming data. To make the finished before it
generates more data. In a polling system, the consumer would waste many CPU
cycles while it waited for the producer to produce. Once the producer was finished,
it would start polling, wasting more CPU cycles waiting for the consumer to
finish, and so on. Clearly this situation is undesirable.

To avoid polling, Java includes an elegant inter process communication


mechanism via the wait(),notify(), and notifyall() methods. These methods are
implemented as final methods in Object, so all classes have them. All three
conceptually advanced from a computer science perspective, the rules for using
these methods are actually quite simple :

Wait() tells the calling thread to give up the monitor and go to sleep intil some
other thread enters the same monitor and calls natify()

Notify() wakes up the first thread that called wait() on the same object.
OOPS Through JAVA 72

notifyAll() wakes up all the threads that called wait() on the same object. The
highest priority thread will run first.

These methods are declared within Object, as shoen here :

Final void wait() throws InterruptedException

Final void notify()

Final void notifyall()


OOPS Through JAVA 73

Program:
class Q
{
int n;
boolean valueSet = false ;
synchronized int get()
{
if ( !valueSet)
try
{
wait ( ) ;
}
catch ( InterruptedException e)
{
System.out.println ( " Interrupted
Exception caught " ) ;
}
System.out.println ( " Got : " + n ) ;
valueSet = false ;
notify ( ) ;
return n ;
}
synchronized void put( int n )
{
if ( valueSet)
try
{
wait( ) ;
}
catch ( InterruptedException e)
{
System.out.println ( " Interrupted
Exception caugth " ) ;
}
this . n = n ;
valueSet = true ;
System.out.println ( " Put : " + n ) ;
notify ( ) ;
}
}

class Producer implements Runnable


{
Q q ;
Producer ( Q q )
{
this.q = q ;
OOPS Through JAVA 74

new Thread ( this, "Producer" ).start( ) ;


}
public void run( )
{
int i = 0 ;
while ( true)
q.put ( i++ ) ;
}
}

class Consumer implements Runnable


{
Q q ;
Consumer ( Q q )
{
this.q = q ;
new Thread ( this , "Consumer" ).start ( ) ;
}
public void run( )
{
while (true)
q.get( );
}
}

class PCFixed
{
public static void main ( String args[] )
{
Q q = new Q ( ) ;
new Producer ( q ) ;
new Consumer ( q ) ;
System.out.println ( " Press Control + C to
stop... " ) ;
}
}
OOPS Through JAVA 75

Output:
OOPS Through JAVA 76

18. Program to create BarChart


THEORY :-

The HTML APPLET Tag:

The APPLET tag is used to start an applet from both an HTML document
and from an applet viewer. An applet viewr will execute each APPLET tag that it
finds in a separate window, while web browsers like Netscape Navigator, will
allow many applets on a single page.

The syntax for the standard APPLET tag is shown here. Bracketed items are
optional:

<APPLET

[CODEBASE = codebaseURL]

CODE = appletFile

[ALT = alternateText]

[NAME = appletInstanceName]

WIDTH = pixels HEIGHT = pixels

[ALIGN = alignment]

[VSPACE = pixels] [ HSPACE = pixels]

>

[<PARAM NAME = AttributeName1VALUE = AttributeValue>]

[<PARAM NAME = AttributeName2VALUE = AttributeValue>]

….

[HTML displayed in the absence of Java]

</APPLET>

CODEBASE:
OOPS Through JAVA 77

CODEBASE is an optional attribute that specifies the base URL of the applet code,
which is the directory that will be searched for the applet’s executable class file.

CODE:

CODE is a required attribute that gives the name of the file containing your
applet’s compiled .class file.

ALT:

The ALT tag is an optional attribute used to specify a short text message that
should be displayed if the browser understands the APPLET tag but can’t currently
run java applets.

NAME:

NAME is an optional attribute used to specify a name for the applet


instance. Applets must be name in order for other applets on the same page to find
them by which is defined by the AppletContext interface.
OOPS Through JAVA 78

Program:
import java.awt.*;
import java.applet.*;

public class BarChart extends Applet


{
int n = 0 ;
String label [] ;
int value [] ;
public void init ( )
{
try
{
n = Integer.parseInt ( getParameter
( "Columns" ) ) ;
label = new String[ n ] ;
value = new int [ n ] ;
label [ 0 ] = getParameter ( "Label
1" ) ;
label [ 1 ] = getParameter ( "Label
2" ) ;
label [ 2 ] = getParameter ( "Label
3" ) ;
label [ 3 ] = getParameter ( "Label
4" ) ;
value [ 0 ] = Integer.parseInt (
getParameter ( "C1" )) ;
value [ 1 ] = Integer.parseInt (
getParameter ( "C2" )) ;
value [ 2 ] = Integer.parseInt (
getParameter ( "C3" )) ;
value [ 3 ] = Integer.parseInt (
getParameter ( "C4" )) ;
}
catch ( NumberFormatException e)
{
System.out.println ( " Exception: "
+ e ) ;
}
}
public void paint ( Graphics g )
{
for ( int i = 0 ; i < n ; i++ )
{
g.setColor ( Color.red ) ;
g.drawString ( label[i], 20,i * 50 + 30
) ;
OOPS Through JAVA 79

g.fillRect (50 ,i*50+10,value [ i ] , 40


) ;
}
}
}

/*
<applet code = "BarChart.class" height = 300 width =
450 >
<param name = "Columns" value ="4">
<param name = "C1" value="110">
<param name = "C2" value="150">
<param name = "C3" value="100">
<param name = "C4" value="170">
<param name = "Label 1" value= "91">
<param name = "Label 3" value= "92">
<param name = "Label 3" value= "93">
<param name = "Label 4" value= "94">
</applet>
*/
OOPS Through JAVA 80

OUT PUT :-
OOPS Through JAVA 81

19. Program to draw Line, Rectangle, Round Rectangle, Oval


THEORY :-

WORKING WITH GRAPHICS :-

The AWT supports a rich assortment of graphics methods. All graphics are drawn
relative to a window. This be the main window of an Applet, a child window of an
Applet, or a stand-alone application window. The origin of each window is at the
top-left corner and is 0,0 coordinates are specifed in pixels. All out put to a
window GRAPHICS class and is obtained in two ways

It is passed to an applet when one of its various methods, such as paint() or


update(),is called.

It is returned by the get graphics () methods of component

The Graphics class defines a number of drawing functions. Each shape can be
drawn edge-only or filled. Objects are drawn and filled in the currently selected
graphics color, which is black by default. When a graphics object is drawn that
exceeds the dimensions of the window, Output is automatically clipped. Let’s take
a look at several of the drawing methods.

Drawing Lines :-

Lines are drawn by means of the drawline() method

Void drawLine(int startX,int startY, int endX, int endY)

drawLine() displays a line in the current drawing color that begins at startX,
StartY and ends at endX, endY.
OOPS Through JAVA 82

Drawing Rectangles :-

The drawrect() and fillRect() methods display an outlined and filled


rectangle, respectively .

Void drawRect(int top, int left, int width, int height)

Void fillRect(int top, int left, int width, int height)

The upper-left corner of the rectangle is at top left. The dimensions of the
Rectangle are specified by Width and Height.

To draw a rounded rectangle, use drawRoundRect() or fillRoundRect()

voiddrawRoundRect(int top, int left, int width, int height,int xDiam,int


yDiam)

voidfillRoundRect(int top,int left,int width,int height,int xDiam, int yDiam)

A rounded rectangle has rounded corners. The upper-left corner of the


Rectangle is at top-left. The dimensions of the rectangle are specified by width and
height. The diameter of the rounding arc along the X axis is specified by xDiam.
The diameter of the rounding arc along the Y axis specified by yDiam.

Drawing Ellipse and Circles :-


OOPS Through JAVA 83

To draw an Ellipse , use DrawOval(). To fill an ellipse, use fillOval(). These


methods are :

Void drawOval(int top,int left,int width,int height)

Void fillOval(int top,int left,int width, int height)

The Ellipse is drawn within a bounding rectangle whose upper-left corner is


specified by top,left and whose width and height are specified by width and height.
To draw a circle, specify a square as the bounding rectangle.

Drawing Arcs :-

Arcs can be drawn with drawArc() and FillArc()

Void drawArc(int top,int width, int height, int startAngle,int sweepAngle)

Void FillArc(int top,int left,int width,int height,int startAngle,int sweepAngle)

The arc is bounded by the rectangle whose upper-left corner is specified by


top,left and whose width and height are specifed by width and height. The arc is
drawn from StartAngle through the angular distance specified by SweepAngle.
Angles are specified in degrees. Zero degrees is on the horizontal, at the three
O’Clock position. The arc is drawn counterclockwise if SweepAngle is positive
and clockwise if SweepAngle is negative. Therefore, to draw an arc from twelve
O’clock, the start angle would be 90 and the SweepAngle 180.
OOPS Through JAVA 84

Program : -
import java.applet.*;
import java.awt.*;

public class DrawAll extends Applet


{
public void paint ( Graphics g )
{
g.drawLine ( 0 , 0 , 100 , 200 ) ;
g.drawRect ( 10 , 10 , 60 , 50 ) ;
g.fillRect ( 100 , 10 , 60 , 50 ) ;
g.drawRoundRect ( 190 , 10 , 60 , 50 , 15 , 15
) ;
g.fillRoundRect ( 70 , 80 , 140 , 100 , 30 ,
40 ) ;
g.drawOval ( 0 , 180 , 140 , 100 ) ;
g.fillOval ( 180 , 180 , 140 , 100 ) ;
}
}
/*
applet code = "DrawAll.class" width = 300 height = 400
>
<applet>
*/
OOPS Through JAVA 85

OUT PUT : -
OOPS Through JAVA 86

20.Program to implement Client Server


THEORY :-

DATAGRAMS: -

TCP includes many complicated algorithms for dealing with congestion


control on crowded networks, as well as pessimistic expectations about packet
loss. This leads to a somewhat inefficient way to transport data. Datagrams provide
an alternative.

Datagrams are bundles of information passed between machines. They are


somewhat like a hard throw from a well-trained but blindfolded catcher to the third
baseman. Once the datagram has been released to its intended target, there is no
assurance that it will arrive or even that someone will be there to catch it.
Likewise, when the datagram is received, there is no assurance that it hasn’t been
damaged in transit or that whoever sent it is still there to receive a response.

Java implements Datagrams on the top of the UDP protocol by using two
classes. The DatgramPacket object is the data container, while the DatagramSocket
is the mechanism used to send or receive the DatagramPackets.

DATAGRAM PACKET :-

DatagramPacket defines several constructors. The first constructor


specifies a buffer that will receive data, and the size of a packet. It is used for
receiving data over a DatagramSocket. The second form allows to specify an offset
into the buffer at which data will be stored. The third form specifies a target
address and port, which are used by a DatagramSocket to determine where the
data in the packet will be sent. The fourth form transmits packets beginning at he
specified offset into the data. Think of the two forms as building an “In Box”, and
OOPS Through JAVA 87

the second two forms as stuffing and addressing an envelope. The four
constructors are……

DatagramPacket(byte data[],int size)

DatagramPacket (byte data[],int offset,int size)

DatagramPacket (byte data[],int size,InetAddress ipAdress,int port)

DatagramPacket (byte data[],int offset,int size,InetAddress ipAdress,int


port)

There are several methods for accessing the internal state of a


DatagramPacket. They give complete access to the destination address and port
number of a packet, as well as the raw data and its length. Here are some of the
most commonly used :

InetAddress getAddressReturns the destination InetAddress, typically used for


sending.

Int getport() Returns the port number.

Byte[]getData() Returns the byte array of data contained in the datagram.


Mostly used to retrieve data from the datagram after it has been received.

Int getLength() Returns the length of the valid data contained in the byte array
that would be returned from the getData() method. This typically does not equal
the length of the whole byte array.
OOPS Through JAVA 88

PROGRAM :-
import java.net.*;
class Writeserver {
public static int serverPort = 998;
public Static Int clientPort = 999;
public Static int buffer_size = 1024;
public Static DatagramSocket ds;
public Static byte buffer[] = new byte[buffer_size];

public static void TheServer() throws Exception {


int pos=0;
while(true) {
int c = system.in.read();
switch( c ) {
case – 1 :
System.out.println(“Server Quits.”);
return;
case ‘\r’ :
break;
case ‘\n’;
ds.send(new
DatagramPacket(buffer,pos,InetAddress.getLocalHost(),
clientPort));
pos=0;
break;
default :
buffer[pos++] = (byte) c;
}
}
}
public static void TheClient() throws Exception {
while(true) {
datagramPacket p = new
DatagramPacket(buffer,buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(),
0,p.getLength()));
}
}
public static void main(String args[]) throws Exception
{
if(args.length ==1)
{
ds = new DatagramSocket(Server Port);
TheServer();
}
else
OOPS Through JAVA 89

{
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}
OOPS Through JAVA 90

OUT PUT :-
This sample program is restricted by the DatagramSocket
constructor to running between two ports on the local
machine. To use the program, run

Java WriteServer
in one window; this will be the client. Then run

Java WriteServer 1

This will be the server. Anything that is typed in the


server window will be sent to the client window after a new
line is received.

This example requires that your Computer be


connected to the Internet.

Potrebbero piacerti anche