0% found this document useful (0 votes)
14 views249 pages

3.2 OOP in JAVA

The document outlines a Java programming course, detailing its evaluation scheme, objectives, and expected outcomes for students. It introduces Java as a programming language, its features, and compares it with other languages like C++. Additionally, it covers Java's data types, constructs, and development tools, along with examples of simple Java programs and applets.

Uploaded by

kmokshada
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views249 pages

3.2 OOP in JAVA

The document outlines a Java programming course, detailing its evaluation scheme, objectives, and expected outcomes for students. It introduces Java as a programming language, its features, and compares it with other languages like C++. Additionally, it covers Java's data types, constructs, and development tools, along with examples of simple Java programs and applets.

Uploaded by

kmokshada
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 249

PROGRAMMING IN JAVA

COURSE CODE: BTITOE504C


Evaluation Scheme
 Mid Sem Examination (MSE) : 20
 Continuous Assessment (CA) : 20
 End Semester Examination (ESE)

: 60
---------------------------------------------------------
-
Total
: 100
Course Objectives
1. Understand fundamentals of
programming such as variables, conditional
and iterative execution, methods, etc.
2. Understand fundamentals of object-
oriented programming in Java, including
defining classes, invoking methods, using
class libraries, etc.
3. Be able to use the Java SDK environment
to create, debug and run simple Java
programs.
Course Outcomes
At the end of this course Students will be able to:
1. Understand fundamentals and constructs of basic
Java Programming.
2. Understand and implement constructs of Object
Oriented Programming using Java
3. Understand and implement Multithreading and
Exception Handling in Java.
4. Understand and implement Java packages and
graphical constructs.
5. Understand and implement file handling and I/O
event handling.
Java - An Introduction
 Java - The new programming language
from Sun Microsystems
 Java -Allows anyone to publish a web
page with Java code in it
 Java - CPU Independent language
 Created for consumer electronics
 Java - James , Arthur Van , and others
 Oak -The predecessor of Java
 Java is “C++ -- ++ “
Java is...
 Simple and Powerful
 Object Oriented
 Portable
 Architecture Neutral
 Distributed
 Multi-threaded
 Robust, Secure/Safe
 Interpreted
 High Performance
 Dynamic programming
language/platform.
Java as Object Oriented
 “Objects all the way down”
 Simple and Familiar: “C++ Lite”
 No Pointers!
 Garbage Collector
 Dynamic Binding
 Single Inheritance with “Interfaces”
Java as Portable
 Unlike other language compilers, Java
complier generates code (byte codes) for
Universal Machine.
 Java Virtual Machine (JVM): Interprets
bytecodes at runtime
 Architecture Neutral
 Higher Level Portable Features: AWT,
Unicode
Total Platform Independence

JAVA (translator)
COMPILER

JAVA BYTE CODE


(same for all platforms)

JAVA INTERPRETER
(one for each different system)

Windows 95 Macintosh Solaris Windows NT


Architecture Neutral

 Java Compiler -Java source code to


bytecode
 Bytecode - an intermediate form, closer
to machine representation
 A virtual machine on any target platform
interprets the bytecode
 Porting the java system to any new
platform involves writing an interpreter
that supports the Java Virtual Machine
 The interpreter will figure out what the
equivalent machine dependent code to
run
Object Oriented Languages-a
Comparison
Objective
Feature C++ C Ada Java

Encapsulation Yes Yes Yes Yes


Inheritance Yes Yes No Yes
Multiple Inherit. Yes Yes No No
Polymorphism Yes Yes Yes Yes
Binding (Early/Late) Both Both Early Late
Concurrency Poor Poor Difficult Yes
Garbage Collection No Yes No Yes
Genericity Yes No Yes No
Class Libraries Yes Yes Limited Yes
Comparing Java with C++ ?
 No Global Variables
 No Goto statements
 No Pointers
 No Unsafe Structures
 No Multiple Inheritance
 No Operator Overloading
 No Fragile Data Types
Basic Data Types
 Types
boolean either true of false
char 16 bit Unicode 1.1
byte 8-bit integer (signed)
short 16-bit integer (signed)
int 32-bit integer (signed)
long 64-bit integer (singed)
float 32-bit floating point
double 64-bit floating point
 String (class for manipulating strings)
 Java uses Unicode to represent characters
internally
Two Types of Java
Applications
 Different ways to write/run a Java codes
are:
Application- A stand-alone program that can
be invoked from command line . A program
that has a “main” method
Applet- A program embedded in a web page ,
to be run when the page is browsed . A
program that contains no “main” method

 Application -Java interpreter


 Applets- Java enabled web browser
(Linked to HTML via <APPLET> tag. in
html file)
Life cycle of Java code
Runtime
Compile-time Environment Class
Environment Java
Loader
Class
Bytecode Libraries
Java Verifier
Source
(.java)

Just in
Java
Time
Interpreter Java
Java Compiler
Java Bytecodes Virtual
Compiler move locally machine
or through
network Runtime System

Java
Bytecod Operating System
e
(.class )
Hardware
Java Development Kit
 javac - The Java Compiler
 java - The Java Interpreter
 jdb- The Java Debugger
 appletviewer -Tool to run the applets

 javap - to print the Java bytecodes


 javaprof - Java profiler
 javadoc - documentation generator
 javah - creates C header files
Hello world!!!
// HelloWorld.java: Hello world program
class HelloWorld
{
public static void main(String args[])
{
System.out.println(“Hello World”);
}
}
Program Processing
 Compilation
# javac hello.java
results in HelloWorld.class
 Execution
# java HelloWorld
Hello World
#
Simple Java Applet

// HelloWorld.java: A sample applet


import java.applet.Applet;
public class HelloWorld extends
Applet {
public void paint(Graphics g)
{
g.drawString(“Hello World !”,25,25);
}
}
Calling an Applet

<HTML>
<TITLE> Hello Worlds Applet </TITLE>
<APPLET code=“HelloWorld.class” width=500
height=500>
</APPLET>
</HTML>
 Example
Example.java
Execution of Applets
2 4 5
1 3
APPLET hello.class Create Accessing The browser
Development Applet from creates
AT C-DAC’S a new
“hello.java” WEB tag in CRAY Corp.
HTML (USA) window and
AT SERVER
document a new thread
CDAC-India and
then runs the
code

Hello Java
<app=
“Hello”> The Internet
Hello
Rich Object Environment
 Core Classes
language
Utilities
Input / Output
Low-Level Networking
Abstract Graphical User Interface
 Internet Classes
TCP/IP Networking
WWW and HTML
Distributed Programs
Java versions
 J2SE
 J2EE
 J2ME
J2SE
 JDK 1.1.4 (Sparkler) September 12, 1997
 JDK 1.1.5 (Pumpkin) December 3, 1997
 JDK 1.1.6 (Abigail) April 24, 1998
 JDK 1.1.7 (Brutus) September 28, 1998
 JDK 1.1.8 (Chelsea) April 8, 1999
 J2SE 1.2 (Playground) December 4, 1998
 J2SE 1.2.1 (none) March 30, 1999
 J2SE 1.2.2 (Cricket) July 8, 1999
 J2SE 1.3 (Kestrel) May 8, 2000
 J2SE 1.3.1 (Ladybird) May 17, 2001
 J2SE 1.4.0 (Merlin) February 13, 2002
 J2SE 1.4.1 (Hopper) September 16, 2002
 J2SE 1.4.2 (Mantis) June 26, 2003
 J2SE 5.0 (1.5.0) (Tiger) September 29, 2004
 Java SE 6 (1.6.0) (Mustang) December 11, 2006
 Java SE 7 (1.7.0) (Dolphin) anticipated for 2008
Main Packages

 java.lang
 java.util
 java.io
 java.awt
 java.awt.image
 java.applet
 java.net
Java Constructs
 What is Java, basic constructs, including
 classes and objects
 constructors,
 this and super keywords,
 inheritance,
 abstract classes, interfaces,
 inner classes,
 exceptions.
Data Types
 Eight basic types
 4 integers (byte, short, int, short) [ int a; ]
 2 floating point (float, double) [double a;]
 1 character (char) [ char a; ]
 1 boolean (boolean) [ boolean a; ]
 Everything else is an object
 String s;
 Example
Example2.java
Java program structure
Documentation Section

Package Statements

Import Statements

Interface Statements

Class Definitions

main method class

main method definition

}
Editors used
 DOS editor
 Jcreator
 Eclipse
 Netbeans
 Textpad
 GNU editor
 Emacs
Java tokens
 Identifiers
 Keywords
 Literals
 Operators
 Separators
Keywords
Abstract boolean break byte byvalue*

Case cast* catch char class

Const continue default do double

Else extends false final finally

Float for future* generic* goto*

if implements import inner* instanceof

Int interface long native new

Null operator* outer* package private

protected public rest* return short

static super switch synchronized this

threadsafe* throw throws transient true

try var* void volatile while


Identifiers
 They can have only alphabets, digits,
underscore ( _ ) and dollar sign ( $ )
characters.
 They must not begin with digit. Digit can
be placed anywhere except starting
position.
 Uppercase and lowercase letters are
different.
 They can be of any length.
 They must not be the keywords.
 They can have any special symbol in it.
Hungarian notations
 Name of all public methods and instance
variables start with a lowercase letter.
Examples:
calculate
string
display
Hungarian notations
 When the method name contains more
than one word, the second and
subsequent words are marked with
leading uppercase characters.
Examples:
findAverage
isLeapYear
grandTotal
Hungarian notations
 All private and local variables use only
lowercase letters combined with
underscores.
Example:
birth_day
total
avg_marks
Hungarian notations
 All class and interface names starts with
an uppercase letter and each subsequent
letter of the word with uppercase letter.
Examples:
HelloJava
FirstClass
Example1
Hungarian notations
 Variables that represent constant values
use all uppercase letters and underscores
between words.
Examples:
MAX_MARKS
VALUE_OF_PI
GRADE
These are like symbolic constants in
C/C++.
Literals
 Integer literals
 Real literals
 Character literals
 String literals
 Boolean literals
Constants
Escape sequences

Escape Meaning

\n New Line

\t Tab

\b Backspace

\r Carriage Return

\\ Back slash

\’ Single quote

\” Double quote
Separators

Separator Name

() Parenthesis

{} Curly Braces

[] Square brackets

; Semicolon

, Comma

. Dot/Period
Data types
Integer data type

Typ
Size Minimum Value Maximum Value
e

byte One byte -128 127

shor
Two bytes -32,768 32,767
t

Four
int -2,147,483,648 2,147,483,647
bytes

-
Real data types

Type Size Minimum Maximum

Value Value

float Four 3.4e–38 3.4e+38

bytes

doubl Eight 1.7e–308 1.7e+308

e bytes
Default values
Type of Default

variable value

boolean False

byte zero : 0

short zero : 0

int zero : 0

long zero : 0L

float 0.0f

double 0.0d

char null character


Scope of the variables
 Local
 Instance
Comments
 Single line
//
 Multi line
/* */
 Documentation comments
/** */
Operators
 Arithmetic Operators (+,-,*,/,%)
 Assignment Operators (+=,-=,*=,/=,%=)
 Increment / Decrement Operators (++,--)
 Relational Operators (==,!=,>,<,>=,<=)
 Logical Operators (&,|,!, ^)
 Conditional Operators (?:)
 Special Operators (instanceOf)
Automatic type conversion
 Conversion of float to int causes
truncation of fractional part.
 double to float conversion causes
rounding of digits.
 long to int conversion causes dropping of
the excess higher order bits.
 Type conversion can not be applied to
boolean data type.
Type promotion rules
 All byte, short and char values are
promoted to int.
 If one operand in the expression is long
then the whole expression will be
promoted to long.
 If one operand is float then the whole
expression will be promoted to float.
 If any of the operands is double, the
result is double.
 Example
Conversion.java
Promote.java
No loss of information

From To

short, char, int, long, float,


byte
double

short int, long, float, double

char int, long, float, double

int long, float, double

long float, double

float double
Free form language
System.out.println(“Welcome to Java”);
Can also be written as,
System.out.println
(“Welcome to Java”);
Or even as,
System.
out
.
println(“Welcome to Java”);
Decision making
statements
 if
 if-else
 Nested if-else
 else-if ladder
 switch-case
Loop statements
 for loop
 while loop
 do-while loop
 Nested loops
 Example
BlockTest.java
break statement
 Jumping out of switch-case.
 Breaking loop statements
 Specialized form of goto
break as goto
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t)
break second;
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
continue statement
 It is useful to force the early iteration of
the loop.
 When we want to continue the next
iteration of the loop by skipping some
part inside it, the ‘continue’ statement
can be used. It is also associated with the
condition
 Example
ContinueLabel.java
Class definition
class class-name
{
data-type instance-variable1;
data-type instance-variable2;
- - - - -;
data-type instance-variableN;
data-type method-name1(parameter-list)
{
//body of the method1
}
data-type method-name2(parameter-list)
{
//body of the method2
}
- - - - -;
data-type method-nameN(parameter-list)
{
//body of the methodN
}
}
Example: class
class Country
{
long population;
float currencyRate;
int noOfStates;
}
Creating objects
 Country japan; // declaration

 japan = new Country(); //


instantiation

Or (combined)

 Country japan = new Country();


Object instantiation
Constructor
 A constructor used to initialize an object
immediately upon creation.
 It has the same name as the class in which it
resides and it is syntactically similar to a
method. Once defined, the constructor is
automatically called immediately after the
object is created, before the new operator
completes.
 It is the constructor’s job to initialize the internal
state of an object so that the code creating an
instance will have a fully initialized, usable
object instantly
Example
class Country
{
long population;
int noOfStates;
float currancyRate;
Country(long x, int y)
{
population = x;
noOfStates = y;
}
void display()
{

System.out.println(“Population:”+population);
System.out.println(“No of
states:”+noOfStates);
}
}
Constructor overloading
class Box
{
int height, depth, length;
Box() {
height = depth = length = 10;
}
Box(int x,int y) {
height = x; depth = y;
}
Box(int x, int y, int z) {
height = x; depth = y; length = z;
}
}
 Example
BoxDemo7.java
The ‘this’ keyword
 Used to refer the instance variables and
methods of the same class where it is
used.
 Used to call a constructor from another
constructor.
The ‘this’ keyword
class Box
{
int height;
int depth;
int length;
Box(int height, int depth, int length)
{
this.height = height;
this.depth = depth;
this.length = length;
}
}
 Examples
This-Example1.txt
This-Example with
Constructor.txt
Method overloading
 It is possible to define two or more
methods within the same class that are
having the same name, but their
parameter declarations are different.
 In the case, the methods are said to be
overloaded, and the process is referred to
as method overloading.
 Method overloading is one of the ways of
Java implementation of polymorphism.
Example
int add(int z) //version1
{
cal = z + 10;
return(cal);
}
float add(float x, float y) //version2
{
val = x + y;
return(val);
}
 Example
Overload.java
Overload1.java
Static members
 In some cases it is necessary to define
a member that is common to all the
objects and accessed without using a
particular object.
 That is, the member belongs to the
class as a whole rather than the
objects created from the class. Such
members can be created by preceding
them with the keyword static.
Example: static
 static int cal;
 static float min = 1;
 static void display(int x)
‘static’ restrictions
Restrictions over static methods
 They can only call other static methods.
 They must only access static data.
 They cannot refer to this or super in any
way.
Example: static
class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme()
{
System.out.println("a = " + a);
}
}
class StaticByName
{
public static void main(String args[])
{
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Calling methods
 Call by value
 Call by reference
Call by Value & reference
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
// pass an object
void meth(Test o)
{
o.a *= 2;
o.b /= 2;
}
}
class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " +
ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " +
ob.b);
}
Recursion
int fact(int n)
{
if(n==1)
return 1; //statement1
else
return(n*fact(n-1));
}
Nested classes
 It is possible to define a class within
another class; such classes are known as
nested classes.
 The scope of a nested class is bounded
by the scope of its enclosing class.
 Types-
 Static
 Non-static
Static nested class
 A static nested class is one which has the
static modifier applied.
 Because it is static, it must access the
members of its enclosing class through
an object.
 That is, it cannot refer to members of its
enclosing class directly.
 Because of this restriction, static nested
classes are rarely used.
Non-static nested class
 An inner class is a non-static nested
class.
 It has access to all of the variables and
methods of its outer class and may refer
to them directly in the same way that
other non-static members of the outer
class do.
 Thus, an inner class is fully within the
scope of its enclosing class.
 Example
InnerClassDemo.java
Inheritance
 The reusability can be obtained by creating
new classes and reusing the properties of
the existing one.
 The mechanism of deriving a new class from
existing one is called as inheritance. The old
class or existing class is known as super
class and new class is known as subclass.
 Thus, a subclass is specialized version of
super class. We can call super class as base
class or parent class and subclass as derived
class or child class.
Inheritance types
 Single Inheritance (only one super and subclass)
 Hierarchical Inheritance (one super class with
many subclasses)
 Multilevel Inheritance (subclass is super class of
another class)
 Hybrid Inheritance (combination of above three
types)
Creating inheritance
class subclassname extends
superclassname
{
//Body of the class;
}
Example
class Super
{
int i, j;
void show()
{
System.out.print("i and j: ");
System.out.println( + i + " " + j);
}
}
class Sub extends Super
{
int k;
void display()
{
System.out.println("k: " + k);
}
void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}
}
 Example

SimpleInheritance.java
The ‘super’ keyword
 The keyword ‘super’ has specially been
added for inheritance.
 Whenever the subclass needs to refer to
its immediate super class, ‘super’
keyword is used. There are two different
applications of the ‘super’. That are,
 Accessing members from super class that has
been hidden by members of the subclass
 Calling super class constructor
 Example
DemoSuper.java
UseSuper.java
Multilevel hierarchy
class A
{
…….
…….
…….
}
class B extends A
{
…….
…….
…….
}
class C extends B
{
…….
…….
…….
}
Sequence of constructor
call
class GrandFather class Child extends Father
{ {
GrandFather() Child()
{ {
System.out.println("This is GrandFather");
System.out.println("This is
} Child");
}
}
class Father extends GrandFather
}
{
class CallConstructor
Father()
{ {
System.out.println("This is Father"); public static void main(String
} args[])
} {
Child roger = new Child();
}
}
Method overriding
 A method in a subclass has the same
name and type signature as a method in
its superclass.
 Compiler will always refer to the version
of that method defined by the subclass.
 Example
Override.java
Override1.java
Dynamic method dispatch
 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 the only way in which Java
implements run-time polymorphism.
 Example
Dispatch.java
Abstract class
 In some situations, it may be required to define
a super class that declares the structure of a
given abstraction without providing a complete
implementation of every method.
 That is, sometimes we may want to create a
super class that only defines a generalized form
that will be shared by all of its subclasses by
leaving it to each subclass to fill in the details.
 Such a class determines the nature of the
methods that the subclasses must implement.
This can be done by creating a class as an
abstract.
Abstract class and
methods
abstract datatype
methodname(parameters);

abstract class White


{
……
abstract void paint();
……
……
}
 Example
AbstractDemo.java
The ‘final’ keyword
 Defines a constant value.
 Prevents method from being overridden.
 Preventing inheritance
Wrong implementation
class First
{
final void display()
{
System.out.println(“This is first class”);
}
}
class Second extends First
{
void display() //statement1
{
System.out.println(“This is second class”);
}
}
Wrong implementation
final class First
{
// ….
}
class Second extends First //statement1
{
// ….
}
The Object class
 There is one special class, ‘Object’,
defined by Java. All other classes are
subclasses of ‘Object’.
 That is, ‘Object’ is a super class of all
other classes. This means that a
reference variable of type ‘Object’ can
refer to an object of any other class.
 Also, since arrays are implemented as
classes, a variable of type ‘Object’ can
also refer to any array.
The Object class Methods
Object clone() Creates new object same as cloned
object

Boolean equals(Object object) Determines whether one object is equal


to another

void getClass() Obtains the class of an object at run


time

Int hashCode() Returns the hash code associated with


the invoking object

Void notify() Resumes execution of a thread waiting


on the invoking object

Void notifyAll() Resumes execution of all threads


waiting on the invoking object

String toString() Returns a string that describes the


object

Void wait() Waits on another thread of execution


Visibility controls
 Public
 Private
 Protected
 Default
public
protected
default/package/friendly
private
Arrays (are objects in Java)
 Declare
• int a[]; // 1-dim
• int []b; // 1-dim
• int [ ] c [ ]; // 2-dim
• int c [ ][]; // 2-dim

 Allocate space
• a = new int [7];
• c = new int [7][11];
Arrays have length
 used to retrieve the size of an array
• int a [ ] = new int [7]; // 1-dim
 System.out.println(a.length); will print
‘7’

• int b [ ] [ ] = new int [7] [11];


 System.out.println(a.length); will print
‘7’
 System.out.println(b.length *
b[0].length); will print ‘77’
Anonymous array
class Anonymous
{
void printArray(int arr[])
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+", ");
}
public static void main(String args[])
{
Anonymous a = new Anonymous();
System.out.println("Array is: ");
a.printArray(new int[] {5,7,9,3,4}); //stmt1
}
}
Variable size arrays
int table[ ][ ] = new int[3][ ];

table[0] = new int[5];


table[1] = new int[2];
table[2] = new int[3];
Variable size array
java.util.Arrays class

static void sort(Object array[ ])


static void sort(Object array[ ], int start, int
end)
static int binarySearch(Object array[ ],
Object val)
static boolean equals(Object arr1[ ], Object
arr2[ ])
static void fill(Object array[ ], Object value)
String Methods
int length()
String concat(String str)
char charAt(int index)
void getChars(int s, int e, char target[], int
tstart)
byte[] = getBytes( );
char[] toCharArray( )
boolean equals(String str)
boolean equalsIgnoreCase(String str)
boolean startsWith(String str)
boolean endsWith(String str)
String Methods
int compareTo(String str)
int compareToIgnoreCase(String str)
int indexOf(String str)
int lastIndexOf(int ch, int startIndex)
String substring(int start)
String substring(int start, int end)
String replace(char original, char
replacement)
String trim()
String toLowerCase( )
String toUpperCase( )
 Example
StringHandling.txt
StringBuffer class
 String represents fixed-length, immutable
character sequences.
 In contrast, StringBuffer represents
growable and writeable character
sequences.
 It is possible to insert the characters
anywhere inside the StringBuffer.
 StringBuffer will automatically grow to
make room for such additions and often
has more characters pre-allocated than
are actually needed, to allow room for
 Example
Test.java
Package
 Package is Java’s most innovative feature.
 Package is Java’s way of grouping the
classes and interfaces together.
 That is, a package is called as the collection
of classes and interfaces.
 It can be called as the container for classes
that is used to keep the class name space
compartmentalized.
 Packages are stored in a hierarchical manner
and are explicitly imported into new class
definitions
Package goals
 Classes contained in packages of other
programs can be easily reused.
 Two classes in two different packages can have
same name but they should be referred by their
fully qualified name.
 Packages provide a way of hiding classes. So we
can prevent them from accessing outside.
 Packages provide a way of separating ‘design’
from ‘coding’. We can design classes and decide
their relationships and then we can implement
the Java code needed for the methods.
Package hierarchy
Java package hierarchy
import statement
 import java.awt.*;
 import java.awt.event.*;
 import java.applet.Applet;

Using a class in program:

 java.util.Vector v = new
java.util.Vector(10);
Creating package
 Include a package command as the first
statement in a Java source file.
 Then any classes declared within that file
will automatically belong to the specified
package.
 The package statement defines a name
space in which classes are stored. If we
omit the package statement, the class
names are put into the default package,
which has no name.
Package statement
 package pkg;

 Here, ‘pkg’ is the name of the package. For


example, the following statement creates a
package called ‘MyPackage’.

package myPackage;
public class MyClass
{
//body of the class
}
Package hierarchy
 We can create a hierarchy of packages
also. For this, we have to separate each
package name from the one above it by
use of a dot operator.
 The general form of a multileveled
package statement is shown here:

package pkg1[.pkg2[.pkg3]];

e.g. package java.awt.image.*;


Example
package myPack; class SimplePack
class Nation {
{ public static void main(String args[])
String name; {
long pop; Nation asia[ ] = new Nation[3];
asia[0] = new Nation("Korea",
Nation(String n, long p) 56233314);
{ asia[1] = new Nation("Iran",
name = n; 35264124);
pop = p; asia[2] = new Nation("Singapore",
2356660);
}
for(int i=0; i<3; i++)
void display( )
asia[i].display( );
{
}
System.out.println("Nation:"+name); }

System.out.println("Population:"+pop);
}
}
Executing the program
 Save this file with name SimplePack.java, and
put it in a directory called myPack. Next,
compile the file. This can be compiled by
following command:

javac myPack\SimplePack.java

 After this the resulting .class file will get stored


also in the myPack directory. Then try executing
the SimplePack.class, using the following
command line:

java myPack.SimplePack
Visibility control

private default protected public

Same class Yes Yes Yes Yes

Same package subclass No Yes Yes Yes

Same package no
No Yes Yes Yes
subclass

Different package
No No Yes Yes
subclass

Different package no
No No No Yes
subclass
 Example
Packages.txt
Hiding classes
package myPack;
public class A
{
//body of A
}
class B
{
//body of B
}
Static import
import static java.lang.Math.sqrt;
import static java.lang.Character.isUpperCase;
import static java.lang.System.out;
class StaticImport
{
public static void main(String args[])
{
double x = sqrt(52); //method1
out.print("Square root of 52: ");
out.println(x); //method2
char ch = 'D';
if(isUpperCase(ch)) //method3
out.println(ch+" is uppercase");
}
}
interface
 Interface is Java’s abstract class
implementation. They can not be
instantiated.
 That is, using interface, we can specify what
a class must do, but not how it does it.
 Interfaces are syntactically similar to
classes, but they do not have instance
variables, and their methods are declared
without having any body.
 This means that we can define interfaces
which don’t make assumptions about how
they are implemented.
interface
 Once the interface is defined, any number of
classes can implement an interface. Also,
one class can implement any number of
interfaces.
 To implement an interface, a class must
create the complete set of methods defined
by the interface. However, each class can
define the methods with different
definitions.
 By providing the interface keyword, Java
allows us to fully utilize the “one interface,
multiple methods” aspect of polymorphism.
Interfaces are designed to support dynamic
Defining an interface
access interface InterfaceName
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
.......
data-type final-varname1 = value;
data-type final-varname2 = value;
.......
return-type method-nameN(parameter-list);
data-type final-varnameN = value;
}
Example
interface College
{
int studs = 120;
void play();
int countUp(int x);
}
Implementing an interface
access class ClassName [extends
superclass]
[implements interface
[,interface...]]
{
// class-body
}
Example
class Sitrc implements College
{
public void play( )
{
System.out.println(“Let’s play !!!”);
}
public int countUp(int x)
{
x++;
return(x);
}
}
Implementation
interface Mango class MyInterface
{ {
void display( ); public static void main(String args[ ])
{
}
Mango m = new Summer( ); //statement
class Summer implements Mango Winter n = new Winter( );
{ m.display( );
public void display( ) m = n; //assigning the reference
{ m.display( );
System.out.println("First Display method... }
"); }
}
}
class Winter implements Mango
{
public void display( )
{
System.out.println("Second Display
method...");
}
}
Partial implementation
error
interface Mango
{
void display();
void show();
}
class Summer implements Mango
{
public void display()
{
System.out.println("Display method");
}
}
 Example
TestIface2.java
Partial-interface.txt
Implementing multiple inheritance
Nesting of interfaces
class CPU
{
public interface MicroProcessor
{
boolean isMultiCore(int core);
}
}
class Computer implements CPU.MicroProcessor
{
public boolean isMultiCore(int core)
{
if(core>1)
return true;
else
return false;
}
}
Interface variables
interface Constants
{
double PI = 3.14;
String unit = " sq.cm";
}
interface Values
{
int cir = 2;
}
public class InterfaceVar implements Constants
{
public static void main(String args[])
{
double rad = 5.83;
System.out.print("Area of circle: ");
System.out.println(PI * rad * rad + unit);
System.out.print("Perimeter of circle: ");
System.out.println(Values.cir*PI*rad);
}
}
Interface inheritance
interface SEIT
{
int strength = 74;
void displaySecond();
}
interface TEIT extends SEIT
{
int strength = 66;
void displayThird();
void displayAll();
}
class InfoTech implements TEIT
{
int total;
 Example
IFExtend.java
Interface versus abstract class
 Methods of a Java interface are implicitly abstract and cannot
have implementations. A Java abstract class can have instance
methods that implements a default behavior.
 Variables declared in a Java interface is by default final. An
abstract class may contain non-final variables.
 Members of a Java interface are public by default. A Java
abstract class can have the usual flavors of class members like
private, protected, etc..
 Java interface should be implemented using keyword
“implements”; A Java abstract class should be extended using
keyword “extends”.
 An interface can extend another Java interface only, an abstract
class can extend another Java class and implement multiple Java
interfaces.
 A Java class can implement multiple interfaces but it can extend
only one abstract class.
 Interface is absolutely abstract and cannot be instantiated; A
Java abstract class also cannot be instantiated, but can be
invoked if a main() exists.
Multithreading
Java thread model
Java thread states
 Newborn state
 Runnable state
 Running state
 Blocked state
 Dead state
The Thread class methods

Method Meaning

getName( ) Obtains a thread’s name.

getPriority( ) Obtains a thread’s priority

isAlive( ) Determines whether a thread is still

running

join( ) Waits for a thread to terminate

run( ) Creates entry point for the thread

sleep( ) Suspends a thread for some period of

time
The main thread
 All the Java programs are at least single
threaded programs.
 When a Java program starts up, one thread
begins running immediately. This is usually
called the main thread of the program, because
it is the one that is executed when our program
begins.
 The main thread is important for two reasons:
 It is the thread from which other “child” threads can be
initiated
 Generally it must be the last thread to finish execution
because it performs various shutdown actions.
Using main thread
class CurrentThread
{
public static void main(String args[]) throws
InterruptedException
{
Thread t = Thread.currentThread();
System.out.println("Current thread: " + t);
// changing the name of the thread
t.setName("Prime Thread");
System.out.println("After name change: " + t);
Thread.sleep(3000);
System.out.println("End of main thread & Program");
}
}
Creation of thread in Java
 Implementing Runnable interface
 Extending the Thread class
 Example
ThreadDemo.java
ExtendThread.java
Implementing Runnable interface

 public void run( )

 void start( )

 Thread(Runnable threadOb, String threadName)


Thread implementation
methods
 final boolean isAlive( )

 final void join( ) throws


InterruptedException
Setting thread priority
 final void setPriority(int level)

 final int getPriority( )

 NORM_PRIORITY
 MAX_PRIORITY
 MIN_PRIORITY
Thread synchronization
 Needed for execution of multiple threads.

 Two ways-
 synchronized methods
 synchronized blocks

 The keyword synchronized is used to


perform this operation.
 Example

MultiThreadDemo.java
Applets
The Applet
The Applet skeleton
import java.awt.*; public void stop( )
import java.applet.*; {
public class MyApplet extends // suspends
Applet execution
{ }
public void init( ) public void destroy( )
{ {
// initializes // perform
applet shutdown activities
} }
public void start( ) public void paint (Graphics g)
{ {
// start or // redisplay
resume execution contents of window
} }
}
The Applet method calls
Life cycle of applet
Life cycle of applet
 init: This method is intended for whatever initialization is
needed for your applet.
 start: This method is automatically called after the browser calls
the init method. It is also called whenever the user returns to the
page containing the applet after having gone off to other pages.
 stop: This method is automatically called when the user moves
off the page on which the applet sits. It can, therefore, be called
repeatedly in the same applet.
 destroy: This method is only called when the browser shuts
down normally. Because applets are meant to live on an HTML
page, you should not normally leave resources behind after a
user leaves the page that contains the applet.
 paint: Invoked immediately after the start() method, and also
any time the applet needs to repaint itself in the browser. The
paint() method is actually inherited from the java.awt.
A simple applet
import java.awt.*;
import java.applet.*;
/*
<applet code = "HelloApplet" width = 200 height = 100>
</applet>
*/
public class HelloApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello",100,50);
}
}
Colors
Color.black Color.magenta
Color.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellow
Color.lightGray

void setBackground(Color newCol)


void setForeground(Color newCol)
Graphics class
 void drawLine(int startx, int starty, int endx, int endy)
 void drawRect(int top, int left, int width, int height)
 void fillRect(int top, int left, int width, int height)
 void drawRoundRect(int top, int left, int width, int height, int
xDiam, int yDiam)
 void fillRoundRect(int top, int left, int width, int height, int
xDiam, int yDiam)
 void drawOval(int top, int left, int width, int height)
 void fillOval(int top, int left, int width, int height)
 void drawArc(int top, int left, int width, int height, int startAngle,
int sweepAngle)
 void fillArc(int top, int left, int width, int height, int startAngle, int
sweepAngle)
 void drawPolygon(int x[ ], int y[ ], int numPoints)
 void fillPolygon(int x[ ], int y[ ], int numPoints)
GUI Programming in Java
(AWT and Event Handling)
AWT - Abstract Window
Toolkit
 Single Windowing Interface on Multiple
Platforms
 Supports functions common to all window
systems
 Uses Underlying Native Window system
 AWT provides
 GUI widgets
 Event Handling
 Containers for widgets
 Layout managers
 Graphic operations
AWT - Abstract Window
Toolkit
 Portable GUI - preserves native look & feel
 Standard GUI Components (buttons…)
 Containers - Panels, Frames, Dialogs
 Graphics class for custom drawing
 Layouts responsible for actual positioning of
components:
 BorderLayout, GridLayout, FlowLayout,
null layout
AWT
 The AWT contains numerous classes and
methods that allow us to create and
manage windows.
 Although 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 environment, such as
Windows.
Window fundamentals
Component
 At the top of the AWT hierarchy is the
Component class. Component is an abstract
class that encapsulates all of the attributes of a
visual component.
 All user interface elements that are
displayed on the screen and that interact
with the user are subclasses of
Component.
 A Component object is responsible for
remembering the current foreground and
background colors and the currently selected
text font.
Container
 A container is responsible for laying out
(that is, positioning) any components that
it contains. It does this through the use of
various layout managers.
Panel
 The Panel class is a concrete subclass of
Container. It doesn’t add any new
methods; it simply implements Container.
 A Panel may be thought of as a
recursively nestable, concrete screen
component. Panel is the super-class for
Applet.
 When screen output is directed to an
applet, it is drawn on the surface of a
Panel object. In essence, a Panel is a
window that does not contain a title
bar, menu bar, or border.
Window
 The Window class creates a top-level
window. A top-level window is not
contained within any other object; it sits
directly on the desktop.
 Generally, we won’t create Window
objects directly. Instead, we will use a
subclass of Window called Frame.
Frame
 Frame encapsulates what is commonly
thought of as a “window.” It is a
subclass of Window and has a title
bar, menu bar, borders, and resizing
corners.
Frame window
 Frame( )
 Frame(String title)

 void setSize(int newWidth, int newHeight)


 void setSize(Dimension newSize)

 void setVisible(boolean visibleFlag)

 void setTitle(String newTitle)


Creating frame within
applet
 AppletFrame.java
 AppWindow.java
AWT Controls
 Controls are components that allow a user to
interact with his application in various ways—for
example; a commonly used control is the push
button.
 A layout manager automatically positions
components within a container.
 Labels
 Push buttons
 Check boxes
 Choice lists
 Lists
 Scroll bars
 Text Area
 Text Field
Adding and removing controls

 Component add(Component compObj)

 void remove(Component obj)


Label
 A label is an object of type Label, and it
contains a string, which it displays.
Labels are passive controls that do not
support any interaction with the user.
 Label defines the following constructors:

 Label( )
 Label(String str)
 Label(String str, int how)
Button
 A push button is a component that
contains a label and that generates an
event when it is pressed. Push buttons
are objects of type Button. Button defines
these two constructors:

 Button( )
 Button(String str)
CheckBox
 A check box is a control that is used to turn an
option on or off. It consists of a small box that
can either contain a check mark or not. There is
a label associated with each check box that
describes what option the box represents.

 Checkbox( )
 Checkbox(String str)
 Checkbox(String str, boolean on)
 Checkbox(String str, boolean on, CheckboxGroup
cbGroup)
 Checkbox(String str, CheckboxGroup cbGroup, boolean
on)
CheckboxGroup
 It is possible to create a set of mutually
exclusive check boxes in which one and
only one check box in the group can be
checked at any one time.

 Checkbox getSelectedCheckbox( )
 void setSelectedCheckbox(Checkbox wh)
Dimension class
 This class encapsulates the ‘width’
and ‘height’ of a component (in
integer precision) in a single object.
 The class is associated with certain
properties of components. Several
methods defined by the Component class
and the LayoutManager interface return a
Dimension object.
Choice
 The Choice class is used to create a pop-
up list of items from which the user may
choose.
 Thus, a Choice control is a form of menu.
When inactive, a Choice component takes
up only enough space to show the
currently selected item.
Choice methods
 int getItemCount( )
 void select(int index)
 void select(String name)
 String getSelectedItem( )
 int getSelectedIndex( )
 void add(String name)
 String getItem(int index)
List
 The List class provides a compact,
multiple-choice, scrolling selection list.
 List( )
 List(int numRows)
 List(int numRows, boolean multipleSelect)
 void add(String name)
 void add(String name, int index)
 String getSelectedItem( )
 int getSelectedIndex( )
 String[ ] getSelectedItems( )
 int[ ] getSelectedIndexes( )
Scrollbar
 Scroll bars are used to select continuous
values between a specified minimum and
maximum. Scroll bars may be oriented
horizontally or vertically.
 A scroll bar is actually a composite of
several individual parts. Each end has an
arrow that we can click to move the
current value of the scroll bar one unit in
the direction of the arrow
Scrollbar methods
 Scrollbar( )
 Scrollbar(int style)
 Scrollbar(int style, int iValue, int tSize, int min, int
max)
 void setValues(int iValue, int tSize, int min, int
max)
 int getValue( )
 void setValue(int newValue)
 int getMinimum( )
 int getMaximum( )
 void setUnitIncrement(int newIncr)
 void setBlockIncrement(int newIncr)
TextComponent

TextComponent

TextArea TextField
TextField
 The TextField class implements a single-
line text-entry area, usually called an edit
control.
 Text fields allow the user to enter strings
and to edit the text using the arrow keys,
cut and paste keys, and mouse selections
Constructor and methods
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
 String getText( )
 void setText(String str)
 String getSelectedText( )
 void select(int startIndex, int endIndex)
 boolean isEditable( )
 void setEditable(boolean canEdit)
 void setEchoChar(char ch)
 boolean echoCharIsSet( )
 char getEchoChar( )
TextArea
 Sometimes a single line of text input is
not enough for a given task.
 To handle these situations, the AWT
includes a simple multiline editor called
TextArea.
TextArea
 TextArea( )
 TextArea(int numLines, int numChars)
 TextArea(String str)
 TextArea(String str, int numLines, int numChars)
 TextArea(String str, int numLines, int numChars, int
sBars)

 SCROLLBARS_BOTH
SCROLLBARS_NONE
 SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
 void append(String str)
 void insert(String str, int index)
LayoutManager
 A layout manager is an instance of any
class that implements the
LayoutManager interface.
 The layout manager is set by the
setLayout( ) method. If no call to
setLayout( ) is made, then the default
layout manager is used.
 Whenever a container is resized (or sized
for the first time), the layout manager is
used to position each of the components
within it.
LayoutManager

void setLayout(LayoutManager layoutObj)


Adding Components via
Layouts
FlowLayout
 FlowLayout implements a simple layout
style, which is similar to how words flow
in a text editor.
 Components are laid out from the upper-
left corner, left to right and top to
bottom. When no more components fit on
a line, the next one appears on the next
line.
 A small space is left between each
component, above and below, as well as
left and right.
FlowLayout
 FlowLayout( )
 FlowLayout(int how)
 FlowLayout(int how, int horz, int vert)

 FlowLayout.LEFT
 FlowLayout.CENTER
 FlowLayout.RIGHT
BorderLayout
 The BorderLayout class implements a
common layout style for top-level
windows.
 It has four narrow, fixed-width
components at the edges and one large
area in the center.
 The four sides are referred to as north,
south, east, and west. The middle area is
called the center.
BorderLayout
 BorderLayout( )
 BorderLayout(int horz, int vert)

 BorderLayout.CENTER
BorderLayout.SOUTH
 BorderLayout.EAST
BorderLayout.WEST
 BorderLayout.NORTH
 void add(Component compObj, Object
region);
Insets
 Sometimes we want to leave a small
amount of space between the container
that holds our components and the
window that contains it.
 For doing this, we have to override the
getInsets( ) method that is defined by
Container.
Insets
 Insets(int top, int left, int bottom, int
right)

 Insets getInsets( )

 Example:
public Insets getInsets()
{
return new Insets(10, 10, 10, 10);
}
GridLayout
 GridLayout lays out components in a two-
dimensional grid. When we instantiate a
GridLayout, we define the number of
rows and columns.

 GridLayout( )
 GridLayout(int numRows, int numColumns )
 GridLayout(int numRows, int numColumns, int
horz, int vert)
Menus
 A top-level window can have a menu bar
associated with it.
 A menu bar displays a list of top-level
menu choices.
 Each choice is associated with a drop-
down menu. This concept is implemented
in Java by the following classes:
MenuBar, Menu, and MenuItem.
Creating menus on Frame

Create Add
Menu
Menubar MenuItems to
Objects
Object Menu

Add Menubar
to Applet
Menu
 Menu( )
 Menu(String optionName)
 Menu(String optionName, boolean
removable)
MenuItem
 MenuItem( )
 MenuItem(String itemName)
 MenuItem(String itemName,
MenuShortcut keyAccel)

 void setEnabled(boolean enabledFlag)


CheckboxMenuItem
 CheckboxMenuItem( )
 CheckboxMenuItem(String itemName)
 CheckboxMenuItem(String itemName,
boolean on)
Adding menu and menu items

 Method of Menu class-


 MenuItem add(MenuItem item)

 Method of Menubar-
 Menu add(Menu menu)
Delegation Event Model
Event
 In the delegation model, an event is an
object that describes a state change in a
source.
 It can be generated as a consequence of
a person interacting with the elements in
a graphical user interface.
 Some of the activities that cause events
to be generated are pressing a button,
entering a character via the keyboard,
selecting an item in a list, and clicking
the mouse.
Event Source
 A source is an object that generates an
event. This occurs when the internal state
of that object changes in some way.
 Sources may generate more than one
type of event.

 public void addTypeListener(TypeListener


el)
Event Listeners
 A listener is an object that is notified
when an event occurs.
 It has two major requirements.
 First, it must have been registered with one or
more sources to receive notifications about
specific types of events.
 Second, it must implement methods to receive
and process these notifications.
Event classes
 The classes that represent events are at
the core of Java’s event handling
mechanism.
 At the root of the Java event class
hierarchy is EventObject, which is in
java.util. It is the superclass for all
events.
 EventObject contains method:

 Object getSource( )
Event Objects
 EventObject is a superclass of all events.
 AWTEvent is a superclass of all AWT
events that are handled by the
delegation event model.
Events
 ActionEvent
 AdjustmentEvent
 ComponentEvent
 ContainerEvent
 FocusEvent
 InputEvent
 ItemEvent
 KeyEvent
 MouseEvent
 MouseWheelEvent
 TextEvent
 WindowEvent
Events
 ActionEvent - Generated when a button is
pressed, a list item is double-clicked, or a
menu item is selected.
 AdjustmentEvent- Generated when a
scroll bar is manipulated.
 ComponentEvent- Generated when a
component is hidden, moved, resized, or
becomes visible.
Events
 ContainerEvent- Generated when a
component is added to or removed from
a container.
 FocusEvent- Generated when a
component gains or loses keyboard
focus.
 InputEvent- Abstract super class for all
component input event classes.
 ItemEvent- Generated when a check box
or list item is clicked; also occurs when a
choice selection is made or a checkable
Events
 KeyEvent- Generated when input is received
from the keyboard.
 MouseEvent- Generated when the mouse is
dragged, moved, clicked, pressed, or released;
also generated when the mouse enters or exits
a component.
 MouseWheelEvent- Generated when the mouse
wheel is moved.
 TextEvent- Generated when the value of a text
area or text field is changed.
 WindowEvent- Generated when a window is
activated, closed, deactivated, deiconified,
iconified, opened, or quit.
ActionEvent
 An ActionEvent is generated when a
button is pressed, a list item is double-
clicked, or a menu item is selected.

 String getActionCommand( )
AdjustmentEvent
 An AdjustmentEvent is generated by a
scroll bar. There are five types of
adjustment events.
 The AdjustmentEvent class defines
integer constants that can be used to
identify them. The constants and their
meanings are shown here:
AdjustmentEvent
 BLOCK_DECREMENT The user clicked inside
the scroll bar to decrease its value.
 BLOCK_INCREMENT The user clicked inside
the scroll bar to increase its value.
 TRACK The slider was dragged.
 UNIT_DECREMENT The button at the end of
the scroll bar was clicked to decrease its value.
 UNIT_INCREMENT The button at the end of
the scroll bar was clicked to increase its value

 int getValue( )
ComponentEvent
 A ComponentEvent is generated when the
size, position, or visibility of a component
is changed. There are four types of
component events.

 COMPONENT_HIDDEN - Component was hidden.


 COMPONENT_MOVED - Component was moved.
 COMPONENT_RESIZED - Component was
resized.
 COMPONENT_SHOWN- Component became
visible.
InputEvent

ComponentEvent

InputEvent

KeyEvent MouseEvent
ItemEvent
 An ItemEvent is generated when a check
box or a list item is clicked or when a
checkable menu item is selected or
deselected.
 There are two types of item events, which
are identified by the following integer
constants:

 DESELECTED The user deselected an


item.
 SELECTED The user selected an
ItemEvent
 Object getItem( )

 int getStateChange( )
KeyEvent
 A KeyEvent is generated when keyboard
input occurs.
 There are three types of key events,
which are identified by these integer
constants: KEY_PRESSED, KEY_RELEASED,
and KEY_TYPED.
 The first two events are generated when
any key is pressed or released. The last
event occurs only when a character is
generated.
KeyEvents
 KeyEvent constants:
VK_ENTER VK_ESCAPE
VK_CANCEL VK_UP
VK_DOWN VK_LEFT
VK_RIGHT VK_PAGE_DOWN
VK_PAGE_UP VK_SHIFT
VK_ALT VK_CONTROL
 char getKeyChar( )
 int getKeyCode( )
MouseEvent
 MOUSE_CLICKED The user clicked the mouse.
 MOUSE_DRAGGED The user dragged the
mouse.
 MOUSE_ENTERED The mouse entered a
component.
 MOUSE_EXITED The mouse exited from a
component.
 MOUSE_MOVED The mouse moved.
 MOUSE_PRESSED The mouse was pressed.
 MOUSE_RELEASED The mouse was
released.
 MOUSE_WHEEL The mouse wheel was moved.
MouseEvent
 int getX( )
 int getY( )
 Point getPoint( )
 void translatePoint(int x, int y)
 int getClickCount( )
Event Listeners
 The delegation event model has two
parts: sources and listeners.
 Listeners are created by implementing
one or more of the interfaces defined by
the java.awt.event package.
 When an event occurs, the event source
invokes the appropriate method defined
by the listener and provides an event
object as its argument.
Listener Interfaces
 ActionListener Interface
 void actionPerformed(ActionEvent ae)
 AdjustmentListener Interface
 void
adjustmentValueChanged(AdjustmentEvent ae)
 ComponentListener Interface
 void componentResized(ComponentEvent ce)
 void componentMoved(ComponentEvent ce)
 void componentShown(ComponentEvent ce)
 void componentHidden(ComponentEvent ce)
Listener Interfaces
 ItemListener Interface
 void itemStateChanged(ItemEvent ie)
 KeyListener Interface
 void keyPressed(KeyEvent ke)
 void keyReleased(KeyEvent ke)
 void keyTyped(KeyEvent ke)
 MouseListener Interface
 void mouseClicked(MouseEvent me)
 void mouseEntered(MouseEvent me)
 void mouseExited(MouseEvent me)
 void mousePressed(MouseEvent me)
 void mouseReleased(MouseEvent me)
Listener interfaces
 MouseMotionListener Interface
 void mouseDragged(MouseEvent me)
 void mouseMoved(MouseEvent me)

 TextListener Interface
 void textChanged(TextEvent te)
Examples
 MouseEvents.java
 SimpleKey.java
 ButtonDemo.java
References
 Herbert Schildt, “The Complete
Reference: Java”, 5th Edition, Tata McGraw
Hill.

 E Balagurusamy, “Programming with


Java”, 4th Edition, Tata McGraw Hill.
University Questions (Unit Three)
1) With respect to JAVA, what is use of String Buffer over String? [4]
(April 10)
2) What is the use of following JAVA methods? [4] (April 10)
i) indexOf(String S, int i)
ii) toCharArray()
3) How to create our own exception handling mechanism in JAVA? [4]
(April 10)
4) Explain significance of following keywords of exception handling
with examples. [8] (April 11)
i) Try ii) Catch iii) Throw iv) Throws
5) What do you mean by checked exceptions? What are Pros and Cons
of the same? [6] (April 11)
6) What is difference between Abstraction, Encapsulation and Data
Hiding?
[6] (April 11)
7) Explain in brief: types of access specifiers associated with JAVA. [4]
(oct.09)
8) Differentiate between concept of static variable and instance
University Questions (Unit Three)
10) Explain the concept of inheritance with respect to Java and C++ in
detail. [10]
(April 11)
11) Differentiate between abstract class and interface in Java. [02]
(April 11)
12) What is the difference between a window and a Frame in Java. [04]
(April 11)
13) Explain any 3 types of listeners in Java. [06] (April 11)
14) Differentiate between Java Swing and Java AWT. [06] (April 11)
15) Explain the following concepts in Java. . [08] (April 11)
i) Panel ii) Frame iii) Canvas iv) Container
16) Explain Run-Time Type identification with respect to Java. . [06]
(April 12)
17) Explain the concept of Multithreading. Explain the same with
respect to JAVA with suitable example. [10] (Nov 12)

You might also like