Professional Documents
Culture Documents
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
Java – an Introduction
BITS Pilani
Pilani Campus
What is Java?
Hardware and
Programmer
Operating System
• Web applications
• Enterprise applications
• Mobile
• Embedded System
• Smart card
• Robotics
• Games etc.
• JavaFx
• Rich internet applications. Uses light weight user interface APIs.
• Released in 1995.
• JDK 1.0 was released in Jan 23, 1996.
Features of Java
Java Buzzwords
• Simple
• Syntax based on C++
• Removed confusing and rarely used features like pointers, operator overloading
etc.,
• Automatic garbage collection
• Object Oriented
• Object, Class, Inheritance, Polymorphism, Abstraction, Encapsulation
• Platform Independent
• Compiler converts Java code to bytecode
• Bytecode is platform independent
• Write Once and Run Anywhere
JAVA COMPILER
(translator)
JAVA INTERPRETER
(one for each different system)
• Secured
• Robust
• Strong memory management, secure due to lack of pointers, automatic garbage
collection, exception handling and type checking
• Size of primitive types is fixed i.e., 4 bytes for both 32 and 64 bit architectures
• Porting the java system to any new platform involves writing an interpreter.
• The interpreter will figure out what the equivalent machine dependent code to run
• High Performance
• Bytecode is close to native code
• It is an interpreted language hence slower than C, C++
• Distributed
• Enables access to files by calling methods from any machine on the internet
• RMI, EJB
• Multi-threaded
• Thread is like a separate program executing concurrently
• Doesn’t occupy memory for each thread
• Multimedia, Web applications etc
• Dynamic
• Supports dynamic loading of classes i.e. classes are loaded on demand
• Also supports functions from native languages i.e. C and C++
BITS Pilani
Pilani Campus
My first program
class first{
public static void main(String args[]){
System.out.println("Hello World");
}
}
• INVALID
• public void main(String[] args)
• static void main(String[] args)
• public void static main(String[] args)
• abstract public static void main(String[] args)
• Class
• Object
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
Vehicle Objects
Polygon Objects
Polygon Class
Abstract Attributes: Vertices, Border,
Into Color, FillColor
Operations: Draw(), Erase(), Move()
Student Circle
Account
class Student{
int id; Creates a data
String name;
type Student
}
// Class Student
Student s1;
• Encapsulation is:
– Binding the data with the code that manipulates it.
– It keeps the data and the code safe from external interference
Parent
Inherited
capability
Child
Shape
Circle Rectangle
move(newCentre){ move(newCentre){
centre = newCentre; centre = newCentre;
} }
centre move(newCentre){
centre = newCentre
}
move(newCentre)
Circle Rectangle
height
radius width
area() area()
circumference() circumference()
method name should start with lowercase letter and be a verb e.g.
actionPerformed(), main(), print(), println() etc.
• Types of variables
• Static or class variables
• Instance Variables
• Local variables
System.out.println(obj1.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(myClassVar);
// instance variable
public String myVar="instance variable";
// Creating object
VariableExample obj = new VariableExample();
System.out.println("Calling Method"); Output:
Calling Method
obj.myMethod(); Inside Method
Instance variable
System.out.println(obj.myVar);
}
} BITS Pilani, Pilani Campus
Primitive Data Types
Ans: 99
ch = num;
System.out.println(ch);
Error: incompatible types: possible lossy conversion from int
to char
Solution: ch = (char) num; //Type casting or explicit conv.
Ans: X
BITS Pilani, Pilani Campus
Type Promotion
• While evaluating
expressions, the
intermediate value may
exceed the range of
operands and hence the
expression value will be
promoted.
• Some conditions for type
promotion are:
• Java automatically promotes
each byte, short, or char operand
to int when evaluating an
expression.
• If one operand is a long, float or
double the whole expression is
promoted to long, float or double
respectively.
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
// The Expression
double result = (f * b) + (i / c) - (d * s);
System.out.println("result = " + result);
byte b = 50;
b = (b * 2);
System.out.println(b);
Ans: 100
int a=10,b=20,c=30,d=40,e=50;
int result = a>=10 ? b <20 ?c :d :e ;
System.out.println("Result:" + result );
• Answer: 40
int a=-9;
Boolean b=true;
Boolean result = (a>0) && (b=false) ;
System.out.println("Result:" + result +"b="+b);
Answer: b= true
Account
acc_no
name
amount
}
} Output:
Compile time error
Types of constructors
• Default (no argument) constructor
• Provide default values to the object like 0, null etc.
• Parameterized constructor
• Provide different values to distinct objects.
class TestAccount{
public static void main(String[] args){
Account a1=new Account(); Output:
a1.display(); 0 null 0.0
}}
Static Keyword
Static Method
• Restrictions
• Static method cannot use non static data member or call non-static method
directly i.e. non static members can only be accessed using objects.
• this and super keywords cannot be used in static context.
BITS Pilani, Pilani Campus
Static Method - Example
class Account{
int acc_no;
String name;
float amount;
static int branch;
Account(int acc,String aname, float amt){
acc_no = acc;
name = aname;
amount = amt; }
static void change(int bch)
{
branch = bch; }
void display(){System.out.println(acc_no+" "+name+" "+amount+"
"+branch);}
}
}
}
• Example
class first{
static int i;
static{i = 100; System.out.println("static block is invoked with i="+i);}
public static void main(String args[]){
System.out.println("Hello main");
Output:
} } static block is invoked with i=100
Hello main
• When the reference is passed to a method, the parameter that receives refer to
the same object.
boolean equalTo(Account a) {
return(acc == a.acc && name == a.name);
}
}
BITS Pilani, Pilani Campus
Passing Objects - Example
class TestAccount{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit");
Account a2=new Account(832345,"Ankit");
Account a3=new Account(832346,"Shobit");
}}
Output:
a1==a2: true
a1==a3: false
a1.name="Aankit";
Output:
a1.display();
a1==a2: true
a2.display(); a1==a3: false
832345 Aankit 0.0
}} 832345 Ankit 0.0
boolean equalTo(Account a) {
return(acc == a.acc && name == a.name);
}
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
Assigning Object Reference
class second{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit");
Account a2= a1;
Account a3=new Account(832346,"Shobit");
System.out.println("a1==a2:" + a2.equalTo(a1));
System.out.println("a1==a3:" + a3.equalTo(a1));
a1.name="Aankit";
Output:
a1.display();
a1==a2: true
a2.display(); a1==a3: false
}} 832345 Aankit 0.0
832345 Aankit 0.0
‘This’ Keyword
‘this’ Keyword
• Six usage
• this can be used to refer current class instance variable.
• this can be used to invoke current class method (implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance from the method.
void display(){
System.out.println(acc+" "+name+" "+amount);}
} BITS Pilani, Pilani Campus
Constructor Chaining -
Example
class Account{
int acc;
String name;
float amount;
Account(int acc, String name){
this.acc = acc;
this.name = name;}
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
Constructor Chaining -
Example
class TestAccount{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit",5000);
a1.display();
}}
}}
Output:
832345 Shobit 0.0
832346 Aankit 5000.0
832346 Aankit 5000.0
class TestAccount{
public static void main(String args[]){
Account a1=new Account(832345,"Ankit");
}
}
BITS Pilani, Pilani Campus
Returning Objects using this
keyword
class Account{
int acc;
String name;
float amount;
Account(int acc,String name){
this.acc = acc;
this.name = name; }
Account update(int act,String aname, float amt) {
acc = act;
name = aname;
amount = amt;
return this; }
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
Returning Objects using this
keyword
class TestAccount{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit");
a1.display();
a1 = a1.update(832346, "Aankit", 5000);
a1.display();
}}
String s2 = "JAVA";
s1 = s1 + "J2EE";
s1.concat("J2EE");
String s2=s1.concat("J2EE");
}
}
• A parameterized constructor
• No setters
• To not have option to change the value of the instance variable
int getAcc(){
return acc;}
String getName() {
return name; }
float getAmount() {
return amount; }}
BITS Pilani, Pilani Campus
Immutable Class - Example
class TestAccount{
public static void main(String[] args) {
a.amount = 1000;
}}
Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
The final field Account.amount cannot be
assigned
Command Line
Arguments
Command Line Arguments
class Account{
int acc;
String name;
float amount;
Account(int act,String aname){
acc = act;
name = aname;
}
}}
Array of Objects
Array of Objects
class Account{
int acc;
String name;
float amount;
void insert(int acc,String name,float amt){
this.acc = acc;
this.name = name;
this.amount = amt;
}
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
for(int i=0;i<3;i++)
{
a[i]= new Account();
a[i].insert(Integer.parseInt(args[3*i]), args[3*i+1], Float.parseFloat(args[3*i+2]));
a[i].display();
}
Output:
}}
111 abc 1000.0
222 bcd 2000.0
333 cde 5000.0
I/O Streams
Stream
class Account{
int acc;
String name;
float amount;
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
class TestAccount{
public static void main(String[] args) throws IOException{
• Solution ?
sr.nextLine();
System.out.println("Enter the name");
String name; Console:
name = sr.nextLine(); Enter the account no
111
System.out.println("Enter the amount"); Enter the name
Float amount; Ankit Tiwari
amount = sr.nextFloat(); Enter the amount
5000
a.insert(acc, name, amount); 111 Ankit Tiwari 5000.0
a.display();
sr.close(); }} BITS Pilani, Pilani Campus
Other differences
‘Super’ Keyword
Immediate parent class instance
variable
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
BITS Pilani, Pilani Campus
Invoke parent class method
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
BITS Pilani, Pilani Campus
Invoke parent class constructor
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
void addInterest() {
float interest = getBalance()*this.interest /100;
deposit(interest);
}
}
System.out.println("Initial: "+sa.getBalance());
sa.deposit(1000);
System.out.println("After Deposit: " + sa.getBalance());
sa.addInterest();
System.out.println("Deposit+Interest: " + sa.getBalance());
sa.withdraw(6000);
System.out.println("After Withdraw: " + sa.getBalance()); }}
Method Overriding
What is Overriding?
System.out.println("Initial: "+ca.getBalance());
ca.deposit(1000);
ca.withdraw(2000);
ca.deposit(6000);
System.out.println("After three Transactions: " + ca.getBalance());
ca.deductFee();
‘Final’ Keyword
Java Final Keyword
• Prevents Inheritance
Example 1: Example 2:
class first{ class first{
final int i;
public static void main(String i=10 // Error
args[]){ first(){
final int i; i=10;
i=10; }
} System.out.println("s1: "+new
} first().i);
}
}
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
BankAccount ba;
if (yr==1)
ba = new BankAccount(111,"Ankit",5000);
else
ba = new CheckingAccount(111,"Ankit",5000);
ba.deposit(1000);
ba.withdraw(2000);
ba.deposit(6000);
System.out.println("After three Transactions: " + ba.getBalance());
ba.deductFee(); //ERROR
}}
void deductFee()
{
}
• Instantiation of an array
• arr = new int[size];
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
public static void arraycopy(Object src, int srcPos,Object dest, int destPos, int length)
System.arraycopy(a, 1, b, 0, a.length-1);
for(int i=0;i<b.length;i++)
System.out.print(" "+b[i]);
Output:
350
for(int i=0;i<a.length;i++)
Output:
System.out.print(a[i]+" "); 235147
[1, 2, 3, 5, 4, 7]
System.out.println(); [1, 2, 3, 4, 5, 7]
Arrays.sort(a,0,4); Binary Search for 5 is 4
System.out.println(Arrays.toString(a));
Arrays.sort(a);
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(Arrays.copyOf(a, a.length)));
System.out.println(Arrays.toString(Arrays.copyOfRange(a, 1,4)));
Arrays.fill(a,4,a.length,1); Output:
System.out.println(Arrays.toString(a)); [1, 2, 3, 4, 5, 7]
[2, 3, 4]
[1, 2, 3, 4, 1, 1]
Arrays.fill(a,1);
[1, 1, 1, 1, 1, 1]
System.out.println(Arrays.toString(a));
class first{
public static void main(String args[]){
2f410acf
zero a = new zero(); a
System.out.println(a);
a.i =10;
a.j=20;
}
}
Output:
System.out.println(a[1].length); [[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5]]
2
Interfaces
Interface
Interfaces
Default Methods in Interface
(defender or virtual extension)
• Before Java 8, interfaces could have only abstract
methods. Implementation is provided in a separate class
Nested Classes
Inner Classes
• Member
• Anonymous
• Local
• Static nested class
Packages
Create a package & sub
package
Project New
Package
Package New
class
package class2.sub;
Packages
Create a package & sub
package
Project New
Package
Package New
class
package class2.sub;
Down casting
Downcasting
Strings
Strings
• String(char[] char_arr)
• String(char[] char_array, int start_index, int count)
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
String Methods
Length and Append
• String toLowerCase()
• Converts all characters to lower case
• String toUpperCase()
• Converts all characters to upper case
• String trim()
• Returns the copy of the String, by removing whitespaces at both ends. It does
not affect whitespaces in the middle.
s1 = "Hello World";
s2 = "World";
System.out.println(s1.endsWith(s2));
s1 = "HellO World";
s2 = "hello";
System.out.println(s1.regionMatches(1, s2, 1,
4));
s1 = "Hello World";
s2 = “World";
System.out.println(s1.contains(s2));
BITS Pilani, Pilani Campus
Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
Importing a class
String Buffer
StringBuffer Constructors
Constructor Description
public StringBuffer() create an empty StringBuffer
create a StringBuffer with initial room
public StringBuffer(int capacity)
for capacity number of characters
create a StringBuffer containing the
public StringBuffer(String str)
characters from str
String Tokenizer
String Tokenizer
}
BITS Pilani, Pilani Campus
String Tokenizer - Example
import java.util.StringTokenizer;
public class Test{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name/ is \t khan \n");
int i=0,j;
j = st.countTokens();
while (st.hasMoreTokens()) {
System.out.println(st.nextToken("/"));
Output:
i++; my name
} is khan
System.out.println("i: "+i+"and j: "+j);
System.out.println( st.countTokens()); i: 2and j: 4
} 0
}
Output:
abc,def,ghi
Output:
abc
Output:
abc
+
def
:
ghi
Wrapper Classes
Wrapper Class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing and
Unboxing (Java 5)
Wrapper Class & Boxing -
Example
int a = 50;
Integer i = Integer.valueOf(60); Output:
Integer j = a; // auto boxing -1
System.out.println(j.compareTo(i));
#0: http
#1: www.java.com
#2: strings
#0: http
#1: www.java.com/strings
#0: http
#1:
#2: www.java.com
#3: strings
sb.ensureCapacity(10);
System.out.println(sb.capacity());
Output:
45
sb.ensureCapacity(50);
45
System.out.println(sb.capacity()); 92
Generics (J2SE 5)
Generic Class
class Test {
public static void main (String[] args) {
class Test {
public static void main (String[] args) {
Identity <String, Integer> I1 = new Identity<String,
Integer>("Ankit",20171007);
Identity <Integer,String> I2 = new
Identity<Integer,String>(20171007,"Ankit");
I1.printObject();
I2.printObject();
}}
BITS Pilani, Pilani Campus
Generic Functions
class Identity {
public <T> void printObject(T obj) {System.out.println(obj); }
}
class Test {
public static void main (String[] args) {
Identity I1, I2;
I1 = new Identity();
I2 = new Identity();
I1.printObject(20071007);
I2.printObject("Ankit");
}
}
class Test {
public static void main (String[] args) {
Identity I1, I2;
I1 = new Identity();
I2 = new Identity();
System.out.println(I1.printObject(20071007));
System.out.println(I2.printObject("Ankit"));
}
}
Collections
What are Collections
T - Type
E - Element
K - Key
N - Number
V – Value
System.out.println(al);
System.out.println(Arrays.toString(s));
Comparable Interface
Comparable Interface
al.add(new Account(111,"Ankit",5000));
al.add(new Account(112,"Ashok",4000));
al.add(new Account(123,“Ryan",5000));
Collections.sort(al);
for(Account a:al)
System.out.println(a);
}
}
Comparator Interface
Comparator Interface
class Account{
int acc;
String name;
float amt;
Account(int acc,String name,float amt){
this.acc = acc;
this.name = name;
this.amt = amt; }
public String toString() {
return "Acc. No.: "+acc+" Name: "+name+" Amount: "+amt;}
}
al.add(new Account(123,"Ankit",5000));
al.add(new Account(112,"Ashok",4000));
al.add(new Account(111,"Ryan",5000));
System.out.println("Comparison on Amount");
Collections.sort(al,new AmtCmp());
for(Account a:al)
System.out.println(a);
class test {
public static void main(String[] args) {
List<Account> al = new ArrayList<Account>();
al.add(new Account(111,"Ryan",5000));
al.add(new Account(112,“Ryan",5000));
al.add(new Account(111,"Ryan",5000));
System.out.println(al.get(0).equals(al.get(2)));
System.out.println(al.get(0).equals(al.get(1))); }
} BITS Pilani, Pilani Campus
Multiple Bounds in Generics
public class test {
public static void main(String[] args) {
System.out.printf("Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ));
System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));
System.out.printf("Max of %s,%s and %s is %s\n\n",
"s", "j", "r", maximum( "s", "j", "r" ));
}
public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
T max = x;
if(y.compareTo(max) > 0) { Output:
max = y; } Max of 3, 4 and 5 is 5
Max of 6.6,8.8 and 7.7 is 8.8
if(z.compareTo(max) > 0) {
Max of s,j and r is s
max = z; }
return max; }
} BITS Pilani, Pilani Campus
Multiple Bounds in Generics
public class test {
public static void main(String[] args) {
System.out.printf("Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ));
System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));
System.out.printf("Max of %s,%s and %s is %s\n\n",
"s", "j", "r", maximum( "s", "j", "r" ));
}
public static <T extends Number & Comparable<T>> T maximum(T x, T
y, T z) {
T max = x; Error:
if(y.compareTo(max) > 0) { The method maximum(T, T, T)
max = y; } in the type test is not
applicable for the arguments
if(z.compareTo(max) > 0) {
(String, String, String)
max = z; }
return max; } } BITS Pilani, Pilani Campus
Text File I/O
Text Files and Binary Files
Files that are designed to be read by human beings,
and that can be read or written with an editor are
called text files
Text files can also be called ASCII files because the data
they contain uses an ASCII encoding scheme
An advantage of text files is that the are usually the same
on all computers, so that they can move from one computer
to another
Text Files and Binary Files
Files that are designed to be read by programs and
that consist of a sequence of binary digits are called
binary files
Binary files are designed to be read on the same type of
computer and with the same programming language as the
computer that created the file
An advantage of binary files is that they are more efficient
to process than text files
Unlike most binary files, Java binary files have the
advantage of being platform independent also
outStream.close( );
}
}
Writing to a Text File
When a program is finished writing to a file, it should
always close the stream connected to that file
outputStreamName.close();
This allows the system to release any resources used to
connect the stream to the file
If the program does not close the file before the program
ends, Java will close it automatically, but it is safest to
close it explicitly
IOException
When performing file I/O there are many situations in which an
exception, such as FileNotFoundException, may be thrown
Many of these exception classes are subclasses of the class
IOException
The class IOException is the root class for a variety of
exception classes having to do with input and/or output
These exception classes are all checked exceptions
Therefore, they must be caught or declared in a throws clause
Catching IOException
public class TextFileOutputDemo
{
public static void main(String[] args)
{
PrintWriter outStream = null;
interface B {
public void displayClass(); }
class A implements B{
public void displayClass() {
System.out.println("Inside class A"); }
} BITS Pilani, Pilani Campus
Multiple Bounds in Generics
class C implements B {
public void displayClass() {
Note:
System.out.println("Inside class C "); } The type passed to the
} class should be of sub
type class A and should
public class test { have implemented
interface B
public static void main(String a[]) {
//Creating object of sub class A and
//passing it to Bound as a type parameter.
Bound<A> bea = new Bound<A>(new A());
bea.doRunTest();
}
}
Coming back to
Collections
ArrayList
ArrayList Vector
There are no synchronized methods. All methods are synchronized.
No Thread safe: Multiple threads can Thread safe: Only one thread is
access the array list at the same allowed to operate on vector object
time. at a time.
It increases the waiting time of
Threads are not required to wait and threads (since all the methods are
hence performance is high synchronized) and hence
performance is low
Method Description
public E push(E item); Pushes the item on top of the stack
public synchronized E pop(); Removes the item at the top of the stack
and returns that item
public synchronized E peek(); Returns the item at the top of the stack
public boolean empty(); Checks whether stack is empty or not
public synchronized int search Returns the position of an object in the
(Object o); stack.
Set Interface
Set Interface
• The Java Set does not provide control over the position
of insertion or deletion of elements.
Map Interface
Map Interface
LinkedHashMap – maintains
insertion order
Method Description
Object getKey() It is used to obtain key.
Object getValue() It is used to obtain value.
• It maintains no order.
• LinkedHash Map
• Tree Map
• Hashtable
AWT
Abstract Window Toolkit
Event Classes:
• The root of the event class hierarchy is the EventObject
class which contains two methods
• getSource() - returns the source of the event
• toString() – returns the string equivalent of the event
adjustmentValueChanged(Adjustment
AdjustmentListener addAdjustmentListener() AdjustmentEvent
Event)
b.addActionListener(this);
BITS Pilani, Pilani Campus
AWT Event Handling -
Example
setSize(1000,1000);
setBackground(Color.cyan);
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{
test t= new test();
}
l = new Label();
l.setBounds(100,50,170,30);
l.setBackground(Color.green);
BITS Pilani, Pilani Campus
Event Handling by an External
Class-Example
add(b);
add(tf);
add(l);
setSize(1000,1000);
setBackground(Color.cyan);
setLayout(null);
setVisible(true); }
public static void main(String[] args) {
test t= new test(); }
}
BITS Pilani, Pilani Campus
Event Handling by an External
Class-Example
class AHandler implements ActionListener,TextListener{
test obj;
AHandler(test t){
this.obj = t;
}
public void textValueChanged(TextEvent e) {
obj.l.setText("Entered text: " + obj.tf.getText());
}
tf.addTextListener(new TextListener() {
public void textValueChanged(TextEvent E) {
l.setText("Entered text: " + tf.getText());
}
});
• paint(): Override the paint method to display output in the window. This method is
called by the run time system.
• repaint(): Invoke the repaint method if the program needs output to be displayed.
Awt program cannot call the paint method directly.
• System.exit(): When the top level window is closed, it does not cause the
program to terminate. It is necessary to handle the window-close event through a
System.exit() call.
test(){
addMouseListener(this);
setSize(300,300);
setLayout(null);
setVisible(true); }
test(){
addKeyListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);
setBackground(Color.cyan); }
test()
{
setSize(400,400);
setVisible(true);
l=new Label();
l.setBounds(20,50,200,20);
l.setBackground(Color.cyan);
add(l);add(area);
}
public static void main(String[] args)
{
new test();
}
} BITS Pilani, Pilani Campus
Screen Shot
b[0]=(Button) f.add(y);
b[1]=(Button) f.add(n);
b[2]=(Button) f.add(m);
for(int i = 0;i<3;i++)
{
b[i].setBounds(100,100+i*50,100,30);
} BITS Pilani, Pilani Campus
Handling Buttons
for(int i =0;i<3;i++)
{
b[i].addActionListener(this);
}
tf.setBackground(Color.cyan);
tf.setBounds(100,250,200,30);
f.add(tf);
f.setSize(300,300);
f.setVisible(true);
}
Layout Manager
Need for Layout Manager