You are on page 1of 41

Table of Contents

1. 2. 3. 4. 5. 6. 7. 8. 9. Features of Java.......................................................................................... JVM (Java Virtual Machine) ......................................................................... Class ........................................................................................................ Object ...................................................................................................... Data types in Java ....................................................................................... Object Oriented Programming Language (OOPS) .............................................. Inheritance ................................................................................................ Polymorphism (One name many forms) ........................................................... Encapsulation ............................................................................................

3 3 3 4 4 4 4 5 6 6 6 6 7 7 8 9 9

10. First Program ............................................................................................ 11. Compiling and Running the Program .............................................................. 12. Naming Conventions (Traditions) in Java ......................................................... 13. Modifiers .................................................................................................. 14. final ......................................................................................................... 15. static ........................................................................................................ 16. Scope of Variables ....................................................................................... 17. abstract ....................................................................................................

18. Package ...................................................................................................10 19. visibility ...................................................................................................11 20. Constructors .............................................................................................12 21. this .........................................................................................................12 22. super .......................................................................................................12 23. Destructors ...............................................................................................13 24. Interfaces .................................................................................................13 25. String Class ..............................................................................................14 26. Methods of String

......................................................................................14

27. Arrays .....................................................................................................15 28. Javadoc ...................................................................................................15

BASIC JAVA
29. Command Line Arguments ..........................................................................15 30. Wrapper Classes ........................................................................................15 31. Input/Output ............................................................................................16 32. Create an abstract class Area and use this class for calculating the area of Rectangle and Circle. .....................................................................................................16 33. Create an Interface Area and use this interface for calculating the area of Rectangle and Circle. .....................................................................................................17 34. Take the input of marks of three students for three subjects and generate a report. ...18 35. Applets ....................................................................................................20 36. Life Cycle of an Applet ................................................................................20 37. Hierarchy of Applet ....................................................................................21 38. Write an Applet Program to set the Background color to Red and Display a Text .....21 39. Some of the methods used in Applets ..............................................................22 40. Passing parameters to Applet ........................................................................22 41. Playing music through applet ........................................................................22 42. awt (Abstract Windowing Toolkit) .................................................................23 43. Layout .....................................................................................................23 44. Events Handled in awt

................................................................................25

45. Adapter Classes .........................................................................................27 46. Create a program Payroll by using awt ........................................................27 47. Menu Bar .................................................................................................29 48. Check Box ................................................................................................31 49. Radio Button

............................................................................................31

50. List .........................................................................................................32 51. Choice .....................................................................................................32 52. Popup Menu .............................................................................................32 53. Mouse Events ............................................................................................32 54. Example of using PopupMenu and Mouse Event ...............................................33 55. Dialog ......................................................................................................34 56. Example of using Dialog ..............................................................................34

Ajeeth Kumar

Page 2 of 41

BASIC JAVA

OAK This language was developed to connect all the Electronic Gadgets. 1995 Java was developed with the caption Write Once Run Anywhere Anytime.

1. Features of Java
Simple Language No Pointers. Highly secure No Virus. Platform Independent Run across different Operating Systems. Architecturally Neutral does not depend on particular machine architecture. 100% Object Oriented. Distributed Language Task to be performed among more than one machine. (RMI Remote Method Invocation). Internet Programming using Applets. Multithreaded Program Part of a process in execution. GUI (Graphical User Interface) based Application.

2. JVM (Java Virtual Machine)

.class files

Class Loader

Byte Code Verifier

Interpreter

Executed
JIT (Just In Time) Compiler Keeps the copy of the machine code in buffer. JNI (Java Native Interface) Java makes a call to the other languages method.

3. Class
Class is the logical structure. Class contains fields (data) and methods (code). eg. class add { int a1 = 10; //field int a2 = 20; //field int sum() //method { return (a1 + a2); } }

Ajeeth Kumar

Page 3 of 41

BASIC JAVA
4. Object
Object is the actual existence of the class.

5. Data types in Java


Primitive i. byte ii. short iii. int iv. long v. float vi. double vii. char viii. Boolean Non-Primitive i. Arrays ii. class 1 2 4 8 4 8 2 (supports international languages) 1 bit

6. Object Oriented Programming Language (OOPS)


Inheritance Polymorphism Encapsulation

7. Inheritance
Single

Base Class

Derived Class

Multiple Java does not support this type of Inheritance

Base Class C D

E
Multilevel

Derived Class

Base Class

Derived Class

Derived Class

Ajeeth Kumar

Page 4 of 41

BASIC JAVA
Hybrid Supported if it is either single and/or multilevel.

Base Class

Derived Class

Derived Class
eg. class A { --} class B extends A { --} //Inheritance is done through extends.

8. Polymorphism (One name many forms)


Operator Overloading i. Not supported by Java ii. But Java internally overloads the + operator for concatenation and addition. Function Overloading i. Methods should differ by their signature ii. Should not differ in return type. iii. Should differ in number of parameters. iv. Should differ in type of parameters. v. Should differ in order or sequence of parameters.

eg., class A { void show() { --} void show(int a, int b) { --} }

Ajeeth Kumar

Page 5 of 41

BASIC JAVA
Function Overriding
The method that is defined in the base class can be redefined in the derived class. When a call is made to this method, then the method in the derived class is being called. For overriding to happen the method that is to be overridden should be of the same signature.

eg.,
class A { void show() { --} void show(int a, int b) { --} } class B extends A { void show() { --} } The method of class B is called in the above example if there is a call to show() function inside main.

9. Encapsulation
Binding of data and the code, which operates on the data. No use if only the fields or the code are their without both.

10. First Program


//save this as First.java (File name should be same as the class containing the main method) class First { public static void main(String args[]) { System.out.println("First Program"); } }

11. Compiling and Running the Program


Set the path Environment variable as c:\jdk1.3\bin; Compile javac First.java Running java First Execution in Java begins from main

12. Naming Conventions (Traditions) in Java


Class First letter in capitals. (eg. class Car) If there are two words then first letter of both words in capitals. (eg. class MyCar)

Ajeeth Kumar

Page 6 of 41

BASIC JAVA
Fields Start with lowercase. (eg. int total) If there are two words then first word in lowercase and the first letter of the second word in Capitals. (eg. int myTotal)

Method Start with lowercase. (eg. void show()) If there are two words then first word in lowercase and the first letter of the second word in Capitals. (eg. void myShow()) Constants The complete word is in capitals. (eg. final float PI=3.14f;) Package Start with lowercase. (eg. package ajeeth;) If there are two words then first word in lowercase and the first letter of the second word in Capitals. (eg. package myAjeeth;) Interface First letter in capitals. (eg. interface Car) If there are two words then first letter of both words in capitals. (eg. interface MyCar)

13. Modifiers
Modifiers modify the usual way something behaves. There are four types of modifiers, they are final static abstract visibility

14. final
Modifying as final is nothing but declaring as constant. Prevents overriding if method is modified as final.

class A { final void show() { --} } class B extends A { void show() { --} }

// overriding not allowed as show() is modified as final in the base class

Ajeeth Kumar

Page 7 of 41

BASIC JAVA
Prevents Inheritance if class is modified as final.

final class A { void show() { --} } class B extends A //Inheritance not allowed as class A is modified as final. { --} Prevents Fields (variables) to change value if it is modified as final.

class A { final int A = 10; void show() { A = 20; //Value for this field cannot be changed as it is modified as final. } }

15. static
If a method is modified as static then only static fields can be accessed directly and non-static fields can be accessed only by instantiating its object first and then making a call to it indirectly.

class A { int a = 10; static int b = 100; static int display() { A obj = new A(); obj.show(); return obj.a; } void show() { System.out.println(b); } } Class Variables (Class Fields) Cannot be used as reference to any object but can be accessed directly in the same class or has to be accessed as class.field (A.b) in other classes.

//show(); will not work //return a; will not work

//static field can be accessed by non-static method.

Ajeeth Kumar

Page 8 of 41

BASIC JAVA
class A { int a = 10; static int b = 100; public static void main (String arg[]) { System.out.println(a); //static method cannot access non-static field System.out.println(b); A obj1 = new A(); a = 20 A obj2 = new A(); obj 1 obj1.a = 20; obj2.a = 30; b = 100 } } class B { }

Static field does not depend on the instance objects

obj 2

a = 30

A.b; //need not create an instance to access the static field (class variable) of class A.

16. Scope of Variables


class A { int a = 10; //Global for the class void show() { int b = 20; //Global only within this method. } void display() { --} }

17. abstract
abstract method does not have body but ends with a semicolon. eg., abstract void show(); If a class has one or more abstract methods then the class should be declared abstract. abstract class can also have instance methods. eg., abstract class A { abstract void show(); void display() //Instance method { --} } Reference variable of an abstract class can refer to the object variable of its subclass. A class that extends the abstract class should declare all the abstract methods of the class or else that class should be declared as abstract.

Ajeeth Kumar

Page 9 of 41

BASIC JAVA
eg., abstract class Tree { abstract void leaf(); abstract void fruit(); void photosynthesis() { --} } class MangoTree extends Tree { void leaf() { --} void fruit() { --} } class AppleTree extends Tree { void leaf() { --} void fruit() { --} } The abstract methods are defined by the subclasses of the abstract class.

18. Package
Package is a collection of related classes and interfaces. By default lang package is imported in all Java program by default. Below are some of the commonly used packages net (networking classes) Socket, ServerSocket, etc. lang (basic classes) System, String, etc. awt (abstract windowing toolkit) Button, Label, etc. sql (query of databases) Connection, Resultset, etc.i import (loads the class to the memory) is used to import a package. Creating a package with class A. Save this file as A.java package ajeeth; class A { --}

Ajeeth Kumar

Page 10 of 41

BASIC JAVA
Compile this package and put it into a folder called ajeeth No main method needed for the classes in the package. Set the classpath environment variable to the folder ajeeth. This package can be used by importing import ajeeth.*; If the class in the package has the same name as the user defined class, then user define class will be overridden.

19. visibility
This modifier is also called as the Access Specifier. There are four visibility modifiers, they are public private protected default Given below are the contents of two packages, ajeeth and kumar. package ajeeth class A {

Same Package

package kumar import ajeeth.*;

Different Package

int a = 10; void show() { --} } class B extends A { --} class C { } Modifiers Same class Same package Sub class Same package Non sub class Diff. package Sub class Diff. Package Non sub class private Y N N N N protected Y Y N Y (Provided the class is declared public) N

class D extends A Sub class { --} class E {

Non-sub class
---

Sub class

Non-sub class
--default Y Y Y N N public Y Y Y Y Y

Class can be modified as public or default only. Constructors can be modified as public or default only.

Ajeeth Kumar

Page 11 of 41

BASIC JAVA
20. Constructors
eg., class A { A () { } A (String str) //Parameterized Constructor { --} } //Empty Constructor --Special methods that have the same name as that of the class name. Invoked only when object is created. Initialization of the member fields is done through constructors. Has no return type. Constructors can be modified as public or default only. Constructors can be overloaded. Two types of constructors Empty and Parameterized.

21. this
class A { int a; A (int a) { this.a = a; //sets the value of member a to 100. } } class B { public static void main (String arg[]) { A obj = new A(100); } }

22. super
class A { int a = 20; } class B extends A { int a;

Ajeeth Kumar

Page 12 of 41

BASIC JAVA
B (int a) { this.a = super.a; //this refers to a of class B, super refers to a of class A } }

23. Destructors
No Concept of destructors in Java. Still Java takes care of memory freeing by using the Garbage Collector Software that runs periodically. If this software finds a piece of code without reference, then it will free the memory.

24. Interfaces
Interfaces are pure abstract classes. Has no instance method. Interface must have abstract methods only. Interface also creates a class file after compilation. Interface can have fields declared (by default all the fields are public final & static) Relationship between class and interface is through implements. All the methods of the interface should be declared in the sub-class. Declare all the abstract methods as public in the implemented class. Cannot create an instance of the interface. Reference variable of an interface can refer to the object of a class that has implemented that interface. Multiple inheritance is possible through interface but not through classes. Class can extend only one class but can implement any number of interfaces.

interface A { int TOTAL = 100; //By default the field is public static final abstract void show1(); } abstract class B implements A { --} class C { --} class D { public static void main (String arg[]) { A ref1 = new B(); A ref2 = new C(); //This is not possible since C does not implement A. } }

Ajeeth Kumar

Page 13 of 41

BASIC JAVA
Inheritance in Interfaces interface A { int TOTAL = 100; abstract void show1(); } interface B { abstract void show2(); } interface C extends A, B //Multiple Inheritance { abstract void show3(); } class D implements C { //show1(), show2(), show3() should be declared as public or //else class should be abstract] } Difference between Interface and Abstract Class Abstract class can have one or more instance methods but interface can have only abstract methods. Thread Class Thread class internally uses the Runnable interface. For creating a class MyFrame which extends both Frame and Thread, Frame class has to be extended and the Thread (Runnable) class has to be implemented since Java does not support multiple inheritance for class. eg., class MyFrame extends Frame implements Runnable.

25. String Class


Available in lang package. Creating a String object. String obj1 = new String(Hello); (or) String obj2 = Hello //This provision is provided only for String

26. Methods of String


Compares for equal if (obj1.equals(obj2)) //True if both are equal. { --} else { --} Compares for equal but ignores case if (obj1.equalsIgnoreCase(obj2)) Concatenation String obj3 = obj1 + obj2;

Ajeeth Kumar

Page 14 of 41

BASIC JAVA
Conversion to uppercase String obj3 = obj2.toUpperCase(); Conversion to lowercase String obj3 = obj2.toLowerCase(); Character at Obj2.charAt(int index);

27. Arrays
Collection of homogeneous data types. Syntax dt var[ ] = new dt[size]; eg., int ar[ ] = new int[10]; String str[ ] = new String[5]; Accessing the array elements for (int i=0; i < ar.length; i++) { ar[i] = i; System.out.println(ar[i]); } Initialization udt obj[ ] = new udt[10]; obj[0] = new udt(); String str[0] = Hello; String str[1] = new String(Hello);

28. Javadoc
Contains the list of all packages, list of all classes, list of all methods and fields.

29. Command Line Arguments


class A { public static void main(String s[ ]) { int i = Integer.parseInt(s[0]); //Integer is a wrapper class int j = Integer.parseInt(s[1]); System.out.println(value of i = + i + value of j = + j); } } > java A 10 20 output:value of i = 10 value of j = 20

30. Wrapper Classes


A wrapper class wraps the value inside the constructor. eg., Primitive datatypes Wrapper Classes byte Byte int Integer

Ajeeth Kumar

Page 15 of 41

BASIC JAVA
31. Input/Output
System.out.print(Hello); System is a class in lang package. out is a static field of System class of printStream data type. print is a method of PrintStream class which is in io package. For reading input from the console BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); The above statement takes input from console and stores into buffer br. This throws IOException, so have to handle it. io package has to be imported before using the BufferedReader class import java.io.*; eg., String name = br.readLine(); //for reading a String data from console int mark = Integer.parseInt(br.readLine); //for reading a int data from console If String is inputed instead of integer then NumberFormatException is thrown System.in.read(); Will read only one character from the console.

32. Create an abstract class Area and use this class for calculating the area of Rectangle and Circle.

Calc.java
import java.io.*; abstract class Area //abstract class Area { int radius; int length, breadth; int result; abstract void area(); } class Rectangle extends Area { void area() { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); try { System.out.println("Enter Length and breadth of a rectangle"); length = Integer.parseInt(br.readLine()); breadth = Integer.parseInt(br.readLine()); result = 2 * (length + breadth); System.out.println("Area of the rectangle = " + result); } catch (IOException ioe) //because BufferedReader throws IOException { } } }

Ajeeth Kumar

Page 16 of 41

BASIC JAVA
class Circle extends Area { void area() { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); try { System.out.println("Enter radius of a circle"); radius = Integer.parseInt(br.readLine()); result = 3.14 * radius * radius; System.out.println("Area of the Circle = "+ result); } catch (IOException ioe) { } } }

class Calc { public static void main(String args[]) { Circle cir = new Circle(); cir.area(); Rectangle rec = new Rectangle(); rec.area(); } }

33. Create an Interface Area and use this interface for calculating the area of Rectangle and Circle.

CalcInt.java
import java.io.*; interface Area { float PI=3.14f; abstract void area(); } class Rectangle implements Area { float length,breadth, result; public void area() { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); try { System.out.println("Enter Length and breadth of a rectangle"); length = Float.parseFloat(br.readLine()); breadth = Float.parseFloat(br.readLine()); result = 2 * (length + breadth); System.out.println("Area is =" + result); } catch (IOException ioe)

Ajeeth Kumar

Page 17 of 41

BASIC JAVA
{ } } } class Circle implements Area { float radius, result; public void area() { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); try { System.out.println("Enter radius of a circle"); radius = Float.parseFloat(br.readLine()); result = Area.PI * radius * radius; System.out.println("Area is ="+ result); } catch (IOException ioe) { } } } class CalcInt { public static void main(String args[]) { Circle cir = new Circle(); cir.area(); Rectangle rec = new Rectangle(); rec.area(); } }

34. Take the input of marks of three students for three subjects and generate a report.

Reports.java
import java.io.*; class Students { String name; String rollno; int mathsMark; int scienceMark; int englishMark; int total; String result; void getinfo() { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); try {

Ajeeth Kumar

Page 18 of 41

BASIC JAVA
System.out.print("Enter the students name: "); name = br.readLine(); System.out.println(); System.out.print("Enter the Roll Number: "); rollno = br.readLine(); System.out.println(); System.out.print("Enter the mark in Maths: "); mathsMark = Integer.parseInt(br.readLine()); System.out.println(); System.out.print("Enter the mark in Science: "); scienceMark = Integer.parseInt(br.readLine()); System.out.println(); System.out.print("Enter the mark in English: "); englishMark = Integer.parseInt(br.readLine()); } catch (IOException ioe) { } } void processinfo() { total = mathsMark + scienceMark + englishMark; if (mathsMark >40 && scienceMark >40 && englishMark >40 && total >150) result = "PASS"; else result = "FAIL"; } void genreport() { System.out.println("|" + name + "\t\t|" + rollno + "\t\t|" + mathsMark + "\t|" + scienceMark + "\t|" + englishMark + "\t|" + total + "\t|" + result + " |"); } } class Reports { public static void main(String arg[]) throws IOException { Students s[ ] = new Students[3]; for (int i=0; i<=2; i++) { s[i]=new Students(); s[i].getinfo(); s[i].processinfo(); } System.out.println("|========================================== ===============================|"); System.out.println("|Name |RollNo |M1 |M2 |M3 |Total |Result |"); for (int i=0; i<=2; i++) { System.out.println("|------------------------------------------------------------------------|");

Ajeeth Kumar

Page 19 of 41

BASIC JAVA
s[i].genreport(); } System.out.println("|========================================== ===============================|"); } }

35. Applets
Java programs are written and hosted on the Web Server (serves HTML pages). Applet cannot exist itself it needs a browser window for execution. eg., MyApplet.html <HTML> <BODY> <H1> Hello Applet </H1> //control goes to JVM for execution when Applet keyword is seen. Browser should be Java //enabled for running the applet program. The browser executes rest of the code. <applet code=MyApplet.class width=100 height=100> </applet> //codebase attribute should be specified if the HTML file & .class file are in different paths <H1> End of Applet </H1> </BODY> </HTML> MyApplet.java import java.applet.*; public class MyApplet extends Applet { }

36. Life Cycle of an Applet

Born init() paint() start() Running

Applet instance is created Called only once in the life cycle Automatically called by init() method stop() start() Not Running Temporarily Idle

destroy()

destroy()

Dead

Instance is deleted from memory

Ajeeth Kumar

Page 20 of 41

BASIC JAVA
For transforming from one state to another some of these methods are used. public void init() public void start() public void stop() public void destroy() paint() method will be called for drawing or painting the applet. paint() method is the method in the Component class. This method will be called automatically to display in the browser.

37. Hierarchy of Applet

Object

lang Package

Component

awt Package

Container

awt Package

Panel

awt Package

Applet

applet Package

38. Write an Applet Program to set the Background color to Red and Display a Text
import java.awt.*; //awt package should be included if paint method is to be used import java.applet.*; public class MyApplet1 extends Applet { String str = null; public void init() //overriding the init() method of Applet class { str = Hello Applet; setBackground (Color.red); //Color is a class and red is a static variable //customization of Color can be done as below. //setBackground(new Color(45, 34, 45)); //RBG } public void paint(Graphics g) //Graphics is an abstract class in awt package { g.drawstring (str, 10, 10); } }

Ajeeth Kumar

Page 21 of 41

BASIC JAVA
39. Some of the methods used in Applets
Changing the font type, style and size Font f = new Font(String fontName, int style, int size) g.setFont(f); eg., Font f = new Font(Times New Roman, Font.BOLD, 16) Setting the color of font g.setColor(Color.red) Drawing Rectangle g.drawRect(x, y, w, h); Drawing Rectangle with white color filled in it. g.setColor(Color.white); g.fillRect(100,100,50,50); Drawing Oval g.drawOval(x, y, w, h); Drawing Line g.drawLine(x, y, w, h); Drawing Polygon int x[ ] = {x1, x2, x3}; int y[ ] = {y1, y2, y3}; g.drawPolygon(x, y, x.length); //x.length is used to get the number of points

40. Passing parameters to Applet


Part of HTML File <applet ----> <parma name=ibm value =ajeeth> </applet> Part of Applet Program public void init() { String val = getParameter(ibm); }

41. Playing music through applet


For playing the music, AudioClip interface that is present in the applet package is used. This interface has methods like loop(), stop(), play() etc. public class MyMusic extends Applet { AudioClip ac = null; public void init() { ac = getAudioClip(getDocumentBase(), spacemusic.au); //getDocumentBase is the URL obj //---.au is the String obj, should be in the same directory } public void start()

Ajeeth Kumar

Page 22 of 41

BASIC JAVA
{ ac.play(); //or ac.loop(); } public void destroy() { ac.stop(); } }

42. awt (Abstract Windowing Toolkit)

Object

Component

Container

Panel

Window

Applet
Examples of the Components are Button, Label, TextComponent(TextField, TextArea), CheckBox etc. Examples of Window are Frame, Dialog.

43. Layout
The way the Components are arranged in the Container. Default layout for Panel & Applet is FlowLayout. Default layout for Frame and Dialog is BorderLayout. Any Container must contain a layout. There are different types of layouts. FlowLayout Varying size Components are placed from Left to Right and then Top to Bottom.

1 4

2 5

3 6

Ajeeth Kumar

Page 23 of 41

BASIC JAVA
BorderLayout This can have only 5 layouts they are North, South, West, East and Center but can have other layouts using the panel.

N W C S
GridLayout Number of equal sized grids

GridbagLayout Similar to Grid but the components can span to specified number of cells. Gridbag constraints supporting class has fields like gridX, gridY, gridWidth, gridHeight

1 4

Example of placing a button (1) on a GridbagLayout Panel p = new Panel (); Button b1 = new Button (); GridbagLayout gbl = new GridbagLayout(); GridbagConstraints gbc = new GridbagConstraints(); gbc.gridX = 0; gbc.gridY = 0; gbc.gridWidth = 3; gbc.gridHeight = 1; p.setLayout (gbl); gbl.setConstraints (gbc, b1); //check this out CardLayout More than one panel of same size placed one over the other on the frame. This layout is used basically for saving space.

p1 p2 p1
Ajeeth Kumar

mp
When p1 button is pressed then the panel p1 will be shown on mp panel. Page 24 of 41

p3 p2 p3

BASIC JAVA
Sample code CardLayout cl = new CardLayout (); Panel mp = new Panel (); mp.setLayout (cl); Panel p1 = new Panel (one); ------mp.add (p1);

44. Events Handled in awt

Label

Test Box

Close Option at Frame Level

LISTENER EVENT (in this case Event is click) SOURCE Button is the Source Button Test Box (Task Bar)
Types of Events ActionEvent for Button ItemEvent for CheckBox, List, Choice (Combo Box) MouseEvent for Mouse WindowEvent for Window Types of Listeners (in-built interfaces) The corresponding Listeners for the above events are as follows. ActionListener ItemListener MouseListener WindowListener Sample Program for creating the above screen that accepts password and validates the same MyFrame.java import java.awt.*; import java.awt.event.*; class MyFrame extends Frame implements ActionListener { // Only one method (actionPerformed) for this Listener class Label lb1 = null; Button b1 = null; Button b2 = null; Button b3 = null; TextField tf1, tf2 = null;

Password Clear OK Exit

Ajeeth Kumar

Page 25 of 41

BASIC JAVA
MyFrame() //constructor { setSize(400,400); //Lables, Buttons and Text Boxes created as shown in diagram above. lb1 = new Label("Password"); b1 = new Button("OK"); b2 = new Button("EXIT"); b3 = new Button("CLEAR"); tf1 = new TextField(15); tf1.setEchoChar('*'); //Set password text box to display * for all keys pressed tf2 = new TextField(20); setLayout(new FlowLayout()); //set FlowLayout //Adding all the created components to Frame add(lb1); add(tf1); add(b1); add(b2); add(b3); add(tf2); //Registering the Source with the Listener //Syntax component.addListenerclass (Listenerclass obj); b1.addActionListener(this); //this is used because MyFrame class implements Listener Class b2.addActionListener(this); b3.addActionListener(this); //Registering the Source with the Listener this.addWindowListener(new MyWinClose()); //This will make all the Components visible setVisible(true); } public void actionPerformed (ActionEvent ae) { if(ae.getSource() == b1) //finding the Source { String val = tf1.getText(); if (val.equals("Ajeeth")) { tf2.setText("VALID USER"); } else { tf2.setText("INVALID USER"); } } else if(ae.getSource() == b2) { System.exit(0); } else if(ae.getSource() == b3) { tf1.setText(""); tf2.setText(""); } }

Ajeeth Kumar

Page 26 of 41

BASIC JAVA
public static void main(String arg[]) { new MyFrame(); } //This class is written for enabling the Close option at Frame Level //WindowListener interface has actually 6 methods but since only 1 method needs to be //used, the Adapter Class (WindowAdapter) has to be used for this. //This class is defined inside the MyFrame class, called the Inner Class class MyWinClose extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } }

45. Adapter Classes


Adapter classes are helper classes. For example, the WindowAdapter internally implements WindowListener.

46. Create a program Payroll by using awt


Payroll.java import java.awt.*; import java.awt.event.*; class Payroll extends Frame implements ActionListener { Label lb1 = null; Label lb2 = null; Label lb3 = null; Label lb4 = null; Label lb5 = null; Label lb6 = null; Label lb7 = null; Label lb8 = null; Label lb9 = null; Label lb10 = null; Label lb11 = null; Label lb12 = null; Label lb13 = null; Label lb14 = null; Label lb15 = null; Button b1 = null; Button b2 = null; Button b3 = null; TextField tf1 = null; TextField tf2 = null; Payroll() //Constructor {

Ajeeth Kumar

Page 27 of 41

BASIC JAVA
setSize(430,250); lb1 = new Label("NAME"); lb2 = new Label("Basic"); lb3 = new Label("HRA"); lb4 = new Label(" "); lb5 = new Label("Con. Allowance"); lb6 = new Label(" "); lb7 = new Label("FBP"); lb8 = new Label(" "); lb9 = new Label("Deductions"); lb10 = new Label("Professional Tax"); lb11 = new Label(" "); lb12 = new Label("Provident Fund"); lb13 = new Label(" "); lb14 = new Label("Total"); lb15 = new Label(" "); b1 = new Button("GENERATE REPORT"); b2 = new Button("EXIT"); b3 = new Button("CLEAR"); tf1 = new TextField(30); tf2 = new TextField(6); setLayout(new FlowLayout()); add(lb1); add(tf1); add(lb2); add(tf2); add(lb3); add(lb4); add(lb5); add(lb6); add(lb7); add(lb8); add(lb9); add(lb10); add(lb11); add(lb12); add(lb13); add(lb14); add(lb15); add(b1); add(b2); add(b3); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); this.addWindowListener(new MyWinClose()); setTitle("PAYROLL"); setResizable(false); setVisible(true); } public void actionPerformed(ActionEvent ae) { if(ae.getSource() == b1) { int val = Integer.parseInt(tf2.getText());

Ajeeth Kumar

Page 28 of 41

BASIC JAVA
float hra = 0.7f * val; lb4.setText(Float.toString(hra)); lb6.setText("800"); float fbp = (0.5f * val) - 800; lb8.setText(Float.toString(fbp)); lb11.setText("200"); float pf = .012f * val; lb13.setText(Float.toString(pf)); float total = val + hra + 800 + fbp - 200 - pf; lb15.setText(Float.toString(total)); } else if(ae.getSource() == b2) { System.exit(0); } else if(ae.getSource() == b3) { tf1.setText(""); tf2.setText(""); lb4.setText(""); lb6.setText(""); lb8.setText(""); lb11.setText(""); lb13.setText(""); lb15.setText(""); } } public static void main(String arg[]) { new Payroll(); } class MyWinClose extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } }

47. Menu Bar


Frame Menu Bar Menu Item

Color
Red Blue Gree

Ajeeth Kumar

Page 29 of 41

BASIC JAVA
MenuBar mb = new MenuBar(); Menu m1 = new Menu (Color); MenuItem mi1 = new MenuItem(Red); MenuItem mi2 = new MenuItem(Blue); MenuItem mi3 = new MenuItem(Green); m1.add (mi1); m1.add (mi2); m1.add (mi3); setMenuBar (mb); Sample Program for creating the above screen, which changes background color as per the menu choices MyMenuBar.java import java.awt.*; import java.awt.event.*; class MyMenuBar extends Frame implements ActionListener { MenuBar mb = null; Menu m1, m2 = null; MenuItem m11,m12, m13, m21 = null; MyMenuBar() { setSize(400,400); mb = new MenuBar(); m1 = new Menu("Color"); m11 = new MenuItem("Red"); m12 = new MenuItem("Blud"); m13 = new MenuItem("Green"); m2 = new Menu("Exit"); m21 = new MenuItem("Close"); m1.add(m11); m1.add(m12); m1.add(m13); m2.add(m21); mb.add(m1); mb.add(m2); setMenuBar(mb); setLayout(new FlowLayout()); m11.addActionListener(this); m12.addActionListener(this); m13.addActionListener(this); m21.addActionListener(this); this.addWindowListener(new MyWinClose()); setVisible(true); } public void actionPerformed(ActionEvent ae) { if (ae.getSource() == m11) { this.setBackground(Color.red); }

Ajeeth Kumar

Page 30 of 41

BASIC JAVA
else if (ae.getSource() == m12) { this.setBackground(Color.blue); } else if (ae.getSource() == m13) { this.setBackground(Color.green); } else if (ae.getSource() == m21) { System.exit(0); } } public static void main(String arg[]) { new MyMenuBar(); } class MyWinClose extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } }

48. Check Box


CheckBox cb1 = new CheckBox (Cricket, true); //If true is specified, by default Cricket is selected. CheckBox cb2 = new CheckBox (Football); cb1.getState() // If it returns true, then CheckBox is selected. Event used for CheckBox is ItemEvent and Listener used is ItemListener. There is only one method for this Interface, itemStateChanged. public void itemStateChanged (ItemEvent ie) { if (ie.getItemSelectable() = cb1) { --} }

Hobbies Cricket Football

49. Radio Button

Radio Buttons are nothing but group of CheckBoxs CheckBoxGroup gender = new CheckBoxGroup(); CheckBox male = new CheckBox (Male, gender, true); CheckBox female = new CheckBox (Female, gender, false); CheckBoxGroup category = new CheckBoxGroup(); CheckBox senior = new CheckBox(Senior Citizen, category, false); CheckBox citizen = new CheckBox(Citizen, category, false);

Gender Male Female

Catagor Senior Citizen Citizen

Ajeeth Kumar

Page 31 of 41

BASIC JAVA
Add only the CheckBox but not the CheckBoxGroup. To find out whether male in gender group is selected, gender.getSelectedCheckBox() == male

50. List

A B

List l = new List (); //No Multiple selection, all the C // elements are shown by default D List l = new List (4, true); //Only 4 elements are visible at a time and multiple //selection is possible. //adding elements to the List l.add (A); l.add (B); To find out the selected item (if Only one item is selected) If (l.getSelectedItem ().equals (A)) { --} Multiple Selected Items String item[] = l.getSelectedItems(); Any one of ItemListener or ActionListener can be used for List.

51. Choice
//Only one element can be selected at a time. Choice c = new Choice(); c.add (A); To find out the selected item c.getSelectedItem() //returns String c.getSelectedIndex() //returns Interger.

52. Popup Menu


PopupMenu pm = new PopupMenu(); MenuItem mi1 = new MenuItem(); MenuItem mi2 = new MenuItem(); MenuItem mi3 = new MenuItem(); pm.add(mi1); pm.add(mi2); pm.add(mi3); Method used to show PopupMenu on the frame pm.show(this, x, y) //x and y are the co-ordinates of Mouse Pointer.

53. Mouse Events


public void mousePressed (MouseEvent me) { if (me.getModifier() == 4) //If right mouse button is pressed. { pm.show(MyFrame, me.getX(), me.getY()); } }

Ajeeth Kumar

Page 32 of 41

BASIC JAVA
54. Example of using PopupMenu and Mouse Event
MyPopupMenu.java import java.awt.*; import java.awt.event.*; class MyPopupMenu extends Frame implements ActionListener { PopupMenu pm = null; MenuItem m11,m12, m13 = null; static MyPopupMenu fr = null; MyPopupMenu() { setSize(400,400); pm = new PopupMenu(); m11 = new MenuItem("Red"); m12 = new MenuItem("Blud"); m13 = new MenuItem("Green"); pm.add(m11); pm.add(m12); pm.add(m13); add(pm); setLayout(new FlowLayout()); m11.addActionListener(this); m12.addActionListener(this); m13.addActionListener(this); this.addWindowListener(new MyWinClose()); this.addMouseListener(new MyMousePressed()); setVisible(true); } class MyMousePressed extends MouseAdapter { public void mousePressed(MouseEvent me) { if(me.getModifiers() == 4) { pm.show(fr,me.getX(),me.getY()); } } } public void actionPerformed(ActionEvent ae) { if (ae.getSource() == m11) { this.setBackground(Color.red); } else if (ae.getSource() == m12) { this.setBackground(Color.blue);

Ajeeth Kumar

Page 33 of 41

BASIC JAVA
} else if (ae.getSource() == m13) { this.setBackground(Color.green); } } public static void main(String arg[]) { fr = new MyPopupMenu(); } class MyWinClose extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } }

55. Dialog
Dialog is not independent as a frame. Dialog requires the frame to be the parent container. Dialog can contain all the components that a frame can have.

56. Example of using Dialog


import java.awt.*; import java.awt.event.*; class MyFrameDia extends Frame implements ActionListener { Label lb1 = null; Button b1 = null; Button b2 = null; Button b3 = null; TextField tf1, tf2 = null; MyFrameDia() { setSize(400,400); lb1 = new Label("Password"); b1 = new Button("OK"); b2 = new Button("EXIT"); b3 = new Button("CLEAR"); tf1 = new TextField(15); tf1.setEchoChar('*'); tf2 = new TextField(20); setLayout(new FlowLayout()); add(lb1); add(tf1); add(b1); add(b2); add(b3); add(tf2);

Ajeeth Kumar

Page 34 of 41

BASIC JAVA
b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); this.addWindowListener(new MyWinClose()); setVisible(true); } public void actionPerformed(ActionEvent ae) { if(ae.getSource() == b1) { String val = tf1.getText(); MyDia md = new MyDia(this, "Dialog"); if (val.equals("Ajeeth")) { tf2.setText("VALID USER"); md.dl1.setText("VALID USER"); } else { tf2.setText("INVALID USER"); md.dl1.setText("INVALID USER"); } } else if(ae.getSource() == b2) { System.exit(0); } else if(ae.getSource() == b3) { tf1.setText(""); tf2.setText(""); } } public static void main(String arg[]) { new MyFrameDia(); } class MyWinClose extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } } class MyDia extends Dialog implements ActionListener { Label dl1 = null; Button db1 = null; MyDia(Frame obj, String title) {

Ajeeth Kumar

Page 35 of 41

BASIC JAVA
super(obj, title); //calling the super class Dialog. dl1 = new Label(); db1 = new Button("OK"); setLayout(new FlowLayout()); add(dl1); add(db1); db1.addActionListener(this); this.addWindowListener(new MyDiaWinClose()); setSize(200, 200); setVisible(true); } public void actionPerformed(ActionEvent ae) { if(ae.getSource() == db1) { setVisible(false); } } class MyDiaWinClose extends WindowAdapter { public void windowClosing(WindowEvent we) { setVisible(false); } } }

57. Handling Errors with Exceptions


Errors occur in software programs. But what really matters is what happens after the error occurs. How is the error handled? Who handles it? Can the program recover, or should it just die? Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Many kinds of errors can cause exceptions--problems ranging from serious hardware errors, such as a hard disk crash, to simple programming errors, such as trying to access an out-of-bounds array element. When such an error occurs within a Java method, the method creates an exception object and hands it off to the runtime system. The exception object contains information about the exception, including its type and the state of the program when the error occurred. The runtime system is then responsible for finding some code to handle the error. In Java terminology, creating an exception object and handing it to the runtime system is called throwing an exception. After a method throws an exception, the runtime system leaps into action to find someone to handle the exception. The set of possible "someones" to handle the exception is the set of methods in the call stack of the method where the error occurred. The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until it finds a method that contains an appropriate exception handler. An exception handler is considered appropriate if the type of the exception thrown is the same as the type of exception handled by the handler. Thus the exception bubbles up through the call stack until an appropriate handler is found and one of the calling methods handles the exception. The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all of the methods on the call stack without finding an appropriate exception handler, the runtime system (and consequently the Java program) terminates.

Ajeeth Kumar

Page 36 of 41

BASIC JAVA
By using exceptions to manage errors, Java programs have the following advantages over traditional error management techniques: Advantage 1: Separating Error Handling Code from "Regular" Code Advantage 2: Propagating Errors Up the Call Stack Advantage 3: Grouping Error Types and Error Differentiation Advantage 1: Separating Error Handling Code from "Regular" Code In traditional programming, error detection, reporting, and handling often lead to confusing spaghetti code. For example, suppose that you have a function that reads an entire file into memory. In pseudocode, your function might look something like this: readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } At first glance this function seems simple enough, but it ignores all of these potential errors: What happens if the file can't be opened? What happens if the length of the file can't be determined? What happens if enough memory can't be allocated? What happens if the read fails? What happens if the file can't be closed? To answer these questions within your read_file function, you'd have to add a lot of code to do error detection, reporting and handling. Your function would end up looking something like this: errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else {

Ajeeth Kumar

Page 37 of 41

BASIC JAVA
errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; } With error detection built in, your original 7 lines (in bold) have been inflated to 29 lines of code--a bloat factor of almost 400 percent. Worse, there's so much error detection, reporting, and returning that the original 7 lines of code are lost in the clutter. And worse yet, the logical flow of the code has also been lost in the clutter, making it difficult to tell if the code is doing the right thing: Is the file really being closed if the function fails to allocate enough memory? It's even more difficult to ensure that the code continues to do the right thing after you modify the function three months after writing it. Many programmers "solve" this problem by simply ignoring it--errors are "reported" when their programs crash. Java provides an elegant solution to the problem of error management: exceptions. Exceptions enable you to write the main flow of your code and deal with the, well, exceptional cases elsewhere. If your read_file function used exceptions instead of traditional error management techniques, it would look something like this: readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } Note that exceptions don't spare you the effort of doing the work of detecting, reporting, and handling errors. What exceptions do provide for you is the means to separate all the grungy details of what to do when something out-of-the- ordinary happens from the main logic of your program. In addition, the bloat factor for error management code in this program is about 250 percent--compared to 400 percent in the previous example. Advantage 2: Propagating Errors Up the Call Stack A second advantage of exceptions is the ability to propagate error reporting up the call stack of methods. Suppose that the readFile method is the fourth method in a series of nested method calls

Ajeeth Kumar

Page 38 of 41

BASIC JAVA
made by your main program: method1 calls method2, which calls method3, which finally calls readFile. method1 { call method2; } method2 { call method3; } method3 { call readFile; } Suppose also that method1 is the only method interested in the errors that occur within readFile. Traditional error notification techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1--the only method that is interested in them. method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; } As you learned earlier, the Java runtime system searches backwards through the call stack to find any methods that are interested in handling a particular exception. A Java method can "duck" any exceptions thrown within it, thereby allowing a method further up the call stack to catch it. Thus only the methods that care about errors have to worry about detecting errors. method1 { try { call method2; } catch (exception) { doErrorProcessing; }

Ajeeth Kumar

Page 39 of 41

BASIC JAVA
} method2 throws exception { call method3; } method3 throws exception { call readFile; } However, as you can see from the pseudo-code, ducking an exception does require some effort on the part of the "middleman" methods. Any checked exceptions that can be thrown within a method are part of that method's public programming interface and must be specified in the throws clause of the method. Thus a method informs its callers about the exceptions that it can throw, so that the callers can intelligently and consciously decide what to do about those exceptions. Note again the difference in the bloat factor and code obfuscation factor of these two error management techniques. The code that uses exceptions is more compact and easier to understand. Advantage 3: Grouping Error Types and Error Differentiation Often exceptions fall into categories or groups. For example, you could imagine a group of exceptions, each of which represents a specific type of error that can occur when manipulating an array: the index is out of range for the size of the array, the element being inserted into the array is of the wrong type, or the element being searched for is not in the array. Furthermore, you can imagine that some methods would like to handle all exceptions that fall within a category (all array exceptions), and other methods would like to handle specific exceptions (just the invalid index exceptions, please). Because all exceptions that are thrown within a Java program are first-class objects, grouping or categorization of exceptions is a natural outcome of the class hierarchy. Java exceptions must be instances of Throwable or any Throwable descendant. As for other Java classes, you can create subclasses of the Throwable class and subclasses of your subclasses. Each "leaf" class (a class with no subclasses) represents a specific type of exception and each "node" class (a class with one or more subclasses) represents a group of related exceptions. For example, in the following diagram, ArrayException is a subclass of Exception (a subclass of Throwable) and has three subclasses. Exception

ArrayException

InvalidIndexException

NoSuchElementException

ElementTypeException

Ajeeth Kumar

Page 40 of 41

BASIC JAVA
InvalidIndexException, ElementTypeException, and NoSuchElementException are all leaf classes. Each one represents a specific type of error that can occur when manipulating an array. One way a method can catch exceptions is to catch only those that are instances of a leaf class. For example, an exception handler that handles only invalid index exceptions has a catch statement like this: catch (InvalidIndexException e) { ... } ArrayException is a node class and represents any error that can occur when manipulating an array object, including those errors specifically represented by one of its subclasses. A method can catch an exception based on its group or general type by specifying any of the exception's superclasses in the catch statement. For example, to catch all array exceptions regardless of their specific type, an exception handler would specify an ArrayException argument: catch (ArrayException e) { ... } This handler would catch all array exceptions including InvalidIndexException, ElementTypeException, and NoSuchElementException. You can find out precisely which type of exception occurred by querying the exception handler parameter e. You could even set up an exception handler that handles any Exception with this handler: catch (Exception e) { ... } Exception handlers that are too general, such as the one shown here, can make your code more error prone by catching and handling exceptions that you didn't anticipate and therefore are not correctly handled within the handler. We don't recommend writing general exception handlers as a rule. As you've seen, you can create groups of exceptions and handle exceptions in a general fashion, or you can use the specific exception type to differentiate exceptions and handle exceptions in an exact fashion.

Ajeeth Kumar

Page 41 of 41

You might also like