Object Oriented Paradigm:: Compiled By: Er. R. K. Gupta
Object Oriented Paradigm:: Compiled By: Er. R. K. Gupta
Er. R. K. Gupta
E-Mail:[email protected]
Student Object
newAdmission( )
updateCourse( ) Methods
updateAddress()
Page 1 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
add( ), update( )
Employee
Designation, basic
pay, hra, da
Polymorphism:
Polymorphism means the ability to take more than one forms. For example consider the
operation of addition for two numbers operation will generate sum( 1+1=2 ) and for two
strings generate third string( “1” + ”1” = ”11” ). Figure given below describes that a single
function name can be used to handle different number and different types of arguments.
Shape
draw(Page
) 2 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Circle
Square
draw( radius )
draw(side)
Benefits of OOP:
OOP offers several benefits to both the programmer and the user. The main benefits are as
under:
1) Through inheritance we can eliminate redundant code and extend the use of existing
classes.
2) The principal of data hiding helps the programmer to build secure programs.
3) It is possible to have multiple objects to coexist without any interference.
4) It is easy to partition the work in a project based on objects.
5) Object oriented system can be easily upgraded from small to large systems.
6) Software complexity can be easily managed.
Applications of OOP:
The most popular application of object oriented programming, up to now, has been in the
area of user interface design such as windows. The promising areas for application of OOP
includes
1) Real Time Systems
2) Simulation and modeling.
3) Object oriented databases.
4) AI and expert systems.
5) Decision support and office automation systems.
6) CIM/ CAD system.
Java History:
Java is a general purpose, object oriented programming language developed by Sun
Microsystems of USA in 1991. Originally called Oak , java was designed for the
development of software for consumer electronic devices like TVs, toasters. The java team
Page 3 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
4. Distributed:
Java is designed as a distributed language for creating applications on networks. It has
the ability to share both data and program. Java applications can access remote objects
on internet.
Page 4 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 5 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 6 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Comments in Java:
Java permits both single line comments and multi line comments available in C++. The
single line comment begins with // and end at the end of line. Multiline comment starting
with a /* and ending with a /*. For Example a program with two classes and different type of
comment is shown below.
/* Program with two classes
Author: Aryabhatta Group*/
class A
{ void show( )
{ System.out.println(“Class A”);}
}
class B
{ public static void main(String args[ ])
{ System.out.println(“Hello”);} // display Hello
}
Java Program Structure:
A java program may contain one or more sections as shown in figure
below
Documentation Section Suggested
Optional
Interface statements
Page 7 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
1. Document Section:
Document section includes comment lines giving the name of the program, the author and
other details.
2. Package Section:
First statement allowed in a java file is a package statement which informs the compiler
that the class defined here belongs to this package. Package statement is optional.
3. Import Statements:
This is similar to the #include statement in C. Using import statements we can use classes
that are part of other packages. This is also an optional section.
4. Interface Statement:
An interface is like a class but include a group of method declarations. This is also an
optional section.
5. Class Definitions:
A java program may contain multiple class definitions. Classes are primary and essential
elements of a java program.
6. Main Method Class:
Since every program execution starts from main method so this class is the essential part
of a java program.
Java Virtual Machine:
Java compiler produces an intermediate code known as bytecode for a machine that does not
exist. This machine is called the Java Virtual Machine and it exists only inside the computer
memory.
Java interpreter converts this bytecode into machine code. So java interpreter act as an
intermediary between the virtual machine and the real machine.
Page 8 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Java Tokens:
Smallest individual units in a program are known as tokens. The compiler recognizes them
for building up expressions and statements.
Java language includes five types of tokens. They are:
a) Reserve Keywords
b) Identifiers
c) Literals
d) Operators
e) Separators
Keywords:
The keywords are also called reserved words. Keywords has specific meaning in java, we
cannot use them as names for variables, methods, classes, interfaces and so on. Java
language has 50 keywords. For example
Identifiers:
Identifiers are used for naming variables, methods, classes, objects, labels, packages and
interfaces in a program. Java identifiers must enforce following rules
a) They can have alphabets (a to z), digits (0 to 9), and underscore.
sal1 Valid
sal# Invalid (# is not a valid character)
b) They must not begin with a digit.
sal1 Valid
_sal1 Valid
Page 9 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 10 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Escape Purpose
Sequence
\b Backspace
\f Form feed
\n New line
\t Tab
\\ Backslash
\” Double quote
Separators or Punctuators:
These are symbols used for grouping and separating code. They are also known as separators
or Delimiters. Separators are given below
Parentheses ()
Braces { }
Brackets [ ]
Semicolon (;)
Comma (,)
Period (.) etc.
Variables:
A variable is an identifier that denotes a storage location used to store a data value. A
variable may take different values during the execution of program. Variable must be
declared befor use.
Data Types:
Page 11 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Type Size
Page 12 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Float 4 bytes
Double 8 bytes
Character Type:
Character data type can hold only a single alphabet (A-Z) or digit (0-9) or special symbol.
The character data type assumes a size of two bytes. It has been designed to hold 16 bit
Unicode.
Boolean Type:
There are only two values that a Boolean type can take: true or false. All comparison
operators return Boolean type values. The words true or false cannot be used as identifiers.
Mathematical Functions:
Java supports mathematical functions through Math class defined in the java.lang package.
The function should be used as follows:
Math.function_name()
For Example
Class MF1
{ public static void main( String args[ ] )
{ double x;
x=Math.max(22 , 33);
System.out.println(“ Maximum value= “ + x);
x=Math.pow(2,4);
System.out.println(“Power=”+x);
}
}
o/p is
Maximum value= 33
Power= 16
Page 13 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Java operators:
An operator is a symbol that tells the compiler to perform a certain mathematical or logical
manipulators. Java supports a rich set of operators. Java operators can be classified into following
categories:
1. Arithmetic operators :
Arithmetic operators are used for arithmetic operations like Addition, Subtraction,
Multiplication, and Division & Modulus. These can operate on any built in numeric type.
Arithmetic operators are binary operators because they required two operands. Following are
the list of Arithmetic Operators.
Operator Meaning
+ Addition
* Multiplication
/ Division
% Modulus division
class AO1
{
public static void main( String args[ ] )
{
int a=14, b=4;
System.out.println( a - b); //10
System.out.println( a * b); //56
System.out.println( a / b); //3(decimal truncated)
System.out.println( a % b); //2
}
}
Page 14 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Type Conversions:
When two operands of different types are encountered in the same expression java
automatically converts lower type variable into higher type variable but opposite not
possible.
float
long
int
short
Operator Meaning
== Equal to
!= Not equal to
class RO1
{ public static void main ( String args [ ] )
{ int a=5;
boolean result;
result=a > 2; //result=true
System.out.println( result);
if (a> 2)
Page 16 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Operator Meaning
&& AND
|| OR
! NOT
class LO1
{ public static void main ( String args [ ] )
{ int a=5;
boolean result;
result=a > 2 && a<5; //result=false
System.out.println( result);
if (a> 2 && a<5)
System.out.println(“ True”);
else
System.out.println (“False”);
}
}
Truth Table of Logical AND and Logical OR Operators
A B A&&B A||B
A !A
True False
False True
5. Bitwise Operators:
These operators are mainly used for the operation of Binary bits i.e. 0 and 1. So these are
mainly used for low level programming. Bitwise operations are the testing, setting or shifting
of the actual bit in a byte. These operators should not be of float or double type due to binary
version. There are mainly six Bitwise Operators.
| Bitwise OR
^ Bitwise XOR
~ One’s Complement
class BO1
{ public static void main ( String args [ ] )
Page 18 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
a+=1 a=a+1
a- =1 a=a-1
a*=5 a= a* 5
a\=5 a=a/5
a%=b a=a%b
a>>=2 a=a>>2
Page 19 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
a<<=2 a=a<<2
a&=2 a=a&2
a|=2 a=a|2
a^=2 a=a^2
class AO2
{ public static void main ( String args [ ] )
{ int a=11;
a &= 5 \
System.out.println ( a);
}
}
O/P= 1
7. Conditional operator or Ternary operator:
This operator is compressed version of if-else statement. This is called ternary operator
because it requires three operands. The syntax of the statement is
c= ( a > b) ? a: b;
This above statement returns the greatest number as a value of c variable i.e. if a is greater than b
then the value of a is assigned to c otherwise the value of b is assigned to c.
class TO1
{ public static void main(String args[ ])
{ int a=11,b=8,c;
c=( a > b) ? a : b;
System.out.println( c);
}
}
Precedence of operators:
In an expression operators with higher precedence are evaluated before lower precedence
operator. Operators having equal precedence are evaluated on the basis of associatively.
Page 20 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
+- Left to right
|| Left to right
= Right to left
Lower Shorthand assignment operator Right to left
Page 21 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
1. Branching:
To override the sequential flow of execution branching is must. Branching must be done on
the basis of some condition. Java supports following control or decision making statements
1. If statement
2. switch statement
3. conditional operator statement
If statement:
“If statement” is used to control the flow of execution of statements. It is a two way decision
statement and used in conjunction with an expression. If statement is of further four types.
a) Simple If Statement:
Simple if statement is used for one way branching. The syntax of if statement is like
If (condition)
{true statement block;}
other statements;
In this type of statement condition will be checked. If condition is true then true statement
block will be executed and after that other statements block will be executed. If the condition
is false only other statements bock will be executed.
b) If-else Statement:
This statement is used for two way branching. The syntax of if statement is like:
if (condition)
{True Statement- block;}
Expressi else
on False {False Statement- block;}
? Statement – n;
True
Page 22 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 23 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 24 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
2. Looping:
Loops are used to repeat the some portion of a program either a specified number of times or
until a particular condition is being satisfied. Mainly loops are of two types. One is Entry
Controlled Loop and another is Exit Controlled Loop.
a) Entry Control Loop: In this type of loop firstly condition is checked if it is true then
body of the loop is executed otherwise body of the loop is not executed.
Page 25 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 26 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
class For2
{ public static void main( String args[] )
{ for( ; ; )
System.out.println(“Hello”);
}
}
Output: Hello infinite times.
2. While loop:
While is an entry controlled loop statement. The test condition is evaluated and if the
condition is true then the body of the loop is executed otherwise loop terminated. The
general form of while loop is as under:
initialization;
while( test condition)
{ Body of the loop; }
class While1
{ public static void main( String args[ ] )
{ int sum =0;
int n=1;
while (n<=5)
{ sum= sum+n ;
n++;
}
System.out.println (sum);
}
}
Output: 15
Page 27 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
initializations;
do
{ body of the loop; }
while ( test condition);}
class Do1
{ public static void main( String args[] )
{ int i=11;
do
{ System.out.println(”Hello”);
i++;
} while( i<=10);
}
}
Output: Hello
3. Jumping:
1. Break statement:
Break statement is used for an early exit from nearest loop .It is usually used with for loop,
do-while, while loops and in the switch statement.
class Break1
{ public static void main( String args [ ] )
{ int i=1;
for( i=1 ; i<=5 ; i++)
{ if(i==2)
Page 28 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
class Break2
{ public static void main( String args [ ] )
{ int i,j;
loop1: for( i=1 ; i<=5 ; i++)
{ for (j=1 ;j<=5;j++)
{ if( j==3)
break;
System.out.print(“*”);
}
System.out.println();
}
}
}
Output:
**
**
**
**
**
class Break3
{ public static void main( String args [ ] )
Page 29 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 30 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 31 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 32 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 33 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 34 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 35 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
class NestingDemo
{ public static void main( String args[])
{ Nesting nest=new Nesting(50, 40);
nest.dispaly( );
}
}
Page 37 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Inheritance:
Inheritance is the process of creating new classes called derived class or sub class from an
old class called base class or super class. Inheritance allows subclass to inherit all the
variables and method of their super class. Inheritance may take different forms
Single inheritance( only one super class, one subclass )
Multiple inheritance( several super classes)
Hierarchical inheritance( one super class, many subclasses )
Multilevel inheritance (subclass from a subclass)
A A
B B C D
B C
C
(Multilevel inheritance) ( Multiple inheritance)
In java multiple inheritances is not possible through classes but it is possible through
interfaces.
For example
class Student
{ int rno;
String name, course;
int fee;
Student ( ) { rno=fee=0; name=course=” ”;}
Student( int r, String n, String c, int f) {rno=r; name=n; course=c; fee=f;}
void dispData()
Page 38 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 39 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 40 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 41 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 42 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Multidimensional Array:
Java treats multidimensional array as “arrays of arrays”. It is possible to declare a two-
dimensional array as follows
int x[][]=new int [3][4];
in java it is possible that each row has different length i.e. variable size array as shown below
int x[][]=new int [3][];
x[0]= new int [2];
x[1]= new int[4];
x[2]= new int[3];
class MulTable
{ public static void main( String args[])
{ int p[][]=new int[10][10];
System.out.println(“Multiplication Table”);
int i,j;
for( i=0; i<10; i++)
{ for(j=0; j<10; j++)
{ p[i][j]=(i+2)*(j+1);
System.out.print(“ “+ p[i][j]);
}
System.out.println(“ “);
}
}
}
Strings:
Strings represent a sequence of characters. In java string is an object of String class. Java
strings as compared to C strings are more reliable and predictable because C lacks bound
checking. A java array is not a character array and is not NULL terminated. Strings may be
decared and created as follows:
String firstName;
Page 43 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Interfaces:
An interface is basically a kind of class but with some major differences as under
1. In an interface by default all methods are abstract and public.
2. In an interface by default all fields are public and final.
Like classes, interfaces can also be extended. This can be obtained using the keyword
extends as shown below:
interface ItemConstants
{
int code=1001;
String name=”Fan”;
}
interface Item extends ItemConstants
{
void display()
}
Page 44 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
1 Data members of a class can be Data members of interface are always declared
constant or variables. as constant.
4. It can use various access specifiers Interfaces can only use public access specifier.
like public, private or protected.
interface Shape
{ double pie=3.14;
double area( );
}
class Rectangle implements Shape
{ double dim1,dim2;
Rectangle() { dim1=dim2=0;}
Rectangle(double d1, double d2) { dim1=d1;dim2=d2;}
public double area( ) { return dim1*dim2);}
}
class Circle implements Shape
{ double radius;
Circle ( ) {radius=0 ;}
Circle (double r) {radius=r ;}
double area( ) { return pie*radius*radius;}
Page 45 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 46 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Example:
C:\java\ptu>
package ptu;
class Hello
{ public static void main ( String args[])
{ System.out.println(“ Hello”);}
}
Page 47 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Applet:
Applets are small java programs that are used in internet computing. They can be transported
over the internet from one computer to another and run using the Applet Viewer or any web
browser that supports java. An applet can perform arithmetic operation, display graphics,
play sounds, create animation and play interactive games. Applets are two types
1. Local Applets:
An applet developed locally and stored in a local system is known as local applet. To
access local applet web page does not require internet connection.
2. Remote Applet:
A remote applet is developed by someone else and stored on a remote computer
connected to internet. To access remote applet web page requires internet connection.
The difference between Applets and application programs is as under:
1. Applets do not use the main () method for initiating the execution of the code.
2. Applets cannot be run independently. They must be embedded in web page using
<applet> tag.
3. Applets cannot read or write to the files in the local computer.
4. Applets cannot communicate with other servers on the network.
5. Applets cannot run any program from the local computer.
6. Applets are restricted from using libraries from other languages such as C or C++.
Steps involved in developing and testing an applet are:
1. Building an applet code (.java file)
2. Creating an executable applet( .class file)
3. Embed applet in HTML file using applet tag
4. Testing the applet code
Building applet code:
import java.awt.*;
import java.applet.*;
public class HelloJava extends Applet
{ public void paint(Graphics g)
{ g.drawString(“Hello Java”,10,100);}
}
Page 48 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 49 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 50 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 51 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 52 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
fillRoundRect(int x, int y, int w, int Draws a filled rectangle with rounded corner.
h, int cw,int ch) x,y represent the coordinates of top left corner
w represent the width of rectangle
h represent the height of rectangle.
cw represents the width of the corner
ch represents the height of the corner
Page 53 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
imaginary rectangle.
w represent the width of imaginary rectangle
h represent the height of imaginary rectangle.
drawPolygon(int x[], int y[], int n ) Draws a hollow polygon with n lines. It takes three
arguments.
x[] an array of integers containing x coordinates.
y[] an array of integers containing y coordinates.
n represents the total number of points.
fillPolygon(int x[], int y[], int n ) Draws a filled polygon with n lines. It takes three
arguments.
Page 54 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
import java.awt.*;
import java.applet.*;
public class GraphicShapes extends Applet
{ public void paint( Graphics g)
{ g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
g.fillRoundRect(10,100,80,50,10,10);
g.drwOval(60,10,200,120);
g.setColor(Color.green);
g.fillOval(110,20,100,100);
g.fillArc(160,100,80,40,180,180);
}
}
<HTML>
<APPLET CODE=”GraphicShapes.class” width=300 height=300>
</APPLET></HTML>
Page 55 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
AWT Package:
AWT (Abstract Window Toolkit) contains classes and methods that allow you to create and
manage windows. The main purpose of the AWT is to support applet windows; it can also be
used to create stand alone windows that run in a GUI (Graphical User Environment). AWT
classes are contained java.awt package. It is one of Java’s largest packages.Some of the
important AWT classes are as under
Window Fundamentals:
The two most common windows are
1. Derived from Panel which is used by applets
2. Derived fro Frame which creates a standard window.
Page 57 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Container
Window Panel
Frame
Component Class:
At the top of the AWT hierarchy is the component class. Component is an abstract class. All
user interface elements that are displayed on the screen and that interact with the user are
subclass of component. It defines over a hundred public methods that are responsible for
managing events such as mouse and keyboard input, positioning and resizing the window
and repainting.
Container:
The container class is subclass of Component. It has additional methods that allow other
Component objects to be nested within it. A container is responsible for laying out
components that it contains.
Panel:
The Panel class is a concrete subclass of container. It does not add any new methods; it
simply implements Container. Panel is the superclass for Applet. When screen output is
directed to an applet, it is drawn on the surface of a Panel object. Panel is a window that does
not contain a title bar.
Window:
The Window class creates a top level window. A top level window is not contained within
any other object. Generally you would not create window objects directly. Instead you will
use subclass of window called Frame.
Frame:
Page 58 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Methods Description
void setAlignment( int how) Set the alignment of the string within the label.
/*
<applet code="LabelDemo.class" width=300 height=200>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class LabelDemo extends Applet
{ public void init()
Page 59 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Methods Description
/*
<applet code="ButtonDemo.class" width=250 height=150>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class ButtonDemo extends Applet
{ String msg = "You pressed yes";
Button yes, no, maybe;
public void init()
{ yes = new Button("Yes");
Page 60 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Methods Description
/*
Page 61 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Choice Control:
Choice class is used to create a popup list of items from which the user may choose. When
the user clicks on it , the whole list of choices pop up and a new selection can be made.
Choice only defines the default constructor which creates an empty list. To add an item call
add () method.
Methods Description
Page 62 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
void select(int index) Set currently selected item using zero based integer index.
void select(String name) Set currently selected item using string that will match a name
in list.
String getItem(int idx) Return the name of the item whose index is given by idx
/*
<applet code="ChoiceDemo.class" width=300 height=180>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class ChoiceDemo extends Applet
{ Choice os, browser;
String msg = "";
public void init()
{ os = new Choice();
browser = new Choice();
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
browser.add("Internet Explorer");
browser.add("Firefox");
Page 63 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Methods Description
Page 64 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
void select(int index) Set currently selected item using zero based integer index.
void select(String name) Set currently selected item using string that will match a name
in list.
String getItem(int idx) Return the name of the item whose index is given by idx
/*
<applet code="ListDemo.class" width=300 height=180>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class ListDemo extends Applet
{ List os, browser;
String msg = "";
public void init()
{ os = new List(4, true);
browser = new List(4, false);
os.add("Windows XP");
os.add("Windows Vista");
os.add("Solaris");
os.add("Mac OS");
browser.add("Internet Explorer");
browser.add("Firefox");
browser.add("Opera");
browser.select(1);
Page 65 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Method Description
Page 66 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
/*
<applet code="SBDemo.class" width=300 height=200>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class SBDemo extends Applet
{ String msg = "";
Scrollbar vertSB, horzSB;
public void init()
{ int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
vertSB = new Scrollbar(Scrollbar.VERTICAL,0, 1, 0, height);
horzSB = new Scrollbar(Scrollbar.HORIZONTAL,0, 1, 0, width);
add(vertSB);
add(horzSB);
}
public void paint(Graphics g)
{ msg = "Vertical: " + vertSB.getValue();
msg += ", Horizontal: " + horzSB.getValue();
g.drawString(msg, 6, 160);
g.drawString("*", horzSB.getValue(),vertSB.getValue());
}
}
TextField:
Page 67 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Method Description
String getText() Return the string currently contained in the text field
boolean isEditable() Returns true if the text may be changed and false if not.
void setEchoChar(char ch) This method specifies a single character that the text
field will display when characters are entered.
/*
<applet code="TextFieldDemo.class" width=380 height=150>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class TextFieldDemo extends Applet
{ TextField name, pass;
public void init()
{ Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
Page 68 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Method Description
String getText() Return the string currently contained in the text field
Page 69 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
boolean isEditable() Returns true if the text may be changed and false if not.
void setEchoChar(char ch) This method specifies a single character that the text
field will display when characters are entered.
void append(String str) Appends the string specified by str to the end of the
current text.
void insert(String str, int idx) Inserts the string specified by str at the specified index
/*
<applet code="TextAreaDemo.class" width=300 height=250>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class TextAreaDemo extends Applet
{ public void init()
{ String val ="Java SE 6 is the latest version of the most\n" +
"widely-used computer language for Internet programming.";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}
Layout Managers:
Each container object has a layout manager associated with it. A layout manager is an
instance of any class that implements the LayoutManager interface. The Layout manager is
set by the setLayout() method. Java has following predefined LayoutManager classes
FlowLayout
BorderLayout
Page 70 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 74 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 75 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
/*
<applet code="ButtonDemo.class" width=250 height=150>
</applet>*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class ButtonDemo extends Applet implements ActionListener
{ String msg = "";
Button yes, no, maybe;
public void init()
{ yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{ String str = ae.getActionCommand();
if(str.equals("Yes"))
{msg = "You pressed Yes.";}
else
if(str.equals("No"))
{msg = "You pressed No.";}
else
Page 77 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
AdjustmentListener Interface
This interface defines the adjustmentValueChanged( ) method that is invoked when an
adjustment event occurs. Its general form is shown here:
void adjustmentValueChanged(AdjustmentEvent ae)
The MouseListener Interface
This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( )
method is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and
mouseReleased( ) methods are invoked when the mouse is pressed and released, respectively.
The general forms of these methods are shown here:
Page 78 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 79 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 80 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 81 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Errors:
An error is an unwanted condition which may produce an incorrect output or terminate the execution of
program. Errors are two types
1. Compile Time Errors:
All errors which occurs during compilation of program are called compile time errors. Whenever
compiler displays an error , it will not create the .class file. Most common compile time errors are
a. Missing semicolon
b. Missing double quotes in strings
c. Missing or mismatch of brackets in classes and methods.
d. Use of undeclared variables
e. Bad refrerence to objects.
For example
class Error1
{ public static void main( String args[ ] )
{
System.out.println(“Hello”) // compile time error (; expected)
}
}
Run Time Errors:
Sometimes a program may compile successfully creating the .class file but may generate errors
during run time. These errors are called run time errors. Most common run time errors are
a. Dividing an integer by zero.
b. Accessing an element that is out of bounds of an array.
c. Trying to store value into an array of incomaptible class or type.
d. Attempting to use a negative size for an array.
e. Converting invlaid string to a number.
For Example
class Error2
{ public static void main( String args[] )
{
int a=10,b=5,c=5;
int x = a / (b-c); // run time error (Division by zero)
System.out.println(“ x= “ + x);
}
}
Page 82 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 83 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 84 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 85 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Multitasking Multithreading
Processor switch between different programs Processor switch between different parts or threads
of a program.
Creating Threads:
A new thread can be created in two ways
1. Define a class that extends Thread class and override its run( ) method with the required code.
2. Define a class that implements Runnable interface and overide its run( ) method with the required
code. Runnable interface has only one method run( )
Stopping a thread:
stop ( ) method is used to stop a thread from running . By calling this method thread moves to the dead
state. A thread will also move to the dead state automatically when it reaches to end of its method. For
example
aThread.stop ( );
Blocking a Thread:
A thread can be suspended or blocked using following methods
sleep ( ) // Blocked for a specified time
suspend( ) // Blocked until further orders i.e. by calling resume ( ) method
wait ( ) // Blocked until certain condition occurs i.e. by calling notify () method
Page 86 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
Page 87 of 88
Compiled By:
Er. R. K. Gupta
E-Mail:[email protected]
class ThreadMethods
{ A threadA =new A( );
B threadB =new B( );
C threadC =new C( );
threadA.start( );
threadB.start( );
threadC.start( );
}
}
Page 88 of 88