Anda di halaman 1dari 87

Java Programming Laboratory BCA504P

Introduction Features Of Java


Java was conceived by James Gosling, Patrick Naughton, Chris Wrath, Ed Frank and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version.This language was initially called Oak but was renamed Java in 1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, many more people contributed to the design and evolution of the language. Bill Joy, Arthur van Holf, Jonathan Payne, Frank Yelin and Tim Lindholm were key contributors to the maturing of the original prototype. Java is an Object Oriented Programming language like C++. It is a portable language and hence was propelled to the forefront of computer language design by the World Wide Web. Features of Java Simple Object-Oriented Distributed Interpreted Robust Secure Architecture-neutral Portable High performance 1

Dept. of Computer Science 2010-2011

Java Programming Laboratory BCA504P Dynamic Byte Code Multithreaded

Simple Java has basically inherited the C/C++ syntax and many of the

object-oriented features of C++. Moreover some of the more confusing concepts from C++ are either left out of Java or implemented in a cleaner, more approachable manner. Error prone tasks such as pointers and memory management have either been eliminated or are handled by the Java environment automatically rather than by the programmer Object-Oriented Java was not designed to be source-code compatible with any other language. This allowed the Java team the freedom to design with a blank slate. One outcome of this was a clean, usable, pragmatic approach to objects. Borrowing liberally from many seminal object-software environments of the last few decades, Java manages to strike a balance between the purists "everything is an object" paradigm and the pragmatist's "stay out of my way" model. The object model in Java is simple and easy to extend, while simple types, such as integers are kept as high performance non-objects. Even though Java has the look and feel of C++, it is a wholly independent language, which has been designed to be object-oriented from the ground up. In object-oriented programming (OOP), data is treated as objects to which methods are applied. Java's basic execution unit is the class. Advantages of OOP include reusability of code, extensibility and dynamic applications. Everything in java is an object, even the primitive data types can also be converted into object by using the wrapper class. The Three OOP Principles Dept. of Computer Science 2010-2011 2

Java Programming Laboratory BCA504P All object-oriented programming languages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, and polymorphism. Encapsulation Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. Inheritance Inheritance is the process by which one object acquires the properties of another object. Polymorphism Polymorphism (from the Greek, meaning "many forms") Interface to be used for a general class of actions. More generally, the concept of polymorphism is often expressed by the phrase "one interface multiple methods" This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler's job to select the specific action (that is, method) as it applies to each situation. Distributed Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different from accessing a file. The original version of Java (Oak) included features for intra address space messaging. This allowed objects on two different computers to execute procedures remotely. Java has recently revived these interfaces in a package called Remote Method Invocation (RMI). This feature brings an unparalleled level of abstraction to client/server programming.

Dept. of Computer Science 2010-2011

Java Programming Laboratory BCA504P Interpreted Java enables the creation of cross platform programs by compiling into an intermediate representation called Java Byte code. This code can be interpreted on any system that provides a Java Virtual Machine. The Java Virtual Machine does not exist physically but is the specification for a hypothetical processor that can run Java code. The byte code is then run through a Java interpreter on any given Robust The multi platform environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given high priority in the design of Java. Java compels the programmer to be thorough. It carries out type checking at both compile and runtime making sure that every data structure has been clearly defined and typed. Java manages memory automatically by using an automatic garbage collector. The garbage collector runs as a low priority thread in the background keeping track of all objects and references to those objects in a Java program. When an object has no more references, the garbage collector tags it for removal and removes the object either when there is an immediate need for more memory or when the demand on processor cycles by the program is low. . Because Java is a strictly typed language, it checks your code at compile time. However, it also checks your code at run time. Secure Java provides a "firewall" between a networked application and your computer. When you use a Java-compatible Web browser, you can safely download Java applets without fear of viral infection or malicious intent. Java achieves this protection by confining a Java program to the Java execution environment and not allowing it access to other parts of the computer. The Java language has built-in capabilities to ensure that Dept. of Computer Science 2010-2011 4

Java Programming Laboratory BCA504P violations of security do not occur. Consider a Java program running on a workstation on a local area network, which in turn is connected, to the Internet. Being a dynamic and distributed computing environment, the Java program can, at runtime, dynamically bring in the classes it needs to run either from the workstation's hard drive, other computers on the local area network or a computer thousands of miles away somewhere on the Internet. This ability of classes or applets to come from unknown locations and execute automatically on a local computer sounds like every system administrator's nightmare considering that there could be lurking out there on one of the millions of computers on the Internet, some viruses, trojan horses or worms which can invade the local computer system and wreak havoc on it. Java goes to great lengths to address these security issues by putting in place a very rigorous multilevel system of security. First and foremost, at compile time, pointers and memory allocation are removed thereby eliminating the tools that a system breaker could use to gain access to system resources. Memory allocation is deferred until runtime. Even though the Java compiler produces only correct Java code, there is still the possibility of the code being tampered with between compilation and runtime. Java guards against this by using the byte code verifier to check the byte code for language compliance when the code first enters the interpreter, before it gets the chance to run the byte code verifier ensures that the code does not do any of the following:

Forge pointers Violate access restrictions Incorrectly access classes Overflow or underflow operand stack Use incorrect parameters of byte code instructions 5

Dept. of Computer Science 2010-2011

Java Programming Laboratory


BCA504P Use illegal data conversions

At runtime, the Java interpreter further ensures that classes loaded do not access the file system except in the manner permitted by the client or the user.

Architecture-Neutral A central issue for the Java designers was that of code longevity

and portability. One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow even on the same machine. Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction. The Java designers made several hard decisions in the Java language and the Java Virtual Machine in an attempt to alter this situation. Their goal was "Write Once Run Anywhere Any Time Forever." To a great extent, this goal was accomplished Portability Many types of computers and operating systems are in use throughout the worldand many are connected to the Internet. For programs to be dynamically downloaded to all the various types of platforms connected to the Internet, some means of generating portable executable code is needed. Java provides a mechanism of generating portable executable code. By porting an interpreter for the Java Virtual Machine to any computer hardware/operating system, one is assured that all code compiled for it will run on that system. This forms the basis for Java's portability. Another feature, which Java employs in order to guarantee portability, is by creating a single standard for data sizes irrespective of processor or operating system platforms. High Performance Most previous attempts at cross platform solutions have done so at the expense of performance. Java, however, was designed to perform well on very lowpower CPUs. Even though Java was engineered for interpretation, the Java Byte code was Dept. of Computer Science 2010-2011 6

Java Programming Laboratory BCA504P carefully designed so that it would be easy to translate directly into native machine code for very high performance by using a just-in-time compiler. Java run-time systems that provide this feature lose none of the benefits of the platform-independent code. "High Performance Cross Platform" is no longer a dream The Java language supports many high-performance features such as multithreading, just in time compiling and native code usage. Java has employed multithreading to help overcome the performance problems suffered by interpreted code as compared to native code. Since an executing program hardly ever uses CPU cycles 100 % of the time, Java uses the idle time to perform the necessary garbage cleanup and general system maintenance that renders traditional interpreters slow in executing applications. [NB: Multithreading is the ability of an application to execute more than one task (thread) at the same time e.g. a word processor can be carrying out spell check in one document and printing a second document at the same time.]

Since the byte code produced by the Java compiler from the corresponding source code is very close to machine code, it can be interpreted very efficiently on any platform. In cases where even greater performance is necessary than the interpreter can provide, just-in-time compilation can be employed whereby the code is compiled at run-time to native code before execution.

An alternative to just-in-time compilation is to link in native C code. This yields even greater performance but is more burdensome on the programmer and reduces the portability of the code

Dynamic Java programs carry with them substantial amounts of run-time

type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner. This is crucial to Dept. of Computer Science 7 2010-2011

Java Programming Laboratory BCA504P the robustness of the applet environment, in which small fragments of Byte code may be dynamically updated on a running system. By connecting to the Internet, a user immediately has access to thousands of programs and other computers. During the execution of a program, Java can dynamically load classes that it requires either from the local hard drive, from another computer on the local area network or from a computer somewhere on the Internet. Byte Code The key that allows Java to solve both the security and the portability is that the output of a Java compiler is not executable code. Rather, it is Byte code. Byte code is a highly optimized set of instructions, which can be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). JVM is an interpreter for Byte code. As you know, C++ is compiled to executable code. In fact, most modern languages are designed to be compiled and not interpretedmostly because of performance concerns. Translating a Java program into byte code helps makes it much easier to run a program in a wide variety of environments, only the JVM needs to be implemented for each platform. The execution of every Java program is under the control of the JVM, the JVM can contain the program and prevent it from generating side effects outside of the system. Multithreaded Java was designed to meet the real-world requirement of creating interactive, networked programs. To accomplish this, Java supports multithreaded

programming, which allows you to write programs that do many things simultaneously. The Java run-time system comes with an elegant yet sophisticated solution for multiprocessing synchronization that enables you to construct smoothly running interactive systems. Java's easy-to-use approach to multithreading allows you to think about the specific behavior of your program, and not about the multitasking subsystem. In multithreaded programs not Dept. of Computer Science 8 2010-2011

Java Programming Laboratory BCA504P even a single thread disturbs the execution of other thread. Threads are obtained from the pool of available ready to run threads and they run on the system CPUs.

Hints:
1.Use javac for compiling the *.java files (E.g., D:\Meena\javac Program.java). 2. Use java fro interpreting the *.class files (E.g., D:\Meena\java Program) 3. If you wan to create your own directory and create *.java files there you need to set the path to the jdk folder in order for you to compile and execute your files there. Go to your created folder and set the path as follows. D:\Meena\set path=c:\program files\java\jdk1.5\bin

Command-Line Arguments
Java Application can accept any number of arguments directly from the command line. The user can enter command-line arguments when invoking the application. The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. While running the program any things written after the name of the class are the command line arguments. Arguments are delimited by the space. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt, a user would enter: java Sort friends.txt When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of Strings. In the

Dept. of Computer Science 2010-2011

Java Programming Laboratory BCA504P previous example, the command-line arguments passed to the Sort application in an array that contains a single String: "friends.txt".

/* 1. Program to find the factorial of a list of numbers using command line arguments */
import java.io.*; class Refact { public static int fact(int n) { int i,f1=1; for(i=1;i<=n;i++)
Dept. of Computer Science 2010-2011 10

Java Programming Laboratory BCA504P

f1=f1*i; return (f1); } public static void main(String args[]) { int i,n,f,x,m; x=args.length; for(i=0;i<x;i++) { n=Integer.parseInt(args[i]); m=n; f=fact(n); System.out.println("Factorial of "+m+" is : "+f); } } }

Output:

Dept. of Computer Science 2010-2011

11

Java Programming Laboratory BCA504P

Dept. of Computer Science 2010-2011

12

Java Programming Laboratory BCA504P

/* 2. Program to display all prime numbers between two limits */


import java.io.*; class Prime { public static void main(String a[]) throws IOException { int l,u,i; boolean x; DataInputStream din=new DataInputStream(System.in); System.out.println("ENTER THE LOWER LIMMITT"); l=Integer.parseInt(din.readLine()); System.out.println("ENTER THE UPPER LIMMITT"); u=Integer.parseInt(din.readLine()); System.out.println(" \n PRIME NOS..."); while(l<2)l++; for(i=l;i<=u;i++) { x=met(i); if(x) System.out.println(i); } System.out.println(" THANK YOU " ); } static boolean met(int n) {
Dept. of Computer Science 2010-2011 13

Java Programming Laboratory BCA504P

boolean flag=true; int i; for(i=2;i<n;i++) if (n%i==0) { flag=false; break; } return(flag);

Dept. of Computer Science 2010-2011

14

Java Programming Laboratory BCA504P

Output:

Dept. of Computer Science 2010-2011

15

Java Programming Laboratory BCA504P

Exception Handling
An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support exception handling, errors must be checked and handled manuallytypically through the use of error codes, and so on. Java's exception handling avoids these problems and, in the process, brings run-time error management into the object-oriented world

A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object caused the error representing that exception is created and thrown in the method that

This method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed. Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment.

Java exception handling is managed via five keywords try catch throw throws finally

Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your Dept. of Computer Science 2010-2011 16

Java Programming Laboratory BCA504P code can catch this exception (using catch) and handle it in some rational manner. Systemgenerated exceptions are automatically thrown by the Java runtime system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed before a method returns is put in a finally block.

Using try and catch It can be used to make an user to handle exceptions on his own.

This has two benefits. First, it allows you to fix the error. Second, it prevents the program from automatically terminating. To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch Multiple catch Clauses In some cases, more than one exception could be raised by a single piece of code. To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block. Nested try Statements The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement's catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all Dept. of Computer Science 17 2010-2011

Java Programming Laboratory BCA504P of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception. throw It is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here: throw ThrowableInstance; There are two ways you can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method's declaration. A throws clause lists the types of exceptions that a method might throw. finally When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the normal flow through the method. The finally keyword is designed to address this contingency. finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception.

Dept. of Computer Science 2010-2011

18

Java Programming Laboratory BCA504P

/* 3. Program to sort the list of numbers in ascending & descending order and show the exception handling */
import java.io.*; class Excep { public static void main(String args[])throws IOException { int num[] = new int[5]; int n,temp,j,i;float x; DataInputStream din = new DataInputStream(System.in); System.out.println("ENTER THE NO.. OF ELEMENTS"); System.out.println("ENTER GREATER THAN 5 TO CHECK ARRAY INDEX OUT OF BOUND EXCEPTION"); n=Integer.parseInt(din.readLine()); try { System.out.println("ENTER THE ELEMENTS"); for(i=0;i<n;i++) { num[i]=Integer.parseInt(din.readLine()); } System.out.println("LIST OF GIVEN NO.. "); for(i=0;i<n;i++) System.out.println(num[i]); for(i=0;i<n;i++) for(j=0;j<n;j++)
Dept. of Computer Science 2010-2011 19

Java Programming Laboratory BCA504P

if(num[i]>num[j]) { temp=num[i]; num[i]=num[j]; num[j]=temp; } System.out.println("LIST OF SORTED NOS.."); //Descending order................ System.out.println("Descending order"); for(i=0;i<n;i++) System.out.println(num[i]); //Ascending order................ System.out.println("Ascending order"); for(i=n-1;i>=0;i--) System.out.println(num[i]); System.out.println("\nARITHMETIC EXCEPTION"); System.out.println("ENTER THE A VALUE"); float a=Integer.parseInt(din.readLine()); System.out.println("ENTER THE B VALUE = 0 TO GET EXCEPTION"); float b=Integer.parseInt(din.readLine()); x=(a/b); System.out.println(x); } catch(ArithmeticException ar) {
Dept. of Computer Science 2010-2011 20

Java Programming Laboratory BCA504P

System.out.println("ARITH-EXCEPTION TERMINATED"+ar); } catch(ArrayIndexOutOfBoundsException ac) { System.out.println("AIOBE-Exception Terminated"+ac); } finally { System.out.println("REACHED EOP ... THANK YOU"); } } }

Dept. of Computer Science 2010-2011

21

Java Programming Laboratory BCA504P

Output:

Dept. of Computer Science 2010-2011

22

Java Programming Laboratory BCA504P

Dept. of Computer Science 2010-2011

23

Java Programming Laboratory BCA504P

Dept. of Computer Science 2010-2011

24

Java Programming Laboratory BCA504P

/* 4. Program to implement the rhombus pattern reading the limit from the user */
import java.io.*; class Rhombus { public static void main(String args[]) throws IOException { int n,i,j,k; DataInputStream din=new DataInputStream(System.in); System.out.println("Enter the n value"); n=Integer.parseInt(din.readLine()); System.out.println("\n\tTHE OUTPUT IS"); for(i=0; i<n; i++) { for(j=0; j<n-i; j++) System.out.print(" "); for(k=0; k<=i; k++) System.out.print("* "); System.out.println(); } for(i=0; i<n-1; i++) { for(j=0; j<=i+1; j++) System.out.print(" "); for(k=n-1-i; k>0; k--) System.out.print("* ");
Dept. of Computer Science 2010-2011 25

Java Programming Laboratory BCA504P

System.out.println(); } } }

Output:

Dept. of Computer Science 2010-2011

26

Java Programming Laboratory BCA504P

String Manipulations

String represents a sequence of characters. Usually a string can be represented in java in two ways 1. By means of a character array. E.g. char name[] = new char[4]; name[0]= J; name[1]= A; name[2]= V; name[3]= A; 2. By means of using String Object In java strings are class objects and implemented using the predefined String class. A java String is an instantiated object of the string class. The String class is available in the java.lang package which is imported by default. String name; name= new String(JAVA);

String Methods
The String class defines a number of methods that allow us to accomplish a variety of string manipulation tasks.

Dept. of Computer Science 2010-2011

27

Java Programming Laboratory BCA504P

List of commonly used String Methods and their Tasks


String s1, s2; Method Call
1. 2. 3. 4.

Task Performed Converts the string s1 to all lowercase Converts the string s1 to all uppercase Replace all appearances of x with y Remove white spaces at the beginning and the Returns true if s1 is equal to s2 Returns true if s1 is equal to s2, ignoring the case Gives the length of s1 Gives the nth character of s1 Returns negative if s1<s2, positive if s1>s2 and zero Concatenates s1 and s2 Gives sub string starting from nth character Gives sub string starting from nth character up to mth Creates a string object of parameter p Creates a string representation of object p Gives the position of the first occurrence of x Gives the position of x that occurs after the nth Converts the parameter value to string

s2 = s1.toLowerCase() s2 = s1.toUpperCase() s2 = s1.replace(x,y) s2 = s1.trim() end of the string s1.equals(s2) s1.equalsIgnoreCase(s2) of characters s1.length() s1.charAt(n) s1.compareTo(s2) if s1 = s2

5. 6.

7. 8. 9.

10. s1.concat(s2) 11. s1.substring(n) 12. s1.substring(n, m)

character
13. String.ValueOf(p) 14. p.toString() 15. s1.indexOf(x)

in the string s1
16. s1.indexOf(x,n)

position in s1
17. String.ValueOf(variable)

representation

Dept. of Computer Science 2010-2011

28

Java Programming Laboratory BCA504P

/* 5. Program to implement all string operations */


import java.io.*; class Stropt { public static void main(String arg[]) throws IOException { String s1,s2; int choice;int m,n;String xx; String x,y; DataInputStream din=new DataInputStream(System.in); System.out.println("\nSTRING OPERATIONS\n"); System.out.println("1. toLowerCase"); System.out.println("2. toUpperCase"); System.out.println("3. subString"); System.out.println("4. length"); System.out.println("5. indexOf"); System.out.println("6. charAt"); System.out.println("7. replace"); System.out.println("8. equal"); System.out.println("9. trim"); System.out.println("10. EXIT"); while(true) {
Dept. of Computer Science 2010-2011 29

Java Programming Laboratory BCA504P

System.out.println(" PLEASE ENTER UR CHOICE \n"); choice=Integer.parseInt(din.readLine()); switch(choice) { case 1: System.out.println("-> toLowerCase");

System.out.println("-> \t Enter the string"); s1=din.readLine(); System.out.println("\t conv-> "+s1.toLowerCase()); break; case 2 : System.out.println("-> toUpperCase");

System.out.println("-> \t Enter the string"); s1=din.readLine(); System.out.println("\t conv-> "+s1.toUpperCase()); break; case 3: System.out.println("-> subString");

System.out.println("-> \t Enter the string"); s1=din.readLine(); System.out.println("-> \t Enter the size of substring"); m=Integer.parseInt(din.readLine()); n=Integer.parseInt(din.readLine()); System.out.println("\tSubstr-> "+s1.substring(m,n)); break; case 4: System.out.println("-> length");

System.out.println("-> \t Enter the string"); s1=din.readLine();


Dept. of Computer Science 2010-2011 30

Java Programming Laboratory BCA504P

System.out.println("\t Length-> "+s1.length()); break; case 5: System.out.println("-> indexOf");

System.out.println("-> \t Enter the string"); s1=din.readLine(); System.out.println("-> \t Enter the index char"); xx=din.readLine(); System.out.println("Index is ->\t"+s1.indexOf(xx)); break; case 6: System.out.println("-> charAt");

System.out.println("-> \t Enter the string"); s1=din.readLine(); System.out.println("-> \t Enter the char value"); m=Integer.parseInt(din.readLine()); System.out.println("char is->\t"+s1.charAt(m)); break; case 7: System.out.println("-> replace");

System.out.println("-> \t Enter the string"); s1=din.readLine(); System.out.println("-> \t Enter the replace char"); x=din.readLine(); y=din.readLine(); System.out.println("Afterreplace->\t" +s1.replace(x,y)); break; case 8:
Dept. of Computer Science 2010-2011

System.out.println("-> equal");
31

Java Programming Laboratory BCA504P

System.out.println("-> \t Enter the 1st string"); s1=din.readLine(); System.out.println("-> \t Enter the 2nd string"); s2=din.readLine(); System.out.println("Result->\t"+s1.equals(s2));break; case 9: System.out.println("-> trim");

System.out.println("-> \t Enter the string"); s1=din.readLine(); System.out.println("str1->\t"+s1.trim()); break; case 10: default: } } System.out.println(" \n\n THANK YOU "); } } System.exit(0); System.out.println("ENTER THE VALID NO..");

Dept. of Computer Science 2010-2011

32

Java Programming Laboratory BCA504P

Output:

Dept. of Computer Science 2010-2011

33

Java Programming Laboratory BCA504P

Dept. of Computer Science 2010-2011

34

Java Programming Laboratory BCA504P

Method Overloading And Constructor Overloading


In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is 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 that Java implements polymorphism. When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. In addition to overloading normal methods, we have overload constructor methods. During the process of the class instantiation a special method called constructor will be called automatically. In fact, for most real-world classes that you create, overloaded constructors will be the norm, not the exception. Characteristics of Constructors They are called only once when the class is being instantiated. They must have the same name as the class itself. They do not return a value and you do not have to specify the keyword void. A class can have more than one constructor (see the section "Method Overloading" below).

Dept. of Computer Science 2010-2011

35

Java Programming Laboratory BCA504P If you do not create a constructor for the class, Java helps you by using a so called default no-argument constructor. Constructors are usually used to assign initial values to member variables of the class

For example: class Tax { double grossIncome; // member variables String state; int dependents; Tax (double gi, String st, int depen) { grossIncome = gi; // member variable initialization state = st; dependents=depen; } ... } If a constructor with arguments has been defined in a class, you can no longer use a default no-argument constructor - you have to write one. Besides the operator new, you can create an instance of the class by loading the class first and then calling the method newInstance() which will also executes constructor's code: Dept. of Computer Science 2010-2011 36

Java Programming Laboratory BCA504P Class.forName("Tax").newInstance(); The Keyword this The keyword this is useful when you need to refer to an instance of the class from its method. Let's consider an example: class Tax { double grossIncome; Tax(double grossIncome){ this.grossIncome = grossIncome; } } The keyword this helps avoid name conflicts, for example this.grossIncome refers to a member variable grossIncome, while the grossIncome on the right refers to the argument's value.

Dept. of Computer Science 2010-2011

37

Java Programming Laboratory BCA504P

/* 6. Program to find the area of geometrical figures using methods */


import java.io.*; class Calculation { void cal(float r) { double vari=Math.PI*Math.pow(r,2); System.out.println("AREA OF CIRCLE : "+vari); } void cal(double s) { System.out.println("AREA OF SQUARE : "+Math.pow(s,2)); } void cal(float b,float h) { double vari=0.5*b*h; System.out.println("AREA OF TRIANGLE : "+vari); } void cal(double l,double br) { System.out.println("AREA OF RECTANGLE : "+(l*br)); } } class Area {
Dept. of Computer Science 2010-2011 38

Java Programming Laboratory BCA504P

public static void main(String args[])throws IOException { DataInputStream din = new DataInputStream(System.in); Calculation c=new Calculation();

System.out.println("....CIRCLE"); System.out.println("ENTER THE RADIUS :"); float r=Float.parseFloat(din.readLine()); c.cal(r);

System.out.println("....SQUARE"); System.out.println("ENTER THE SIDES :"); double s=Double.parseDouble(din.readLine()); c.cal(s);

System.out.println("....TRIANGLE"); System.out.println("ENTER THE BASE AND HEIGHT :"); float b=Float.parseFloat(din.readLine()); float h=Float.parseFloat(din.readLine()); c.cal(b,h);

System.out.println("....RECTANGLE"); System.out.println("ENTER THE LENGTH AND BREATH:"); double l=Double.parseDouble(din.readLine()); double br=Double.parseDouble(din.readLine());
Dept. of Computer Science 2010-2011 39

Java Programming Laboratory BCA504P

c.cal(l,br); System.out.println("\n THANK YOU "); } }

Output:

Dept. of Computer Science 2010-2011

40

Java Programming Laboratory BCA504P

/* 7. Program to implement constructor overloading by passing different number of parameters of different types */
import java.io.*; class Box { double width; double height; double depth; Box() { width=0;height=0;depth=0; } Box(double w,double h,double d) { width=w;height=h;depth=d; } Box(double c) { width=height=depth=c; } double volume() { return width*height*depth; } double volume(double s) {
Dept. of Computer Science 2010-2011 41

Java Programming Laboratory BCA504P

return(s*s*s); } public static void main(String args[])throws IOException { Box b1=new Box(); Box b2=new Box(10,20,15); Box b3=new Box(10); double vol; vol=b1.volume(3); System.out.println("Volume of Box1: "+vol); vol=b2.volume(); System.out.println("Volume of Box2: " + vol); vol=b3.volume(); System.out.println("Volume of Box3: " + vol); } }

Dept. of Computer Science 2010-2011

42

Java Programming Laboratory BCA504P

Output:

Dept. of Computer Science 2010-2011

43

Java Programming Laboratory BCA504P

Introduction to Applets
Java programs that support Web-Based applications are called Applets. The Applets differ from an application program in the following ways Applets require a Browser for its execution. Application programs do not require a browser Applets do not have a main() method. Most of the application programs have a main method Applets do not have access to local machines file system. Application programs have access to local machines file system

Life cycle of an Applet:


An applet requires an html envelop around it to be executed. There are five important methods in an applets life. They are init() start() stop() destroy() paint()

init() - When an applet is loaded into the memory, this function is called. This function sets the initial behavior of an applet. It can be used to set fonts, load images, initialize variables or set parameters. The init() method has to overridden with a necessary code

Dept. of Computer Science 2010-2011

44

Java Programming Laboratory BCA504P Ex: public void init() { Necessary code }

start() - This method is invoked after the applet is initialized and this method physically starts the execution of overridden. Ex: public void start() { Necessary code } an applet. Like init(), start() should also be

stop() - This method is called when an explicit call to the method is made on when the user leaves the current page in which the applet is running. It should also be overridden. Ex : public void stop() { Necessary code }

Dept. of Computer Science 2010-2011

45

Java Programming Laboratory BCA504P destroy() - This method is used whenever the memory used by an applet has to be freed or when the user exists in the browser. It should be overridden. Ex: public void destroy() { Necessary code }

paint() - This method can be called any number of times in an applet. This is responsible for displaying text, graphics, image etc. on the screen. This method should be overridden for user specific functionalities. The Graphics class of the awt package has to be imported since it uses an object of Graphics. Applets programs can be executed in two ways Compiling the Java applet program, Starting the web browser and executing the html file containing the applet tag Compile the Java applet program. The Java program should contain the applet tag commented. Then Run the program using the Built-in Java Web Browser (appletviewer)

Dept. of Computer Science 2010-2011

46

Java Programming Laboratory BCA504P

/* 8. Program to create a student report using applet by reading the input using textboxes and to display the output using buttons */
import java.applet.*; import java.awt.*; import java.awt.event.*; /* <applet code="StudentReport.class" height="400" width="400"> </applet> */ public class StudentReport extends Applet implements ActionListener { TextField tregno, tname, tcourse,tm1,tm2,tm3,tm4,tm5,ttotal; Label ltitle,lregno,lname,lcourse,lm1,lm2,lm3,lm4,lm5,ltotal; Button breport; public void init() { ltitle = new Label("!... STUDENT DETAILS ...!"); lregno=new Label("Register Number->"); lname=new Label("Name->"); lcourse=new Label("Course->"); lm1=new Label("Mark1->"); lm2=new Label("Mark2->");
Dept. of Computer Science 2010-2011 47

Java Programming Laboratory BCA504P

lm3=new Label("Mark3->"); lm4=new Label("Mark4->"); lm5=new Label("Mark5->"); ltotal=new Label("Total");

tregno=new TextField(23); tname=new TextField(23); tcourse=new TextField(23); tm1=new TextField(23); tm2=new TextField(23); tm3=new TextField(23); tm4=new TextField(23); tm5=new TextField(23); ttotal=new TextField(23);

breport=new Button("...CLICK..."); add(ltitle); //x,y,width,height add(lregno); add(tregno); add(lname); add(tname); add(lcourse); add(tcourse);
Dept. of Computer Science 2010-2011 48

Java Programming Laboratory BCA504P

add(lm1); add(tm1); add(lm2); add(tm2); add(lm3); add(tm3); add(lm4); add(tm4); add(lm5); add(tm5); add(ltotal); add(ttotal); add(breport); breport.addActionListener(this); }

public void actionPerformed(ActionEvent ae) { if(ae.getSource() == breport) { int tot,m1,m2,m3,m4,m5; String t=""; m1=Integer.parseInt(tm1.getText()); m2=Integer.parseInt(tm2.getText()); m3=Integer.parseInt(tm3.getText());
Dept. of Computer Science 2010-2011 49

Java Programming Laboratory BCA504P

m4=Integer.parseInt(tm4.getText()); m5=Integer.parseInt(tm5.getText()); tot= m1 + m2 + m3 + m4 + m5; t=t+tot; ttotal.setText(t); } repaint(); } public void paint(Graphics g) { Font f = new Font("Arial",Font.BOLD,25); g.setColor(Color.red); g.setFont(f); g.drawString("Student Details",200,180);

Font x = new Font("TimesNewRoman",Font.ITALIC,20); g.setColor(Color.green); g.setFont(x);

g.drawString("Name : ",200,220); g.drawString(tname.getText(),280,220);

g.drawString("Reg No : ",200,250); g.drawString(tregno.getText(),280,250);

Dept. of Computer Science 2010-2011

50

Java Programming Laboratory BCA504P

g.drawString("Course : ",200,280); g.drawString(tcourse.getText(),290,280);

g.drawString("Mark1 : ",200,310); g.drawString(tm1.getText(),280,310);

g.drawString("Mark2 : ",200,340); g.drawString(tm2.getText(),280,340);

g.drawString("Mark3 : ",200,370); g.drawString(tm3.getText(),280,370);

g.drawString("Mark4 : ",200,400); g.drawString(tm4.getText(),280,400);

g.drawString("Mark5 : ",200,430); g.drawString(tm5.getText(),280,430);

Font y = new Font("Arial",Font.BOLD,25); g.setColor(Color.red); g.setFont(y);

g.drawString("Total : ",200,480); g.drawString(ttotal.getText(),280,460); }


Dept. of Computer Science 2010-2011 51

Java Programming Laboratory BCA504P

Output:

Dept. of Computer Science 2010-2011

52

Java Programming Laboratory BCA504P

Dept. of Computer Science 2010-2011

53

Java Programming Laboratory BCA504P

Inheritance

Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. Using inheritance, we can create a general class that defines traits common to a set of related items. Other more specific classes can inherit this class and each can add only those things that are unique to it.

In the terminology of Java, a class that is inherited is called a super class. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a super class. It inherits all of the instance variables and methods defined by the superclass and add its own, unique elements.

To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword.

Method Overriding
Overriding is the creation of a method in the sub class that has the same signature (i.e., same name, number and type of arguments) as a method in the super class. This new method hides the method of the super class. Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. When a method is called on an object the java compiler first searches for the method in the class of that object, if not found then it searches for the method in the hierarchy until it is found.

Dept. of Computer Science 2010-2011

54

Java Programming Laboratory BCA504P

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 how Java implements run-time polymorphism. A super class reference variable can refer to a subclass object. Java uses this fact to resolve calls to overridden methods at run time. When an overridden method is called through a super class reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. When different types of objects are referred to, different versions of an overridden method will be called. In other words, it is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed. Therefore, if a super class contains a method that is overridden by a subclass, then when different types of objects are referred to through a super class reference variable, different versions of the method are executed.

Dept. of Computer Science 2010-2011

55

Java Programming Laboratory BCA504P

/* 9. Program to calculate the bonus for different departments using method overriding*/
import java.io.*; class Employee { public static void main(String args[])throws IOException { String Name,dept; float salary,da; DataInputStream din=new DataInputStream(System.in); System.out.println("ENTER THE NAME OF EMPLOYEE:"); Name=din.readLine(); System.out.println("ENTER THE BASIC SALARY:"); salary=Float.parseFloat(din.readLine()); salary=Math.abs(salary); if(salary < 10000) da=3000; else if((salary>10000)&&(salary<20000)) da=4000; else da=5000; System.out.println("_________________________"); double hra=salary*0.2; double cca=salary*0.1; Company c;
Dept. of Computer Science 2010-2011 56

Java Programming Laboratory BCA504P

Admin A=new Admin(salary,hra,da); Finance F=new Finance(salary,cca,da); System.out.println("SELECT THE DEPT"); System.out.println("\t ADMIN"); System.out.println("\t FINANCE"); System.out.println("ENTER THE DEPT:"); dept=din.readLine(); if((dept.compareTo("ADMIN"))==0) { System.out.println("\t\tADMIN DEPT"); System.out.println("EMPLOYEE NAME:"+Name); System.out.println("DEARNESS ALLOWENCE:"+da); c=A; c.bonus(); } if((dept.compareTo("FINANCE"))==0) { System.out.println("\t\tFINANCE DEPT"); System.out.println("EMPLOYEE NAME:"+Name); System.out.println("DEARNESS ALLOWENCE:"+da); c=F; c.bonus(); } } }
Dept. of Computer Science 2010-2011 57

Java Programming Laboratory BCA504P

abstract class Company { float basic; Company(float b) {basic=b;} abstract void bonus();

} class Admin extends Company { double hra,x; Admin(float basic,double h,float da) { super(basic); hra=h; x=da; } void bonus() { System.out.println("BASIC SALARY:"+basic); System.out.println("HRA:"+hra); if(basic>5000) { System.out.println("BONUS: "+(basic*0.05)); System.out.println("GROSS PAY: "+((basic*0.05)+(x+basic+hra))); }
Dept. of Computer Science 2010-2011 58

Java Programming Laboratory BCA504P

else { System.out.println("BONUS: "+300); System.out.println("GROSS PAY: "+(300+x+basic+hra)); }

} } class Finance extends Company { double cca,x; Finance(float basic,double c,float da) { super(basic); cca=c;x=da; } void bonus() { System.out.println("BASIC SALARY:"+basic); System.out.println("CCA:"+cca); if(basic>5000) { System.out.println("BONUS: "+(basic*0.03)); System.out.println("GROSS PAY: "+((basic*0.03)+(x+basic+cca))); } else { System.out.println("BONUS: "+300);
59

Dept. of Computer Science 2010-2011

Java Programming Laboratory BCA504P

System.out.println("GROSS PAY: "+(300+x+basic+cca)); } } }

Output:

Dept. of Computer Science 2010-2011

60

Java Programming Laboratory BCA504P

Dept. of Computer Science 2010-2011

61

Java Programming Laboratory BCA504P

Threads

A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. The Java run-time system depends on threads for many things, and all the class libraries are designed with multithreading in mind. In fact, Java uses threads to enable the entire environment to be asynchronous. This helps reduce inefficiency by preventing the waste of CPU cycles

The Thread Class and the Runnable Interface: Java's multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable. Thread encapsulates a thread of execution

To create a new thread, your program will either extend Thread or implement the Runnable interface

The Thread class defines several methods that help manage threads o o o o o o o getName() - Obtain a thread's name getPriority() - Obtain a thread's priority isAlive() - Determine if a thread is still running join() Wait for a thread to terminate Run() - Entry point for the thread Sleep() - Suspend a thread for a period of time Start() - Start a thread by calling its run method

The Main Thread When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is

Dept. of Computer Science 2010-2011

62

Java Programming Laboratory BCA504P the one that is executed when your program begins. The main thread is important for two reasons 1. It is the thread from which other "child" threads will be spawned. 2. It must be the last thread to finish execution. When the main thread stops, your program terminates. Creating a Thread In the most general sense, you create a thread by instantiating an object of type Thread. Java defines two ways in which this can be accomplished: 1. We can implement the Runnable interface 2. We can extend the Thread class itself Thread Priorities Thread priorities are used by the thread scheduler to decide when each thread should be allowed to run. In theory, higher-priority threads get more CPU time than lower-priority threads. In practice, the amount of CPU time that a thread gets often depends on several factors besides its priority. (For example, how an operating system implements multitasking can affect the relative availability of CPU time) A higher-priority thread can also preempt a lower-priority one. For instance, when a lower-priority thread is running and a higher-priority thread resumes (from sleeping or waiting on I/O, for example), it will preempt the lowerpriority thread

Dept. of Computer Science 2010-2011

63

Java Programming Laboratory BCA504P

/* 10. Program to implement thread priorities */


import java.io.*; class NewThread extends Thread { public void run() { try { for(int i=0;i<3;i++) { System.out.println(this+" "+i); Thread.sleep(500); } } catch(InterruptedException ie) { System.out.println("CHILD THREAD INTERRUPTED "+ie); } System.out.println(this+"EXITED"); } public static void main(String args[])throws IOException
Dept. of Computer Science 2010-2011 64

Java Programming Laboratory BCA504P

{ NewThread t = new NewThread(); Thread tm = Thread.currentThread(); System.out.println("NAME OF THE MAIN THREAD:"+tm); System.out.println("NAME OF THE CHILD THREAD:"+t); t.setName("VBCA"); System.out.println("CHANGED NAME OF THE CHILD THREAD:"+t); t.setPriority(7); System.out.println("CHANGED PRIORITY OF CHILD THREAD:"+t); t.start(); try { for(int j=1;j<=5;j++) { System.out.println("MAIN THREAD:"+j); Thread.sleep(1000); } } catch(InterruptedException ie) { System.out.println("MAIN THREAD INTERRUPTED"+ie); } System.out.println(" MAIN THREAD EXITING"); } }
Dept. of Computer Science 2010-2011 65

Java Programming Laboratory BCA504P

Output:

Dept. of Computer Science 2010-2011

66

Java Programming Laboratory BCA504P

/* 11. Program to implement thread, applets and graphics by implementing animating a ball */
import java.awt.*; import java.applet.*; /* <applet code="MovingBall.class" width="200" height="500"> </applet> */ public class MovingBall extends Applet implements Runnable { Thread mythread=null; int pos=0; public void start() { mythread=new Thread(this); mythread.start(); } public void run() { while (true) { for(pos=0;pos<getSize().width;pos+=5) { repaint();
Dept. of Computer Science 2010-2011 67

Java Programming Laboratory BCA504P

try { mythread.sleep(100); } catch(InterruptedException ie){} } } } public void stop() { mythread.stop(); mythread=null; } public void paint(Graphics g) { g.setColor(Color.green); g.fillOval(pos,50,50,50); g.setColor(Color.black); g.fillOval(pos +10,62,10,10); g.fillOval(pos +30,62,10,10); g.drawLine(pos +25,70,pos +25,75); g.drawArc(pos +8,50,34,34,-54,-74); } }

Dept. of Computer Science 2010-2011

68

Java Programming Laboratory BCA504P

Output:

Dept. of Computer Science 2010-2011

69

Java Programming Laboratory BCA504P

Event Handling in Java


In Java, events represent all activity that goes on between the user and the application. Javas Abstract Windowing Toolkit (AWT) communicates these actions to the programs using events. When the user interacts with a program let us say by clicking a command button, the system creates an event representing the action and delegates it to the event handling code within the program. This code determines how to handle the event so the user gets the appropriate response. All the event classes are described inside the following package.

package java.awt.event
It provides interfaces and classes for dealing with different types of events fired by AWT components. Events may occur at any time with no predefined order, so a different programming model is required. In this model, the application passively waits for events, which in turn determine what and when is executed. This programming model defines an event-driven application, such as an interactive application employing a graphical user interface (GUI). It reacts only to user actions (events), and the action it takes depends on the event. Furthermore, the user can press buttons, select options, and type something at any time and in any order. Basically, events are random they occur at the users discretion. In Java, objects generate events. An event is represented by a java.util.EventObject subclass that carries event information. There are subclasses for each kind of event. At a minimum, they hold a reference to the object that generated the event (the source of the event), but each subclass defines additional information appropriate for the event.

Dept. of Computer Science 2010-2011

70

Java Programming Laboratory BCA504P

Event Notification
The notification mechanism involves calling a specific method of any objects that want to be notified about the event and passing the event object as a parameter. These methods are called event handlers. For an object to be notified about an event, it must implement a specific interface and be registered with the source of the event. These objects are called event listeners.

The interface the object must implement depends on the event it wants to receive. There are interfaces for each kind of event; all of them are sub interfaces of the java.util.EventListener interface. Each interface defines one or more methods that are called by the source of the event. Each method receives an event object as a parameter. Note that it is common for an interface to define more than one method, and several events are often represented using the same class. For example, both key presses and key releases generate events, but the same class, java.awt.event.KeyEvent, is used to represent both. So the corresponding interface for java.awt.event.KeyEvent events, java.awt.event.KeyListener, defines a method for key presses, keyPressed, and another for key releases, keyReleased. Once the object implements the correct interface, it must be registered as a listener of the desired event with the event source. Each class that generates events provides methods to add and remove listeners for each kind of event it generates. Any number of listeners may be registered with a given source. When an event is fired, each one is called in turn.

Dept. of Computer Science 2010-2011

71

Java Programming Laboratory BCA504P

Interface KeyListener
The listener interface for receiving keyboard events (keystrokes) is KeyListener. The class that is interested in processing a keyboard event either implements this interface (and all the methods it contains) or extends the abstract KeyAdapter class (overriding only the methods of interest). The listener object created from that class is then registered with a component using the component's addKeyListener method. A keyboard event is generated when a key is pressed, released, or typed (pressedn and released). The relevant method in the listener object is then invoked, and the KeyEvent is passed to it.

keyTyped
public void keyTyped(KeyEvent e) { //Invoked when a key has been typed }

keyPressed
public void keyPressed(KeyEvent e) { // Invoked when a key has been pressed }

Dept. of Computer Science 2010-2011

72

Java Programming Laboratory BCA504P

keyReleased
public void keyReleased(KeyEvent e) { // Invoked when a key has been released }

Interface MouseListener
The listener interface for receiving "interesting" mouse events (press, release, click, enter, and exit) on a component. To track mouse moves and mouse drags, use the MouseMotionListener. The class that is interested in processing a mouse event either implements this interface (and all the methods it contains) or extends the abstract MouseAdapter class (overriding only the methods of interest).

The listener object created from that class is then registered with a component using the component's addMouseListener method. A mouse event is generated when the mouse is pressed, released clicked (pressed and released). A mouse event is also generated when the mouse cursor enters or leaves a component. When a mouse event occurs, the relevant method in the listener object is invoked, and the MouseEvent is passed to it.

mouseClicked
public void mouseClicked(MouseEvent e) { //Invoked when the mouse button has been clicked (pressed and released) on a component Dept. of Computer Science 2010-2011 73

Java Programming Laboratory BCA504P }

mousePressed
public void mousePressed(MouseEvent e) { //Invoked when a mouse button has been pressed on a component }

mouseReleased
public void mouseReleased(MouseEvent e) { //Invoked when a mouse button has been released on a component }

mouseEntered
public void mouseEntered(MouseEvent e) { //Invoked when the mouse enters a component }

mouseExited
public void mouseExited(MouseEvent e) { //Invoked when the mouse exits a component } Dept. of Computer Science 2010-2011

74

Java Programming Laboratory BCA504P

Interface MouseMotionListener
The listener interface for receiving mouse motion events on a component. (For clicks and other mouse events, use the MouseListener.) The class that is interested in processing a mouse motion event either implements this interface (and all the methods it contains) or extends the abstract MouseMotionAdapter class (overriding only the methods of interest). The listener object created from that class is then registered with a component using the component's addMouseMotionListener method. A mouse motion event is generated when the mouse is moved or dragged. (Many such events will be generated). When a mouse motion event occurs, the relevant method in the listener object is invoked, and the MouseEvent is passed to it.

mouseDragged
public void mouseDragged(MouseEvent e) { / Invoked when a mouse button is pressed on a component and then dragged. MOUSE_DRAGGED events will continue to be delivered to the component where the drag originated until the mouse button is released (regardless of whether the mouse position is within the bounds of the component)./ } Due to platform-dependent Drag&Drop implementations, MOUSE_DRAGGED events may not be delivered during a native Drag&Drop operation.

Dept. of Computer Science 2010-2011

75

Java Programming Laboratory BCA504P

mouseMoved
public void mouseMoved(MouseEvent e) { //Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed }

Interface ActionListener
The listener interface for receiving action events. The class that is interested in processing an action event implements this interface, and the object created with that class is registered with a component, using the component's addActionListener method. When the action event occurs, that object's actionPerformed method is invoked. void actionPerformed(ActionEvent e) { // Invoked when an action occurs }

Dept. of Computer Science 2010-2011

76

Java Programming Laboratory BCA504P

/* 12. Program to implement mouse events */


import java.awt.*; import java.applet.*; import java.awt.event.*;

/*<HTML> <HEAD> </HEAD> <BODY BGCOLOR="000000"> <CENTER> <APPLET code = "Smpmouseevent.class" width = "500" height > </APPLET> </CENTER> </BODY> </HTML> */ public class Smpmouseevent MouseListener,MouseMotionListener { int x,y; String msg=" ";
Dept. of Computer Science 2010-2011 77

= "300"

extends

Applet

implements

Java Programming Laboratory BCA504P

public void init() { addMouseListener(this); addMouseMotionListener(this); }

public void mouseEntered(MouseEvent me) { x=me.getX(); y=me.getY(); msg="Mouse Entered at: "+x+" "+y; repaint(); }

public void mouseExited(MouseEvent me) { x=me.getX(); y=me.getY(); msg="Mouse Exited at: "+x+" "+y; repaint(); } public void mousePressed(MouseEvent me) { x=me.getX(); y=me.getY();
Dept. of Computer Science 2010-2011 78

Java Programming Laboratory BCA504P

msg="Mouse Pressed at: "+x+" "+y; repaint(); }

public void mouseReleased(MouseEvent me) { x=me.getX(); y=me.getY(); msg="Mouse Released at: "+x+" "+y; repaint(); }

public void mouseClicked(MouseEvent me) { x=me.getX(); y=me.getY(); msg="Mouse Clicked at: "+x+" "+y; repaint(); }

public void mouseDragged(MouseEvent me) { x=me.getX(); y=me.getY(); msg="Mouse Dragged at: "+x+" "+y;
Dept. of Computer Science 2010-2011 79

Java Programming Laboratory BCA504P

repaint(); } public void mouseMoved(MouseEvent me) { x=me.getX(); y=me.getY(); msg="Mouse Moved at: "+x+" "+y; repaint(); }

public void paint(Graphics g) { g.drawString(msg,x,y);

} }

Dept. of Computer Science 2010-2011

80

Java Programming Laboratory BCA504P Output:

Dept. of Computer Science 2010-2011

81

Java Programming Laboratory BCA504P

Dept. of Computer Science 2010-2011

82

Java Programming Laboratory BCA504P

Dept. of Computer Science 2010-2011

83

Java Programming Laboratory BCA504P

/* 13. Program to implement keyboard events */


Dept. of Computer Science 2010-2011 84

Java Programming Laboratory BCA504P

import java.awt.*; import java.applet.*; import java.awt.event.*; /*<html> <applet code="Smpkeyevent.class" height="200" width="400"> </applet> </html>*/ public class Smpkeyevent extends Applet implements KeyListener { int keycode; char keychar; String msg="U Have Pressed: "; public void init() { addKeyListener(this); }

public void keyPressed(KeyEvent ke) { keycode=ke.getKeyCode(); if (keycode==KeyEvent.VK_ENTER) msg=msg+"Enter"; if (keycode==KeyEvent.VK_SHIFT) msg=msg+"Shift"; if (keycode==KeyEvent.VK_DELETE)
Dept. of Computer Science 2010-2011 85

Java Programming Laboratory BCA504P

msg=msg+"Delete"; if (keycode==KeyEvent.VK_ALT) msg=msg+"Alt"; if (keycode==KeyEvent.VK_END) msg=msg+"End"; repaint(); }

public void keyReleased(KeyEvent ke){}

public void keyTyped(KeyEvent ke) { keychar=ke.getKeyChar(); msg=msg+keychar; repaint(); }

public void paint(Graphics g) { g.drawString(msg,50,50); } }


Output:

Dept. of Computer Science 2010-2011

86

Java Programming Laboratory BCA504P

Dept. of Computer Science 2010-2011

87

Anda mungkin juga menyukai