Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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 ;
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:
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
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:
Integer.parseInt :
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 ) ;
}
}
Output:
OOPS Through JAVA 13
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.
int length ( ) ;
E.g.
System.out.println ( s . length ( ) ) ;
String Concatenation:
Program:
class SortString
OOPS Through JAVA 16
Output:
OOPS Through JAVA 17
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.
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
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
Output:
OOPS Through JAVA 25
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
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
Description:
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.
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.
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 :
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 :
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 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.
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
}
}
OOPS Through JAVA 38
Output:
OOPS Through JAVA 39
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:
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.
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
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;
// body of method
// body of method
//……
// 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 ( ).
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
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.
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
drawString :
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.
Program:
import java.awt.*;
import java.applet.*;
/*
<applet code = Hello.class width = 400 height = 200>
<param name = "String" value = "INDIA">
</applet>
*/
OOPS Through JAVA 51
Output:
OOPS Through JAVA 52
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.
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
Grid Layout :-
GridLayout()
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 :-
These values passed in top,left,bottom and right specify the amount of space
between the container and its enclosing window.
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.*;
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 ) ;
}
}
/*
<applet code = "CalculatorApplet.class" height = 500
width = 400 >
</applet>
*/
OOPS Through JAVA 61
Output:
OOPS Through JAVA 62
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.
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
Using MultiThreading :
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
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.
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.
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 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
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]
[ALIGN = alignment]
>
….
</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:
Program:
import java.awt.*;
import java.applet.*;
/*
<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
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
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 :-
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 upper-left corner of the rectangle is at top left. The dimensions of the
Rectangle are specified by Width and Height.
Drawing Arcs :-
Program : -
import java.applet.*;
import java.awt.*;
OUT PUT : -
OOPS Through JAVA 86
DATAGRAMS: -
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 :-
the second two forms as stuffing and addressing an envelope. The four
constructors are……
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];
{
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