MCA (DISTANCE MODE) DMC 1756 Internet Programming Laboratory IV SEMESTER LAB MATERIAL

Size: px
Start display at page:

Download "MCA (DISTANCE MODE) DMC 1756 Internet Programming Laboratory IV SEMESTER LAB MATERIAL"

Transcription

1 MCA (DISTANCE MODE) DMC 1756 Internet Programming Laboratory IV SEMESTER LAB MATERIAL Centre for Distance Education Anna University Chennai Chennai

2 Author Mrs. L. Prema Rajeswari Lecturer Department of Computer Science and Engineering Anna University Chennai Chennai Reviewer Mr. S. Sendhilkumar Lecturer Department of Computer Science and Engineering Anna University Chennai Chennai Editorial Board Dr. T.V. Geetha Professor Department of Computer Science and Engineering Anna University Chennai Chennai Dr. H. Peeru Mohamed Professor Department of Management Studies Anna University Chennai Chennai Dr. C. Chellappan Professor Department of Computer Science and Engineering Anna University Chennai Chennai Dr. A. Kannan Professor Department of Computer Science and Engineering Anna University Chennai Chennai Copyrights Reserved (For Private Circulation only) 2

3 3

4 4

5 LAB MANUAL FOR INTERNET PROGRAMMING 1. INTRODUCTION 1.1 Java Features 1.2 Types of Java programs 1.3 JDK Tools 1.4 Primitive data types 1.5 Program skeleton 1.6 Implementing a Java Program 2. OVERLOADING 2.1 Methods Overloading 2.2 Overriding Methods 3. INTERFACES 3.1 Interfaces 3.2 Packages 4. EXCEPTION HANDLING 4.1 General form of an Exceptions 4.2 Exception Types 4.3 Uncaught Exception 5. INTER THREAD COMMUNICATION & DEADLOCK AVOIDANCE 5.1. Inter Thread Communication 5.2 Deadlock 6. FIlE OPERATIONS 7. APPLETS 6.1. Streams 6.2 Reading Console Input 6.3 Writing Console Output 6.4 Reading and Writing Files 7.1 Java Applet basics 7.2 Life cycle of an applet 7.3 An applet tag 7.4 An applet skeleton 5

6 8. JDBC 8.1 JDBC API 8.2 JDBC Driver Manager 8.3 JDBC ODBC Bridge 8.4 Connecting to a database 8.5 Using Select 8.6 Using Update 8.7 Using JDBC in servlets 9. JNI 9.1 JNI basics 9.2 Compiling and Running 10.RMI 10.1 JNI basics 10.2 Compiling and Running 11. SERVLET 11.1 Basic servlet structure 11.2 Servlet that generates HTML code 11.3 Servlet that handles Post request 11.4 Servlet that uses Cookies 11.5 Sessions Tracking 6

7 DMC 1756 / MC1708 INTERNET PROGRAMMING LAB 1. Program to illustrate the use of overloading and overriding 2. Program to implement the concept of interfaces and packages 3. Generate the program using exception handling mechanism 4. Program to achieve inter thread communication and deadlock avoidance 5. Implement the file operations 6. Program using Applets 7. Program using JDBC 8. Program using JNI concepts 9. Program to illustrate the use of RMI 10. Program using servlets 7

8 8

9 Chapter 1 Introduction Objectives Java Features Types of Java programs JDK Tools Primitive data types Program skeleton Implementing a Java Program 1.1 INTRODUCTION Java is a general-purpose, object-oriented programming language developed by Sun Microsystems of USA in Java is the first programming language that is not tied to any particular hardware or operating system. Java is a "simple, object-oriented, interpreted, robust, secure, architecture-neutral, portable, high-performance, multithreaded, and dynamic language." 1.2. TYPES OF JAVA PROGRAMS Applications They are programs that do not need a browser for execution Applets They are programs that run off a web page Servlets These programs extend the functionality of Web servers Packages They are collections of classes that can be shared by other Java programs 9

10 1.3. JDK TOOLS JDK provides tools for users to integrate and execute Java programs. They include: i. appletviewer( for viewing Java applets) Syntax for executing a Java applet appletviewer <URL of the.html file > ii. iii. iv. javac ( Java compiler) Syntax for compiling Java code using javac javac <filename.java> java ( Java interpreter) Syntax for executing a Java application using java java <filename.class> javap ( Java disassembler) Syntax for using jdb jdb <list of.class files> v. javah ( for C header files) Syntax for creating header files javah <class filename> vi. vii. javadoc ( for creating HTML documents) Syntax for using javadoc javadoc <list of.java files > jdb ( Java debugger) Syntax for using jdb jdb <filename.class> 10

11 1.4 PRIMITIVE DATA TYPES Possible range of values Data Type Size in bits From To Boolean 8 True False Byte Short 16-32, ,767 Char 16 \u0000 \uffff Int 32-2,147,483, ,147,483,647 Float * (10** -38) 3.4 *( 10** +38) Long ,233,372,036,854,775,807 9,233,372,036,854,775,808 Double *(10 ** -308) 1.7 *(10 ** +308) 1.5 PROGRAM SKELETON: 1. // the skeleton of a java application 2. package packagename; 3. import packagename.classname; 4. public class ProgramName // Define program variables here // Define program methods here // Define the main methods here. 11. public static main(string args [ ] ) //Main method body 11

12 14. // end of the main method 15. // end of class. 1.6 IMPLEMENTING A JAVA PROGRAM Implementation of a Java application program involves a series of steps. They include: i. Creating the program ii. Compiling the program iii. Running the program (i) Creating the program You can create a java program using any text editor. Assume that we have entered the following program: Class Test public static void main(string args [ ] ) System.out.println( JNFPTLVBJGTJ. ); Save the source code as <classname>.java, for example Test.java. The file containing Java source code must have the filename classname.java, where classname is the name of the class in your Java source code. (ii) Compiling the program To compile the program, we must run the Java compiler javac, with the name of the source file on the command line as shown below: javac Test.java 12

13 If everything is OK, the javac compiler creates a file called Test.class containing the bytecodes of the program. If the source code file contains more than one class, the Java compiler will create a separate byte-code file for each class. If a Java development environment is being used, the program is compiled by invoking a menu function rather than by running Java directly. The folder containing javac must be in the programmer s PATH environment variable. (iii) Running the program A Java application is basically run by invoking the Java interpreter on Java byte-code. Java byte-code files have the filename name.class, where name is both the filename and the name of the code module it contains. To run the program from a shell prompt, type: java name In our case type: java Test Now the interpreter looks for the main method in the program and begins execution from there. When executed our program displays the following: JNFPTLVBJGTJ. Note that no suffix is used along with the file name. The interpreter will assume the suffix.class on the filename. Remember that one of the goals of Java is to create programs that can run on any platform. Therefore, the Java compiler generates platform independent byte-code rather than platform dependent machine code. Then, to run a program, the Java interpreter translates this bytecode into the machine code for whatever system the Java interpreter is on. For example, Java source code is written and compiled on a Sun workstation running Solaris. If a Java interpreter running on Solaris invokes the bytecode, the Java interpreter will translate the byte-code into Sun machine code. 13

14 Now, that same byte-code is copied over to a PC running Windows95. In this scenario, the Windows95 Java interpreter translates the byte-code into PC machine code. Because of the time the Java interpreter needs to translate byte-code into machine code, Java applications run somewhat slower than applications stored in native machine code. The programmer s PATH must contain the directory where the interpreter java is stored. The programmer may also need to add the directory containing his/her class files to the CLASSPATH environment variable. SUMMARY Java is purely object-oriented. Java produces programs that are robust and secure. Compiling and running java source code Java compiler generates platform independent byte-code A Java application is run by invoking the Java interpreter on Java bytecode. REVIEW QUESTIONS 1. What is java? 2. Mention the primitive data types in java. 3. What are the various types of java programs that a user can create? 4. Indicate the various program elements in a java program. 5. How will you to implement a java program? 14

15 Chapter 2 Overloading and Overriding OBJECTIVES Methods Overloading Overriding Methods 2.1 INTRODUCTION Java classes have some additional features that aid program development like method overloading and overriding. For example, class methods may be called with varying numbers and types of parameters by using overloading and a derived class might redefine a method contained in the parent class (with the same parameter types) using overriding. 2.2 METHOD OVERLOADING In java, it is possible to create methods that have the same name, but different parameter lists and different definitions. This is called method overloading. Method overloading is used when objects are required to perform similar tasks but using different input parameters. When we call a method in an object, Java matches up the method name first and then the number and type of parameters to decide which one of the definitions to execute. This process is known as polymorphism. In other words, a method is identified by its signature, made up of both the name and the types of its parameters. The return type of a method is not a part of its signature. An overloaded method must differ from other methods of the same name in number and/or types of arguments: public double dothis (Circle cx)... public void dothis (double x)... public void dothis ()... 15

16 When a call to an overloaded method is made, the compiler must perform overload resolution to determine which method is being called. The compiler considers all the methods of the same name and number of arguments as the call, compares the actual types of arguments of the call with the formal argument types of the methods, and chooses the appropriate method. Example: class Calculator public int add( int a, int b) System.out.println( int and int ); return a+b; public float add( float a, float b) System.out.println( float and float ); return a+b; public float add( float a, int b) System.out.println( float and int ); return a+b; public static void main(string args[ ]) Calculator c= new Calculator( ); System.out.println(c.add(1,10)); System.out.println(c.add(1.6f,10)); System.out.println(c.add(1.6f,10.5f)); Constructor Overloading Constructor can also take varying numbers and type of parameters, enabling object with the properties required. Example class Room float length, breadth; Room(float x, float y) // constructor 1 length = x; breadth = y; 16

17 Room(float x) // constructor 2 length = breadth = x; int area( ) return (length * breadth); Here we are overloading the constructor method Room(). An object representing a rectangular room will be created as Room room1 = new Room(25.0, 15.0); // using constructor1 On the other hand, if the room is square, then we may create the corresponding object as Room room2 = new Room(25.0); // using constructor2 Here s another example that shows both overloaded constructors and overloaded ordinary methods: // Demonstration of both constructor and ordinary method overloading. import java.util.*; class Tree int height; Tree() prt("planting a seedling"); height = 0; Tree(int i) prt("creating new Tree that is "+ i + " feet tall"); height = i; void info() prt("tree is " + height+ " feet tall"); void info(string s) prt(s + ": Tree is "+ height + " feet tall"); static void prt(string s) 17

18 System.out.println(s); public class Overloading public static void main(string[] args) for(int i = 0; i < 5; i++) Tree t = new Tree(i); t.info(); t.info("overloaded method"); // Overloaded constructor new Tree(); A Tree object can be created either as a seedling, with no argument, or as a plant grown in a nursery, with an existing height. To support this, there are two constructors, one that takes no arguments (we call constructors that take no arguments default constructors1) and one that takes the existing height. 2.3 METHODS OVERRIDING However there may be occasions when we want an object to respond to the same method but have different behavior when that method is called. That means, we should override the method defined in the super class. This is possible by defining a method in the subclass that has the same name, same arguments and same return type as a method in the super class. Then, when that method is called, the method defined in the subclass is invoked and executed instead of the one in the super class. This is known as overriding. The following program illustrates the concept of overriding. The method show( ) is Overridden. Example: // Method overriding. class A int i, j; A(int a, int b) 18

19 i = a; j = b; void show() class B extends A show() in A class Override // display i and j System.out.println("i and j: " + i + " " + j); int k; B(int a, int b, int c) super(a, b); k = c; void show() // display k this overrides System.out.println("k: " + k); public static void main(string args[]) B subob = new B(1, 2, 3); SubOb.show(); // this calls show() in B The output produced by this program is shown here: k : 3; When show( ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the version of show( ) inside B overrides the version declared in A. If you wish to access the superclass version of an overridden function, you can do so by using super. For example, in this version of B, the superclass version of show( ) is invoked within the subclass version. This allows all instance variables to be displayed. 19

20 class B extends A int k; B(int a, int b, int c) super(a, b); k = c; void show() super.show(); // this calls A's show() System.out.println("k: " + k); If you substitute this version of A into the previous program, you will see the following output: i and j: 1 2 k: 3 Here, super.show( ) calls the superclass version of show( ). 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. For example, consider this modified version of the preceding example: // Methods with differing type signatures are overloaded not overridden. class A int i, j; A(int a, int b) i = a; j = b; // display i and j void show() System.out.println("i and j: " + i + " " + j); // Create a subclass by extending class A. class B extends A 20

21 int k; B(int a, int b, int c) super(a, b); k = c; // overload show() void show(string msg) System.out.println(msg + k); class Override public static void main(string args[]) B subob = new B(1, 2, 3); subob.show("this is k: "); // this calls show() in B subob.show(); // this calls show() in A The output produced by this program is shown here: This is k: 3 i and j: 1 2 The version of show( ) in B takes a string parameter. This makes its type signature different from the one in A, which takes no parameters. Therefore, no overriding (or name hiding) takes place. SUMMARY Method overloading - methods that have the same name, but different parameter lists and different definitions. Method overloading is used when objects are required to perform similar tasks but using different input parameters An overloaded method must differ from other methods of the same name in number and/or types of arguments Constructor Overloading - Constructor can also take varying numbers and type of parameters, enabling object with the properties required 21

22 Method overriding - defining a method in the subclass that has the same name, same arguments and same return type as a method in the super class and when that method is called, the method defined in the subclass is invoked and executed instead of the one in the super class. REVIEW QUESTIONS 2.1 Create a class Overloadtwo. Write a program to assign the values for two values by different number of arguments using a single function. 2.2 Write a program to override the method defined in the superclass to display the values. 2.3 Write a program to create a superclass called Figure that stores various two dimensional objects and using area( ) to computes the area of an object. Derive two subclasses from Figure to override area( ). 22

23 Chapter 3 Interfaces and Packages OBJECTIVES Interfaces Packages 3.1 INTERFACES An interface is a prototype for a class and is useful from a logical design perspective. This description of an interface may sound vaguely familiar Remember abstract classes? Interfaces are used to define a behavior protocol that can be implemented by any class anywhere in the class hierarchy. You define an interface in a similar way to defining a class, but you don't provide any code for the interface. Classes that should be polymorphic with other objects must implement the interface that is, supply the code. Programs can treat any object that implements an interface as though it were an object of the nonexistent class that corresponds to the interface. Defining an Interface: This is the general form of an interface: access interface name return-type method-name1(parameter-list); return-type method-name2(parameter-list); type final-varname1 = value; type final-varname2 = value; //... return-type method-namen(parameter-list); type final-varnamen = value; 23

24 Implementing Interfaces: Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general form of a class that includes the implements clause looks like this: Example: access class classname [extends superclass] [implements interface [,interface...]] // class-body interface Printable public void print(); class T2 implements Printable int n; public T2(int n) this.n=n; public void print() System.out.println("Number = " + n); class T3 implements Printable String s; public T3(String s) this.s=s; public void print() System.out.println("String=" + s); 24

25 public class T1 public static void main(string [] args) Printable p = new T2(100); p.print(); p=new T3("Coriolis"); p.print(); Because both classes (T2 and T3) implement Printable, they must include the methods defined in that interface (one method; in this case, print). What these classes do in that method is their own business, but they must include it. (Not including the interface methods will earn you a compile-time error.) Because each object contains a print method, the main method can treat them both as a Printable object (which isn't really an object at all). So T2 and T3 are polymorphic, but they don't share any code or base classes (except, of course, for Object, which is the eventual base class of all objects). Another interesting point about the previous code is that the constructors use the same parameter name as the field they set. For example: int n; public T2(int n) this.n=n; The this keyword represents the current object and allows the constructor to set the field without conflicting with the parameter of the same name. The benefits of using interfaces are much the same as the benefits of using abstract classes. Interfaces provide a means to define the protocols for a class without worrying with the implementation details. This seemingly simple benefit can make large projects much easier to manage; once interfaces have been 25

26 designed, the class development can take place without worrying about communication among classes. Another important usage of interfaces is the capacity for a class to implement multiple interfaces. This is a twist on the concept of multiple inheritances, which is supported in C++, but not in Java. Multiple inheritances enable you to derive a class from multiple parent classes. Although powerful, multiple inheritances are a complex and often tricky feature of C++ that the Java designers decided they could do without. Their workaround was to allow Java classes to implement multiple interfaces. The major difference between inheriting multiple interfaces and true multiple inheritance is that the interface approach only enables you to inherit method descriptions, not implementations. So, if a class implements multiple interfaces, that class must provide all of the functionality for the methods defined in the interfaces. Although this is certainly more limiting than multiple inheritance, it is still a very useful feature. It is this feature of interfaces that separate them from abstract classes PACKAGES Java provides a powerful means of grouping related classes and interfaces together in a single unit: packages. Packages provide a convenient mechanism for managing a large group of classes and interfaces, while avoiding potential naming conflicts. The Java API itself is implemented as a group of packages. Defining a Package To create a package is quite easy: simply include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are 26

27 put into the default package, which has no name. This is the general form of the package statement: package pkg; Here, pkg is the name of the package. You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period. The general form of a multileveled package statement is shown here: Example: package pkg1[.pkg2[.pkg3]]; // A simple package package MyPack; class Balance String name; double bal; Balance(String n, double b) name = n; bal = b; void show() if(bal<0) System.out.print("--> "); System.out.println(name + ": $" + bal); class AccountBalance public static void main(string args[]) Balance current[] = new Balance[3]; current[0] = new Balance("K. J. Fielding", ); current[1] = new Balance("Will Tell", ); current[2] = new Balance("Tom Jackson", ); for(int i=0; i<3; i++) current[i].show(); 27

28 Call this file AccountBalance.java, and put it in a directory called MyPack. Next, compile the file. Make sure that the resulting.class file is also in the MyPack directory. Then try executing the AccountBalance class, using the following command line: java MyPack.AccountBalance Remember, you will need to be in the directory above MyPack when you execute this command, or to have your CLASSPATH environmental variable set appropriately. As explained, AccountBalance is now part of the package MyPack. This means that it cannot be executed by itself. That is, you cannot use this command line: SUMMARY java AccountBalance AccountBalance must be qualified with its package name. Interfaces are used to define a behavior protocol that can be implemented by any class anywhere in the class hierarchy. Interfaces provide a means to define the protocols for a class without worrying with the implementation details. Packages provide a convenient mechanism for managing a large group of classes and interfaces, while avoiding potential naming conflicts. To create a package, simply include a package command as the first statement in a Java source file. Review Questions 3.1 Using interface write a program to display the text. 3.2 Write a Java program to calculate the area of the rectangle and circle using interfaces. 28

29 Chapter 4 Exception - Handling OBJECTIVES General form of an Exceptions Exception Types Uncaught Exception 4.1. GENERAL FORM OF EXCEPTIONS HANDLING An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a runtime error. Exception are events like division by zero, opening a file that does not exists etc, a Java exception is an object that describes an exceptional ( that is error) condition that has occurred in a piece of code. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. This is the general form of an exceptionhandling: try // block of code to monitor for errors catch (ExceptionType1 exob) // exception handler for ExceptionType1 catch (ExceptionType2 exob) // exception handler for ExceptionType2 //... finally // block of code to be executed before try block ends 29

30 Java uses the try, catch, and throw keywords to do actual exception handling. They are conceptually similar to a switch statement; think of try like the switch statement in terms of exactly identifying the condition to be tested. catch is used to specify the action that should be taken for a particular type of exception. It is similar to the case part of a switch statement. There can be several catch statements in a row to deal with each of the exceptions that may be generated in the block specified by the try statement. throw Understanding exception handling in Java requires that you learn some new terminology. The first concept you need to grasp is that of throwing an exception, Java's name for causing an exception to be generated. For example, say a method was written to read a file. If the method could not read the file because the file did not exist, this would generate an IOException. In Java terminology, it is said that the method threw an IOException. catch The next term to learn in Java exception handling is catch. An exception catch is code that realizes the exception has occurred and deals with it appropriately. In Java terms, you say a thrown exception gets caught. In the case of the IOException thrown because of the nonexistent file mentioned in the previous section, the catch statement writes an error message to the screen stating that the specified file does not exist. It then allows the user to try entering a different filename if the first was incorrect, or it may exit. In Java terminology, the IOException was caught. try Try is the Java exception-handling term that means a Java program is going to try to execute a block of code that might generate (throw) an exception. 30

31 The try is a way of telling the compiler that some attempt will be made to deal with at least some of the exceptions generated by the block of code. finally The finally statement is used to specify the action to take if none of the previous catch statements specifically deals with the situation. It is similar to the default part of a switch statement. finally is the big net that catches everything that falls out of the exception-handling statement EXCEPTION TYPES All exception types are subclasses of the built- in class Throwable. Immediately below Throwable are two subclasses that partition exceptions into two distinct branches exception and error exception class is used for exceptional conditions that user program should catch. Object Throwable Error Exception IOException RuntimeEx ception 31

32 4.3 UNCAUGHT EXCEPTION class Exco public static void main(string args[]) int d=0; int a = 42/d; Here is the output generated when this example is executed by the standard Java JDK run time interpreter. Java.lang.ArithmeticException : / by zero At Exco.main(Exco.java:4) 4.4 USING TRY AND CATCH Example 1 // ArithmeticException generated by the division-by-zero error: class AExcep public static void main(string args[]) int d, a; try // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); catch (ArithmeticException e) // catch divide-by-zero error System.out.println("Division by zero."); System.out.println("After catch statement."); This program generates the following output: Division by zero. After catch statement. 32

33 Example 2: // Handle an exception and move on. import java.util.random; class HandleError public static void main(string args[]) int a=0, b=0, c=0; Random r = new Random(); for(int i=0; i<32000; i++) try b = r.nextint(); c = r.nextint(); a = / (b/c); catch (ArithmeticException e) System.out.println("Division by zero."); a = 0; // set a to zero and continue System.out.println("a: " + a); Summary Exceptions are Java's way of performing error handling. Exceptions are handled using a combination of three statement types: try, catch, and finally. try is used to inform the compiler that exception handling will be performed on an associated block of code. catch is used for processing a specific exception generated in the try block of code. Several catch statements can be specified sequentially to handle specific exceptions in a specific order. The finally statement can be used to catch all exceptions not specifically caught by a catch statement. A program can generate its own exceptions using the throw statement. The exception itself can be either preexisting or newly created. Even a 33

34 preexisting exception can be customized by specifying a different message when creating the exception object. If you need a new exception, you can create one by simply extending an existing exception class such as java.lang. Exception. Exceptions are usually simple and can be created using only two constructors. Everything else is done by the superclass that the new exception extended. Exercise: 4.1 Write a Java program using multiple catch statement. 4.2 Write a Java program using nested try statement. 4.3 Write a program to demonstrate throw, throws and finally statement. 4.4 Write a Java program to create a custom exception type. 34

35 Chapter 5 Inter Thread Communication & Deadlock Avoidance OBJECTIVES Inter-thread communication Deadlock 5.1 THREADS Threads enable a single program to run multiple parts of itself at the same time. For example, one part of a program can display an animation on the screen while another part builds the next animation to be displayed. For advanced programmers, threads are a lightweight version of a process. Threads are similar to processes in that they can be executed independently and simultaneously, but are different in that they do not have all the overhead that a process does. Threads do not make copies of the entire parent process. Instead, only the code needed is run in parallel. This means that threads can be started quickly because they don't have all of the overhead of a complete process. They do, however, have complete access to all data of the parent process. Threads can read and/or write data that any other thread can access. This makes interthread communication simpler, but can lead to multiple threads modifying data in an unpredictable manner. Additional programming care is required with threads. Uses of Threads Threads are useful programming tools for two main reasons. First, they enable programs to do multiple things at one time. This is useful for such activities as letting a user do something while something else happens in the 35

36 background. Second, threads enable the programmer to concentrate on program functionality without worrying about the implementation of multitasking schemes. A programmer can simply spin off another thread for some background or parallel operation without being concerned about interprocess communications. Declaring Threads To create classes that make use of threads, you can extend the class Thread or implement the interface Runnable. Both yield the same result. By implementing Runnable, existing classes can be converted to threads without having to change the classes on which they are based. Creating Threads by Extending Thread An example of creating a thread by extending class Thread follows: public class MyMain public static void main (String args[]) CntThread cntthread; //declare thread cntthread = new CntThread(); //create thread cntthread.start(); //start thread running try System.in.read(); //wait for keyboard input catch(java.io.ioexception e) cntthread.stop(); //stop thread class CntThread extends Thread public void run() int ix = 0; while (true) System.out.println("running, ix = " + ix++); //write count to screen try Thread.sleep(1000); //sleep 1 second catch(interruptedexception e) 36

37 Note: To exit the program, press Ctrl+C In this example, a thread is created that will write an incrementing counter to the screen. It will continue to count until the main routine receives a character from the keyboard, at which time the counting thread stops. This means you can press any key on the keyboard followed by the Enter key or press only the Enter key to stop the thread from counting. This is an excellent example of the concept of threads because it introduces the keywords try and catch (discussed in the "Exceptions" section in previous chapter) and also demonstrates the creation and termination of a thread. 5.2 INTER-THREAD COMMUNICATION Inter-thread communication is achieved using four methods: Wait( ) InterruptedException -> Syntax : public final void wait( ) throws Notify( ) -> Syntax : public final void notify( ) notifyall( ) -> Syntax : public final void notifyall( ) yield( ) -> Syntax : public void static yield( ) All these methods are declared final in the Object class. They can only be called from synchronized methods. The following program shows how the problem is solved using the wait( ) and notify( ) methods. Example 1: // Example involving the use of wait, notify & synchronize) class JobOpening int counter; boolean valueset = false; synchronized int get( ) if(!valueset) try wait( ); 37

38 catch(interruptedexception e) System.out.println( Got : +counter); valueset = false; notify( ); return counter; synchronized void put( int counter) if(valueset) try wait( ); catch(interruptedexception e) this.counter = counter; valueset = true; system.out.println( counter); notify( ); class MyThread1 implements Runnable jobopening job; public MyThread1( JobOpening job) this.job = job; new Thread (this,jobproducer ).start( ); public void run( ) int i =0; while(true) job.put(i++); class MyThread2 implements Runnable jobopening job; public MyThread2( JobOpening job) this.job = job; new Thread (this,jobconsumer ).start( ); 38

39 public void run( ) int i =0; while(true) job.get(i++); public static void main(string args[]) JobOpening job =new JobOpening( ); new MyThread1(job); new MyThread2(job); Example 2: // Implementation of a producer and consumer. class Q int n; boolean valueset = false; synchronized int get() if(!valueset) try wait(); catch(interruptedexception e) System.out.println("InterruptedException caught"); System.out.println("Got: " + n); valueset = false; notify(); return n; synchronized void put(int n) if(valueset) try wait(); catch(interruptedexception e) System.out.println("InterruptedException caught"); this.n = n; valueset = true; System.out.println("Put: " + n); notify(); 39

40 class Producer implements Runnable Q q; Producer(Q q) this.q = q; new Thread(this, "Producer").start(); public void run() int i = 0; while(true) q.put(i++); class Consumer implements Runnable Q q; Consumer(Q q) this.q = q; new Thread(this, "Consumer").start(); public void run() while(true) q.get(); class PCFixed public static void main(string args[]) Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); Inside get( ), wait( ) is called. This causes its execution to suspend until the Producer notifies you that some data is ready. When this happens, execution inside get( ) resumes. After the data has been obtained, get( ) calls notify( ). This tells Producer that it is okay to put more data in the queue. Inside put( ), wait( ) suspends execution until the Consumer has removed the item from the queue. 40

41 When execution resumes, the next item of data is put in the queue, and notify( ) is called. This tells the Consumer that it should now remove it. Here is some output from this program, which shows the clean synchronous behavior: Put: 1 Got: 1 Put: 2 Got: 2 Put: 3 Got: 3 Put: 4 Got: 4 Put: 5 Got: DEADLOCK A special type of error that you need to avoid that relates specifically to multitasking is deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects. Deadlock is a difficult error to debug for two reasons: In general it occurs only rarely, when the two threads time slice in just the right way. It may involve more than two threads and two synchronized objects. Example: class A synchronized void foo(b b) String name = Thread.currentThread().getName( ); System.out.println(name + entered A.foo ); try 41

42 Thread.sleep(1000); catch(exception e) System.out.println( A Interrupted ); System.out.println(name + trying to call B.last( ) ); b.last( ); synchronized void last( ) System.out.println( Inside A.last ); class B synchronized void bar(a a) String name = Thread.currentThread().getName( ); System.out.println(name + entered B.bar ); try Thread.sleep(1000); catch(exception e) System.out.println( B Interrupted ); System.out.println(name + trying to call A.last( ) ); a.last( ); synchronized void last( ) System.out.println( Inside A.last ); class Deadlock implements Runnable A a = new A( ); B b = new B( ); Deadlock( ) Thread.currentThread( ).setname ( MainThread ); Thread t = new Thread (this, RacingThread ); t.start(); a.foo(b); System.out.println( Back in main thread thread ); public void run() b.bar(a); 42

43 System.out.println( back in other thread ); public static void main(string args[] ) new Deadlock( ); When you run this program, you will see the output shown here: MainThread entered A.foo RacingThread entered B..bar MainThread trying to call B.last() Racingthread trying to call A.last( ) the program. Because the program has deadlocked, you need to press CTRL-C to end SUMMARY Threads are Java's way of running multiple, parallel code segments simultaneously. They are a lightweight process that does not have all the overhead that a normal process has. Threads are based on the class Thread and can be implemented by either extending class Thread or using the interface Runnable. Using Runnable, you can add threading to existing classes. All threads implement the init, start, stop, and run methods. init is called the first time a thread is started, and it is a good place to put initialization code. start is called any time a thread is started. stop is used to stop the execution of a thread and usually contains code that will terminate the main body of the thread. run is started by start and normally contains the body of the thread code. Inter-thread communication is achieved using four methods: Wait( ), Notify( ), notifyall( ) and yield( ) A special type of error that you need to avoid that relates specifically to multitasking is deadlock, which occurs when two threads have a circular dependency on a pair of synchronized objects. 43

44 Chapter 6 File operations Objectives Streams Reading Console Input Writing Console Outpu Reading and Writing files 6.1 STREAMS Streams in Java provide a way for two or more processes to send information to each other without any of the processes having to know anything about the others. This means that with streams you can write an application or applet that can then pass data to almost any other stream-based application or applet! It is even possible for multiple threads making up a single process to pass data to each other via streams. Streams have many uses in Java and, in fact, are used quite heavily within Java itself. They are used to read and write information to devices, files, databases, network sockets, other processes-almost anything. All stream interfaces implement a basic set of methods that the programmer can use. These methods are common across all stream types, which makes using a new stream type simple. There are a few stream methods found in some Java package extensions, but the standard ones are found in the java.io package. This package must be imported in all applications or applets that make use of threads. There are some extended stream methods that are not always implemented, such as the capability to reset the stream to an earlier point. For 44

45 these cases, there are other methods discussed in the following sections that you can use to check whether extended methods are supported. This makes it possible for a program to take advantage of these methods if they are available. Java 2 defines two types of streams: byte and character. 1. Byte streams classes that provide support for handling I/O operations on bytes, 2. Character stream classes that provide support for managing I/O operations on characters. The diagram given below represent the hierarchy of the byte stream family. FileInputStream InputStream BufferedInputStream FilterInputStream Object DataInputStream OutputStream FileOutputStream BufferedOutputStream FilterOutputStream DataOutputStream PrintStream Byte stream class Hierarchy 45

46 The diagram given below represent the hierarchy of the Character stream family Reader BufferedReader InputStreamReader FileReader Object BufferedWriter Writer OutputStreamWriter PrintWriter FileWriter Charcter stream class Hierarchy 6.2 READING CONSOLE INPUT To read a character from a BufferedReader, use read( ). The version of read( ) that we will be using is int read( ) throws IOException. Each time that read( ) is called, it reads a character from the input stream and returns it as an integer value. It returns 1 when the end of the stream is encountered. As you can see, it can throw an IOException. The following program demonstrates read( ) by reading characters from the console until the user types a q : // Use a BufferedReader to read characters from the console. import java.io.*; class BRRead public static void main(string args[]) throws IOException char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 46

47 System.out.println("Enter characters, 'q' to quit."); // read characters do c = (char) br.read(); System.out.println(c); while(c!= 'q'); Here is a sample run: Enter characters, 'q' to quit. 123abcq a b c q 6.3 WRITING CONSOLE OUTPUT // Demonstrate System.out.write(). class WriteDemo public static void main(string args[]) int b; b = 'A'; System.out.write(b); System.out.write('\n'); output: The following application illustrates using a PrintWriter to handle console // Demonstrate PrintWriter import java.io.*; public class PrintWriterDemo public static void main(string args[]) PrintWriter pw = new PrintWriter(System.out, true); 47

48 pw.println("this is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); The output from this program is shown here: This is a string E READING AND WRITING FILES /* Copy a text file. To use this program, specify the name of the source file and the destination file. For example, to copy a file called FIRST.TXT to a file called SECOND.TXT, use the following command line. java CopyFile FIRST.TXT SECOND.TXT */ import java.io.*; class CopyFile public static void main(string args[]) throws IOException int i; FileInputStream fin; FileOutputStream fout; try // open input file try fin = new FileInputStream(args[0]); catch(filenotfoundexception e) System.out.println("Input File Not Found"); return; // open output file try 48

49 fout = new FileOutputStream(args[1]); catch(filenotfoundexception e) System.out.println("Error Opening Output File"); return; catch(arrayindexoutofboundsexception e) System.out.println("Usage: CopyFile From To"); return; // Copy File try do i = fin.read(); if(i!= -1) fout.write(i); while(i!= -1); catch(ioexception e) System.out.println("File Error"); fin.close(); fout.close)(); Summary Streams are Java's way of reading and writing data to entities outside an application, such as files, networks, devices, or other processes. All streams in Java consist of a flow of 8-bit bytes. Some stream classes allow the writing of other object types, but internally they simply convert these objects to bytes. Streams can be broken into two main types: input streams and output streams. Input streams accept data from an external source. The read method is used to read data from an input stream. 49

50 Skip is used to skip over information in the input stream to get to data farther on. Close simply closes an input stream. The available method can be used to determine if more data is available in an input stream, but the results returned by this method are not always accurate. The mark Supported method is used to determine if a particular stream supports the mark/reset methods. Output streams produce data for an external destination. The write method is used to write data to an output stream. Flush is used to force data to be written that may be buffered. Close simply closes an output stream. Exercise 6.1 Write a Java program to read a string from console using Buffered Reader class. 6.2 Using Java I/O stream classes create a tiny editor. 6.3 Write a program to read a text file, file name should be given in command line argument. 50

51 Chapter 7 Applet OBJECTIVES Java Applet basics Life cycle of an applet An applet tag An applet skeleton 7.1 JAVA APPLET BASICS: Java applets, however run from inside a World Wide Web browser. A reference to an applet is embedded in a web page using a special HTML tag. When a reader using a Java enabled browser loads a web page with an applet in it., the browser downloads that applet from a web server and executes it on the local system ( the one the browser is running on). An applet is also executed using applet viewer application which is part of the JDK. Because Java applets run inside a Java browser, they have the advantage of the structure the browser provides : an existing window, an event handling and graphics context and surrounding user interface. i. Applet do not need a main() method ii. Applets must be run under an applet viewer or a java compatible web browser. iii. User I/O is not accomplished with Java s stream I/O classes. Instead applets use the interface provided by the AWT. 51

52 7.2 Life cycle of an applet You can describe the life cycle of an applet through four methods. These methods are: The init( ) method The start( ) method The stop( ) method The destroy( ) method 7.3 AN APPLET SKELETON import java.awt.*; import java.applet.*; /* <applet code="appletskel" width=300 height=100> </applet> */ public class AppletSkel extends Applet // Called first. public void init() // initialization /* Called second, after init(). Also called whenever the applet is restarted. */ public void start() // start or resume execution // Called when the applet is stopped. public void stop() // suspends execution /* Called when applet is terminated. This is the last method executed. */ public void destroy() // perform shutdown activities 52

53 // Called when an applet's window must be restored. public void paint(graphics g) // redisplay contents of window Example: Let s begin with the simple applet shown here: // Applet example import java.awt.*; import java.applet.*; public class SimpleApplet extends Applet public void paint(graphics g) g.drawstring("a Simple Applet", 20, 20); After you enter the source code for SimpleApplet, compile in the same way that you have been compiling programs. However, running SimpleApplet involves a different process. In fact, there are two ways in which you can run an applet: Executing the applet within a Java-compatible Web browser. Using an applet viewer, such as the standard SDK tool, appletviewer. An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test your applet. To execute an applet in a Web browser, you need to write a short HTML text file that contains the appropriate APPLET tag. Here is the HTML file that executes SimpleApplet: <applet code="simpleapplet" width=200 height=60> </applet> 53

54 7.4 APPLET TAG The APPLET tag is used to embed an applet in an HTML document. The APPLET tag takes zero or more parameters. The syntax for the standard APPLET tag is shown here. Bracketed items are optional. < APPLET [CODEBASE = codebaseurl] CODE = appletfile [ALT = alternatetext] [NAME = appletinstancename] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [< PARAM NAME = AttributeName VALUE = AttributeValue>] [< PARAM NAME = AttributeName2 VALUE = AttributeValue>]... [HTML Displayed in the absence of Java] </APPLET> To execute SimpleApplet with an applet viewer, you may also execute the HTML file shown earlier. For example, if the preceding HTML file is called RunApp.html, then the following command line will run SimpleApplet: Example C:\>appletviewer RunApp.html // Simple applet import java.awt.*; import java.applet.*; public class Hellojava extends Applet 54

55 Example public void paint(graphics g) g.drawstring("jnf GTJ PTL VBJ",10,100); // html file <applet code = Hellojava width =200 height=60> </applet> // to display a string import java.awt.*; import java.applet.*; public class Hellojavaparam extends Applet String str; public void init() str = getparameter("string"); if(str == null) str = "JAVA"; str = "HeLLo" + str; public void paint(graphics g) g.drawstring(str,10,100); //html file <html> <! parameterized html file> <head> <title> WELCOME TO JAVA APPLETS </title> <head> <body> <applet code = Helljavaparam.class width = 400 height = 200> <param name = "string" value = "applet "> </applet> </body> </html> 55

56 SUMMARY This chapter has explored the java.applet.applet and java.lang packages from the Java API. The java.lang package contains classes associated with basic data structures in Java as well as Java-wide exceptions. The java.applet package is used to create an applet instance and to perform applet-specific functions. Applets require the presence of a browser or applet viewer, and the Applet methods rely on this environment. Exercise 7.1 Write a simple applet program to add two numbers Write a applet program to get user input. 7.3 Write a applet program to sets the foreground and background colors and outputs a string. 7.4 Design a applet program to paint a message by changing the color and font. 56

57 Chapter 8 Java Database Connectivity (JDBC) OBJECTIVES JDBC API JDBC Driver Manager JDBC ODBC Bridge Connecting to a database Using Select Using Update Using JDBC in servlets 8.1 JDBC API This section explains the techniques of database programming using Java. JDBC provides a database programming API for Java programs. Since the ODBC API is written in the C language and makes use of pointers and other constructs that Java does not support, a Java program cannot directly communicate with an ODBC driver. There are several categories of JDBC drivers available. They are JDBC-ODBC bridge + ODBC driver Native API partly Java driver JDBC-Net pure Java driver Native protocol pure Java driver Using Select 57

58 8.2 JDBC DRIVER MANAGER The function of the JDBC driver manager is to connect a Java application to the appropriate driver specified in your Java program. 8.3 JDBC ODBC BRIDGE As a part of JDBC Sun Microsystems provides a driver to access ODBC data sources from JDBC. This driver is called the JDBC-ODBC bridge is implemented as the JdbcOdbc.class and a native library is used to access the ODBC driver. In the windows platform the native library is JDBCODBC.DLL. 8.4 CONNECTING TO A DATABASE The java.sql package contains classes that help in connecting to a database, sending embedded SQL statements to the database and processing query results. (i) The Connection Object The Connection object represents a connection with a database. You may have several Connection objects in an application that connects to one or more databases. (ii) Loading the JDBC-ODBC bridge and establishing the connection To establish a connection with a database you need to register the ODBC- JDBC driver by calling the forname( ) method from the Class class and then calling the getconnection( ) method from the DriverManager class. The getconnection( ) method of the DriverManager class attempts to locaie the driver that can connect to the database represented by the JDBC URL passed to the getconnection ( ) method. 58

59 (iii) The JDBC URL The JDBC URL is string that provides a way of identifying a database. A JDBC URL is dividec into three parts. <protocol> : <subprotocol >: <subname> In this <protocol> in a JDBC URL is always jdbc. <subprotocol> is the name of the database connectivity mechanism. <subname> is used to identify the database. Example: import java.sql.* ; class JDBCQuery public static void main( String args[] ) try // Load the database driver Class.forName( "sun.jdbc.odbc.jdbcodbcdriver" ) ; // Get a connection to the database Connection conn = DriverManager.getConnection( "jdbc:odbc:database" ) ; // Print all warnings for( SQLWarning warn = conn.getwarnings(); warn!= null; warn = warn.getnextwarning() ) System.out.println( "SQL Warning:" ) ; System.out.println( "State : " + warn.getsqlstate() ) ; System.out.println( "Message: " + warn.getmessage() ) ; System.out.println( "Error : " + warn.geterrorcode() ) ; // Get a statement from the connection Statement stmt = conn.createstatement() ; // Execute the query 59

60 ResultSet rs = stmt.executequery( "SELECT * FROM Cust" ) ; // Loop through the result set while( rs.next() ) System.out.println( rs.getstring(1) ) ; // Close the result set, statement and the connection rs.close() ; stmt.close() ; conn.close() ; catch( SQLException se ) System.out.println( "SQL Exception:" ) ; // Loop through the SQL Exceptions while( se!= null ) System.out.println( "State : " + se.getsqlstate() ) ; System.out.println( "Message: " + se.getmessage() ) ; System.out.println( "Error : " + se.geterrorcode() ) ; se = se.getnextexception() ; catch( Exception e ) System.out.println( e ) ; 8.5 USING SELECT import java.net.url; import java.sql.*; class Select public static void main(string argv[]) try // Load the database driver Class.forName( "sun.jdbc.odbc.jdbcodbcdriver" ) ; 60

61 // Create a URL specifying an ODBC data source name. String url = "jdbc:odbc:wombat"; // Connect to the database at that URL. Connection con = DriverManager.getConnection(url); // Execute a SELECT statement Statement stmt = con.createstatement(); ResultSet rs = stmt.executequery("select a, b, c, d, key FROM table1"); // Step through the result rows. System.out.println("Got results:"); while (rs.next()) // get the values from the current row: int a = rs.getint(1); BigDecimal b = rs.getbigdecimal(2); char c[] = rs.getstring(3).tochararray(); boolean d = rs.getboolean(4); String key = rs.getstring(5); // Now print out the results: System.out.print(" key=" + key); System.out.print(" a=" + a); System.out.print(" b=" + b); System.out.print(" c="); for (int i = 0; i < c.length; i++) System.out.print(c[i]); System.out.print(" d=" + d); System.out.print("\n"); stmt.close(); con.close(); catch (java.lang.exception ex) ex.printstacktrace(); 61

62 8.6 USING UPDATE import java.net.url; import java.sql.*; class Update public static void main(string argv[]) try // Load the database driver Class.forName( "sun.jdbc.odbc.jdbcodbcdriver" ) ; // Create a URL specifying an ODBC data source name. String url = "jdbc:odbc:wombat"; // Connect to the database at that URL. Connection con = DriverManager.getConnection(url); // Create a prepared statement to update the "a" field of a // row in the "Table1" table. // The prepared statement takes two parameters. PreparedStatement stmt = con.preparestatement( "UPDATE Table1 SET a =? WHERE key =?"); // First use the prepared statement to update // the "count" row to 34. stmt.setint(1, 34); stmt.setstring(2, "count"); stmt.executeupdate(); System.out.println("Updated \"count\" row OK."); // Now use the same prepared statement to update the // "mirror" field. // We rebind parameter 2, but reuse the other parameter. stmt.setstring(2, "mirror"); stmt.executeupdate(); System.out.println("Updated \"mirror\" row OK."); stmt.close(); con.close(); catch (java.lang.exception ex) ex.printstacktrace(); 62

63 8.7 USING JDBC IN SERVLETS import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class JDBCServlet extends HttpServlet public void doget(httpservletrequest inrequest, HttpServletResponse outresponse) throws ServletException, IOException PrintWriter out = null; Connection connection = null; Statement statement; ResultSet rs; try Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection = DriverManager.getConnection("jdbc:odbc:demo"); statement = connection.createstatement(); outresponse.setcontenttype("test/html"); out = outresponse.getwriter(); rs = statement.executequery("select ID, title, price FROM product"); out.println("<html><head><title>products</title></head>"); out.println("<body>"); out.println("<ul>"); while (rs.next()) out.println("<li>" + rs.getstring("id") + " " + rs.getstring("title") + " " + rs.getstring("price")); out.println("</ul>"); out.println("</body></html>"); catch (ClassNotFoundException e) out.println("driver Error"); catch (SQLException e) out.println("sqlexception: " + e.getmessage()); public void dopost(httpservletrequest inrequest, HttpServletResponse outresponse) throws ServletException, 63

64 IOException doget(inrequest, outresponse); SUMMARY JDBC provides a database programming API for Java programs. There are several categories of JDBC drivers available: JDBC-ODBC bridge + ODBC driver, Native API partly Java Java driver, Native protocol pure Java driver, Using Select driver, JDBC-Net pure The java.sql package contains classes that help in connecting to a database, sending embedded SQL statements to the database and processing query results. The Connection object represents a connection with a database. To establish a connection with a database you need to register the ODBC- JDBC driver by calling the forname( ) method from the Class class and then calling the getconnection( ) method from the DriverManager class. The JDBC URL is string that provides a way of identifying a database. 64

65 Chapter 9 Java Native Interface (JNI) OBJECTIVES JNI basics Compiling and Running 9.1 JNI BASICS The Java Native Interface (JNI) is the native programming interface for Java that is part of the JDK. By writing programs using the JNI, you ensure that your code is completely portable across all platforms. The JNI allows Java code that runs within a Java Virtual Machine (VM) to operate with applications and libraries written in other languages, such as C, C++, and assembly. In addition, the Invocation API allows you to embed the Java Virtual Machine into your native applications. For example, the following figure shows how a legacy C program can use the JNI to link with Java libraries, call Java methods, use Java classes, and so on. 65

66 9.2 COMPILING AND RUNNING A JAVA PROGRAM WITH A NATIVE METHOD This chapter implements the canonical "Hello World!" program. The "Hello World!" program has one Java class, called HelloWorld. HelloWorld.java does two things: it declares a native method that displays "Hello World!" and it implements the main method for the overall program. The implementation for the native method is provided in C. Writing native methods for Java programs is a multi-step process. 1. Begin by writing the Java program. Create a Java class that declares the native method; this class contains the declaration or signature for the native method. It also includes a main method which calls the native method. 2. Compile the Java class that declares the native method and the main method. 3. Generate a header file for the native method using javah with the native interface flag -jni. Once you've generated the header file you have the formal signature for your native method. 4. Write the implementation of the native method in the programming language of your choice, such as C or C Compile the header and implementation files into a shared library file. 6. Run the Java program. 66

67 The following figure illustrates these steps for the Hello World program: Step 1: Write the Java Code Create a Java class named HelloWorld that declares a native method. This class also includes a main method that creates a HelloWorld object and calls the native method. 67

68 Step 2: Compile the Java Code Use javac to compile the Java code that you wrote in Step 1. Step 3: Create the.h File Use javah to create a JNI-style header file (a.h file) from the HelloWorld class. The header file provides a function signature for the implementation of the native method displayhelloworld. Step 4: Write the Native Method Implementation Write the implementation for the native method in a native language (such as ANSI C) source file. The implementation will be a regular function that's integrated with your Java class. Step 5: Create a Shared Library Use the C compiler to compile the.h file and the.c file that you created in Steps 3 and 4 into a shared library. In Windows 95/NT terminology, a shared library is called a dynamically loadable library DLL. Step 6: Run the Program And finally, use java, the Java interpreter, to run the program. Step 1: Write the Java Code The following Javacode segment defines a class named HelloWorld. This class declares one native method, implements a main method, and has a static code segment. class HelloWorld public native void displayhelloworld(); static System.loadLibrary("hello"); 68

69 public static void main(string[] args) new HelloWorld().displayHelloWorld(); Declare a Native Method You must declare all methods, whether Java methods or native methods, within a class on the Java side. When you write a method implementation in a language other than Java, you must include the keyword native as part of the method's definition within the Java class. The native keyword signals to the Java compiler that the function is a native language function. It is easy to tell that the implementation for the HelloWorld class's displayhelloworld method is written in another programming language because the native keyword appears as part of its method definition: public native void displayhelloworld(); This native method declaration in your Java class provides only the method signature for displayhello World. It provides no implementation for the method. You must provide the implementation for displayhelloworld in a separate native language source file. The method declaration for displayhello World also indicates that the method is a public instance method, accepts no arguments, and returns no value. For more information about arguments to and return values from native methods see Interacting with Java from the Native Side. Load the Library You compile the native language code that implements displayhelloworld into a shared library (you will do this in Step 5: Create a Shared Library). The runtime system later loads the shared library into the Java class that requires it. 69

70 Loading the library into the Java class maps the implementation of the native method to its declaration. The HelloWorld class uses the System.loadLibrary method. The System.loadLibrary method loads the shared library that will be created when you compile the implementation code. Place this method within a static initializer. The argument to System.loadLibrary is the shared library name. This can be any name that you choose. The system uses a standard, but platformspecific, approach to convert the library name to a native library name. For example, the Solaris system converts the library name "hello" to libhello.so, while a Win32 system converts the same name to hello.dll. The following static initializer from the HelloWorld class loads the appropriate library, named hello. The runtime system executes a class's static initializer when it loads the class. static System.loadLibrary("hello"); Write the Main Method The HelloWorld class, because it is an application, also includes a main method to instantiate the class and call the native method. The main method instantiates HelloWorld and calls the displayhelloworld native method. public static void main(string[] args) new HelloWorld().displayHelloWorld(); You can see from the code sample that you call a native method in the same manner as you call a regular method: just append the name of the method to the end of the object name, separated with a period ('.'). A matched set of 70

71 parentheses, (), follow the method name and enclose any arguments to pass into the method. The displayhelloworld method doesn't take any arguments. Step 2: Compile the Java Code Use the Java compiler to compile the class that you created in the previous step. Here's the command to use: javac HelloWorld.java Step 3: Create the.h File In this step, you use the javah utility program to generate a header file (a.h file) from the HelloWorld class. The header file provides a C function signature for the implementation of the native method displayhelloworld defined in that class. Run javah now on the HelloWorld class that you created in the previous steps. The name of the header file is the Java class name with a.h appended to the end. For example, the command shown above will generate a file named HelloWorld.h. By default, javah places the new.h file in the same directory as the.class file. Use the -d option to instruct javah to place the header files in a different directory. The Function Definition Look at the header file HelloWorld.h. #includejava example-1dot1/helloworld.h The Java_HelloWorld_displayHelloWorld function provides the implementation for the HelloWorld class's native method displayhelloworld, which you will write in Step 4: Write the Native Method Implementation. You use the same function signature when you write the implementation for the native method. If HelloWorld contained any other native methods, their function signatures would appear here as well. The name of the native language function that implements the native method consists of the prefix Java_, the package 71

72 name, the class name, and the name of the native method. Between each name component is an underscore "_" separator. Graphically, this looks as follows: Step 4: Write the Native Method Implementation Now, you can finally write the implementation for the native method in a language other than Java. Note: Back to that "real world," C and C++ programmers may already have existing implementations of native methods. For those "real" methods, you need only ensure that the native method signature matches the signature generated on the Java side. The function that you write must have the same function signature as the one generated by javah in the HelloWorld.h file in Step 3: Create the.h File. Recall that the function signature generated for the HelloWorld class's displayhelloworld native method looks like this: JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *, jobject); Here's the C language implementation for the native method Java_HelloWorld_displayHelloWorld. 72

73 This implementation is in the file named HelloWorldImp.c. #include <jni.h> #include "HelloWorld.h" #include <stdio.h> JNIEXPORT void JNICALL Java_HelloWorld_displayHelloWorld(JNIEnv *env, jobject obj) printf("hello world!\n"); return; The implementation for Java_HelloWorld_displayHelloWorld is straight forward. The function uses the printf function to display the string "Hello World!" and then returns. The HelloWorldImp.c file includes three header files: 1. jni.h - This header file provides information that the native language code requires to interact with the Java runtime system. When writing native methods, you must always include this file in your native language source files. 2. HelloWorld.h - The.h file that you generated in Step 3: Create the.h File. 3. stdio.h - The code snippet above includes stdio.h because it uses the printf function. The printf function is part of the stdio.h library. Step 5: Create a Shared Library Remember in Step 1: Write the Java Code you used the following method call to load a shared library named hello into your program at runtime: System.loadLibrary("hello"); Now you are ready to create this shared library. In the previous step, Step 4: Write the Native Method Implementation, you created a C file in which you wrote the implementation for the displayhello World native method. You saved 73

74 the native method in the file HelloWorldImp.c. Now, you must compile HelloWorldImp.c into a shared library, which you name hello to match the library name used in the System.loadLibrary method. Compile the native language code that you created in the previous two steps into a shared library. On Solaris, you'll create a shared library, while on Windows 95/NT you'll create a dynamic link library (DLL). Remember to specify the path or paths to all necessary header files. See Creating and Loading Shared Libraries for information on forming a shared library name. On Solaris, the following command builds a shared library libhello.so: cc -G -I/usr/local/java/include -I /usr/local/java/include/solaris \ HelloWorldImp.c -o libhello.so On Win32, the following command builds a dll (hello.dll) using Microsoft Visual C++ 4.0: cl -Ic:\java\include -Ic:\java\include\win32 -LD HelloWorldImp.c -Fehello.dll Of course, you need to specify the include path that corresponds to the setup on your own machine.for more information on the system-dependent mechanisms for loading a shared library, see Creating and Loading Shared Libraries. Step 6: Run the Program Now run the Java application (the HelloWorld class) with the Java interpreter, as follows: java HelloWorld You should see the following output: Hello World! 74

75 If you see exception like the following, then you don't have your library path set up correctly. java.lang.unsatisfiedlinkerror: no hello in shared library path at java.lang.runtime.loadlibrary(runtime.java) at java.lang.system.loadlibrary(system.java) at at java.lang.thread.init(thread.java) The library path is a list of directories that the Java runtime system searches when loading libraries. Set your library path now, and make sure that the name of the directory where the hello library lives is in it. Summary The Java Native Interface (JNI) is the native programming interface for Java that is part of the JDK. Writing native methods for Java programs is a multi-step process. o Begin by writing the Java program. Create a Java class that declares the native method; this class contains the declaration or signature for the native method. It also includes a main method which calls the native method. o Compile the Java class that declares the native method and the main method. o Generate a header file for the native method using javah with the native interface flag -jni. Once you've generated the header file you have the formal signature for your native method. o Write the implementation of the native method in the programming language of your choice, such as C or C++. o Compile the header and implementation files into a shared library file. o Run the Java program. 75

76 Chapter 10 Remote Method Invocation (RMI) OBJECTIVES RMI Terminology RMI Packages RMI interfaces and classes Compiling and Running 10.1 RMI TERMINOLOGY Java s RMI approach is organized into a client/server framework. A local object that invokes a method of a remote object is referred to as a client object, and the remote object whose methods are invoked is referred to as s server object. Java s RMI approach makes use of stubs and skeletons. A stub is a local object on the client s machine that act as a proxy for a remote object. The skeleton is the proxy of the client machine s object that is located on the remote host. Remote Method Invocation (RMI) allows a Java object that executes on one machine to invoke a method of Java object that executes on another machine RMI PACKAGES Java provides the following packages for remote method invocation: 1. The java.rmi package provides the Remote interface, aclass for accessing the remote names registered on the server, and a security manager for RMI. 2. The java.rmi.registry package provides classes and interfaces that are used by the remote registry. 76

77 3. The java.rmi.server package provides classes and interfaces that areused to implement remote object stubs and skeleton. 4. The java.rmi.dgc package provides classes and interfaces that are used by the RMI distributed garbage collector RMI INTERFACES AND CLASSES Core packages for RMI: java.rmi java.rmi.server Main interface for RMI: java.rmi.remote Core classes for RMI: java.rmi.server.unicastremoteobject java.rmi.remoteexception java.rmi.naming 10.3 COMPILING & RUNNING A SIMPLE CLIENT/SERVER source files. APPLICATION USING RMI Step One: Enter and Compile the Source Code This application uses four (i) The first file, AddServerIntf.java import java.rmi.*; public interface AddServerIntf extends Remote double add(double d1, double d2) throws RemoteException; (ii) The second source file, AddServerImpl.java import java.rmi.*; import java.rmi.server.*; public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf public AddServerImpl() throws RemoteException public double add(double d1, double d2) throws RemoteException 77

78 return d1 + d2; (iii) The third source file, AddServer.java import java.net.*; import java.rmi.*; public class AddServer public static void main(string args[]) try AddServerImpl addserverimpl = new AddServerImpl(); Naming.rebind("AddServer", addserverimpl); catch(exception e) System.out.println("Exception: " + e); (iv) The fourth source file, AddClient.java import java.rmi.*; public class AddClient public static void main(string args[]) try String addserverurl = "rmi://" + args[0] + "/AddServer"; AddServerIntf addserverintf = AddServerIntf)Naming.lookup (addserverurl); System.out.println("The first number is: " + args[1]); double d1 = Double.valueOf(args[1]).doubleValue(); System.out.println("The second number is: " + args[2]); double d2 = Double.valueOf(args[2]).doubleValue(); System.out.println("The sum is: " + addserverintf.add(d1, d2)); catch(exception e) System.out.println("Exception: " + e); 78

79 Step Two: Generate Stubs and Skeletons. To generate stubs and skeletons, you use a tool called the RMI compiler, which is invoked from the command line, as shown here: rmic AddServerImpl Step Three: Install Files on the Client and Server Machines Copy AddClient.class, AddServerImpl _ Stub.class, and AddServerIntf.class to a directory on the client machine. Copy AddServerIntf.class, AddServerImpl.class, AddServerImpl _Skel.class, AddServerImpl_Stub.class, and AddServer.class to a directory on The server machine. Step Four: Start the RMI Registry on the Server Machine start the RMI Registry from the command line, as shown here: start rmiregistry Step Five: Start the Server Step Six: Start the Client The AddClient software requires three arguments: the name or IP address of the server machine and the two numbers that are to be summed together java AddClient server1 8 9 java AddClient sample output from this program is shown here: The first number is: 8 The second number is: 9 The sum is:

80 SUMMARY Remote Method Invocation (RMI) allows a Java object that executes on one machine to invoke a method of Java object that executes on another machine. Java s RMI approach is organized into a client/server framework. Java s RMI approach makes use of stubs and skeletons. A stub is a local object on the client s machine that act as a proxy for a remote object. The skeleton is the proxy of the client machine s object that is located on the remote host. EXERCISE 10.1 Write a java application program to find the length of a string using RMI Write a java applet to read the content of a file using RMI Write a applet program to get the user input and find the sum of the input using RMI. 80

81 Chapter 11 Servlets OBJECTIVES Basic servlet structure Servlet that generates HTML code Servlet that handles Post request Servlet that uses Cookies Sessions Tracking 11.1 INTRODUCTION Java servlets are a key component of server-side Java development. A servlet is a small, pluggable extension to a server that enhances the server s functionality. Servlets allow developers to extend and customize any Javaenabled server a web server, a mail server, an application server, or any custom server with a hitherto unknown degree of portability, flexibility, and ease. A servlet is a generic server extension a Java class that can be loaded dynamically to expand the functionality of a server. Servlets are commonly used with web servers, where they can take the place of CGI scripts. A servlet is similar to a proprietary server extension, except that it runs inside a Java Virtual Machine (JVM) on the server (see Figure 11.1), so it is safe and portable. Servlets operate solely within the domain of the server: unlike applets, they do not require support for Java in the web browser. 81

82 Figure 11.1 The servlet life cycle Because servlets run within the web server, they can interact very closely with the server to do things that are not possible with CGI scripts. Another advantage of servlets is that they are portable: both across operating systems as we are used to with Java and also across web servers. Basic Servlet structure For any servlet we need to import two packages: java.servlet.* java.servlet.http.* Any servlet class must extend the class HttpServlet. A servlet must also handle two interrupts: ServletException IOException A servlet can handle two types of request from an html document: GET request POST request To handle GET request we write code in doget() method. To handle POST request we write code in dopost() method. The doget method takes two parameters: HttpServletRequest request from HTML document HttpServletResponse response to the request 82

Synchronization synchronization.

Synchronization synchronization. Unit 4 Synchronization of threads using Synchronized keyword and lock method- Thread pool and Executors framework, Futures and callable, Fork-Join in Java. Deadlock conditions 1 Synchronization When two

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: www: materials: e-learning environment: office: alt. office: jkizito@cis.mak.ac.ug http://serval.ug/~jona http://serval.ug/~jona/materials/csc1214

More information

Byte and Character Streams. Reading and Writing Console input and output

Byte and Character Streams. Reading and Writing Console input and output Byte and Character Streams Reading and Writing Console input and output 1 I/O basics The io package supports Java s basic I/O (input/output) Java does provide strong, flexible support for I/O as it relates

More information

Multithreaded Programming

Multithreaded Programming Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes

More information

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet About Applets Module 5 Applets An applet is a little application. Prior to the World Wide Web, the built-in writing and drawing programs that came with Windows were sometimes called "applets." On the Web,

More information

04-Java Multithreading

04-Java Multithreading 04-Java Multithreading Join Google+ community http://goo.gl/u7qvs You can ask all your doubts, questions and queries by posting on this G+ community during/after webinar http://openandroidlearning.org

More information

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B

1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these. Answer: B 1. Java is a... language. A. moderate typed B. strogly typed C. weakly typed D. none of these 2. How many primitive data types are there in Java? A. 5 B. 6 C. 7 D. 8 3. In Java byte, short, int and long

More information

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B Contents About the Course...xv Course Overview... xvi Course Map... xvii Module-by-Module Overview... xviii Course Objectives... xxii Skills Gained by Module... xxiii Guidelines for Module Pacing... xxiv

More information

Core JAVA Training Syllabus FEE: RS. 8000/-

Core JAVA Training Syllabus FEE: RS. 8000/- About JAVA Java is a high-level programming language, developed by James Gosling at Sun Microsystems as a core component of the Java platform. Java follows the "write once, run anywhere" concept, as it

More information

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. Preface p. xix Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. 5 Java Applets and Applications p. 5

More information

PROGRAMMING LANGUAGE 2

PROGRAMMING LANGUAGE 2 1 PROGRAMMING LANGUAGE 2 Lecture 13. Java Applets Outline 2 Applet Fundamentals Applet class Applet Fundamentals 3 Applets are small applications that are accessed on an Internet server, transported over

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Core Java Contents. Duration: 25 Hours (1 Month)

Core Java Contents. Duration: 25 Hours (1 Month) Duration: 25 Hours (1 Month) Core Java Contents Java Introduction Java Versions Java Features Downloading and Installing Java Setup Java Environment Developing a Java Application at command prompt Java

More information

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output

COMP 213. Advanced Object-oriented Programming. Lecture 19. Input/Output COMP 213 Advanced Object-oriented Programming Lecture 19 Input/Output Input and Output A program that read no input and produced no output would be a very uninteresting and useless thing. Forms of input/output

More information

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA

CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 1. JIT meaning a. java in time b. just in time c. join in time d. none of above CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 2. After the compilation of the java source code, which file is created

More information

JAVA. Lab 12 & 13: Multithreading

JAVA. Lab 12 & 13: Multithreading JAVA Prof. Navrati Saxena TA: Rochak Sachan Lab 12 & 13: Multithreading Outline: 2 What is multithreaded programming? Thread model Synchronization Thread Class and Runnable Interface The Main Thread Creating

More information

Reading and Writing Files

Reading and Writing Files Reading and Writing Files 1 Reading and Writing Files Java provides a number of classes and methods that allow you to read and write files. Two of the most often-used stream classes are FileInputStream

More information

SELF-STUDY. Glossary

SELF-STUDY. Glossary SELF-STUDY 231 Glossary HTML (Hyper Text Markup Language - the language used to code web pages) tags used to embed an applet. abstract A class or method that is incompletely defined,

More information

1.00 Lecture 30. Sending information to a Java program

1.00 Lecture 30. Sending information to a Java program 1.00 Lecture 30 Input/Output Introduction to Streams Reading for next time: Big Java 15.5-15.7 Sending information to a Java program So far: use a GUI limited to specific interaction with user sometimes

More information

S.E. Sem. III [CMPN] Object Oriented Programming Methodology

S.E. Sem. III [CMPN] Object Oriented Programming Methodology S.E. Sem. III [CMPN] Object Oriented Programming Methodology Time : 3 Hrs.] Prelim Question Paper Solution [Marks : 80 Q.1(a) Write a program to calculate GCD of two numbers in java. [5] (A) import java.util.*;

More information

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

Inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. Unit-2 Inheritance: Inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. The general form of a class declaration that inherits a super class is

More information

Chapter 1 Introduction to Java

Chapter 1 Introduction to Java What is Java? Chapter 1 Introduction to Java Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows,

More information

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003 Input, Output and Exceptions COMS W1007 Introduction to Computer Science Christopher Conway 24 June 2003 Input vs. Output We define input and output from the perspective of the programmer. Input is data

More information

Lecture 11.1 I/O Streams

Lecture 11.1 I/O Streams 21/04/2014 Ebtsam AbdelHakam 1 OBJECT ORIENTED PROGRAMMING Lecture 11.1 I/O Streams 21/04/2014 Ebtsam AbdelHakam 2 Outline I/O Basics Streams Reading characters and string 21/04/2014 Ebtsam AbdelHakam

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20

File IO. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 20 File IO Computer Science and Engineering College of Engineering The Ohio State University Lecture 20 I/O Package Overview Package java.io Core concept: streams Ordered sequences of data that have a source

More information

JAVA. Duration: 2 Months

JAVA. Duration: 2 Months JAVA Introduction to JAVA History of Java Working of Java Features of Java Download and install JDK JDK tools- javac, java, appletviewer Set path and how to run Java Program in Command Prompt JVM Byte

More information

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE

More information

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7)

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7) Software Development & Education Center Java Platform, Standard Edition 7 (JSE 7) Detailed Curriculum Getting Started What Is the Java Technology? Primary Goals of the Java Technology The Java Virtual

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS. To define a class, use the class keyword and the name of the class:

UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS. To define a class, use the class keyword and the name of the class: UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS 1. Defining Classes, Class Name To define a class, use the class keyword and the name of the class: class MyClassName {... If this class is a subclass

More information

WOSO Source Code (Java)

WOSO Source Code (Java) WOSO 2017 - Source Code (Java) Q 1 - Which of the following is false about String? A. String is immutable. B. String can be created using new operator. C. String is a primary data type. D. None of the

More information

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure. Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

Core Java Syllabus. Overview

Core Java Syllabus. Overview Core Java Syllabus Overview Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java

More information

1 OBJECT-ORIENTED PROGRAMMING 1

1 OBJECT-ORIENTED PROGRAMMING 1 PREFACE xvii 1 OBJECT-ORIENTED PROGRAMMING 1 1.1 Object-Oriented and Procedural Programming 2 Top-Down Design and Procedural Programming, 3 Problems with Top-Down Design, 3 Classes and Objects, 4 Fields

More information

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question) CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers

More information

Roll Number. Common to II Year B.E.CSE & EIE INTERNAL ASSESSMENT TEST - I. Credit 3 R-2017

Roll Number. Common to II Year B.E.CSE & EIE INTERNAL ASSESSMENT TEST - I. Credit 3 R-2017 Roll Number ERODE SENGTHAR ENGINEERING COLLEGE PERDURI, ERODE 638 057 (Accredited by NBA, Accredited by NAAC with A grade, Accredited by IE (I), Kolkotta, Permanently affiliated to Anna University, Chennai

More information

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 OOP THROUGH JAVA (Common to CT, CM and IF)

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 OOP THROUGH JAVA (Common to CT, CM and IF) TED (10)-3069 (REVISION-2010) Reg. No.. Signature. FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- MARCH, 2012 OOP THROUGH JAVA (Common to CT, CM and IF) (Maximum marks: 100) [Time: 3 hours

More information

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

Goals. Java - An Introduction. Java is Compiled and Interpreted. Architecture Neutral & Portable. Compiled Languages. Introduction to Java

Goals. Java - An Introduction. Java is Compiled and Interpreted. Architecture Neutral & Portable. Compiled Languages. Introduction to Java Goals Understand the basics of Java. Introduction to Java Write simple Java Programs. 1 2 Java - An Introduction Java is Compiled and Interpreted Java - The programming language from Sun Microsystems Programmer

More information

SIMPLE APPLET PROGRAM

SIMPLE APPLET PROGRAM APPLETS Applets are small applications that are accessed on Internet Server, transported over Internet, automatically installed and run as a part of web- browser Applet Basics : - All applets are subclasses

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.1) Exception Handling 1 Outline Exception Handling Mechanisms Exception handling fundamentals Exception Types Uncaught exceptions Try and catch Multiple catch

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries 1 CONTENTS 1. Introduction to Java 2. Holding Data 3. Controllin g the f l o w 4. Object Oriented Programming Concepts 5. Inheritance & Packaging 6. Handling Error/Exceptions 7. Handling Strings 8. Threads

More information

Introduction to Java

Introduction to Java Introduction to Java Module 1: Getting started, Java Basics 22/01/2010 Prepared by Chris Panayiotou for EPL 233 1 Lab Objectives o Objective: Learn how to write, compile and execute HelloWorld.java Learn

More information

F I N A L E X A M I N A T I O N

F I N A L E X A M I N A T I O N Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student

More information

15CS45 : OBJECT ORIENTED CONCEPTS

15CS45 : OBJECT ORIENTED CONCEPTS 15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?

More information

Unit 1- Java Applets. Applet Programming. Local Applet and Remote Applet ** Applet and Application

Unit 1- Java Applets. Applet Programming. Local Applet and Remote Applet ** Applet and Application Applet Programming Applets are small Java applications that can be accessed on an Internet server, transported over Internet, and can be automatically installed and run as a part of a web document. An

More information

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Modern Programming Languages. Lecture Java Programming Language. An Introduction Modern Programming Languages Lecture 27-30 Java Programming Language An Introduction 107 Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is significantly

More information

1993: renamed "Java"; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java

1993: renamed Java; use in a browser instead of a microwave : Sun sues Microsoft multiple times over Java Java history invented mainly by James Gosling ([formerly] Sun Microsystems) 1990: Oak language for embedded systems needs to be reliable, easy to change, retarget efficiency is secondary implemented as

More information

Special error return Constructors do not have a return value What if method uses the full range of the return type?

Special error return Constructors do not have a return value What if method uses the full range of the return type? 23 Error Handling Exit program (System.exit()) usually a bad idea Output an error message does not help to recover from the error Special error return Constructors do not have a return value What if method

More information

Java Professional Certificate Day 1- Bridge Session

Java Professional Certificate Day 1- Bridge Session Java Professional Certificate Day 1- Bridge Session 1 Java - An Introduction Basic Features and Concepts Java - The new programming language from Sun Microsystems Java -Allows anyone to publish a web page

More information

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started Application Development in JAVA Duration Lecture: Specialization x Hours Core Java (J2SE) & Advance Java (J2EE) Detailed Module Part I: Core Java (J2SE) Getting Started What is Java all about? Features

More information

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003 The University of Melbourne Department of Computer Science and Software Engineering 433-254 Software Design Semester 2, 2003 Answers for Tutorial 7 Week 8 1. What are exceptions and how are they handled

More information

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine

needs to be reliable, easy to change, retarget efficiency is secondary implemented as interpreter, with virtual machine Java history invented mainly by James Gosling ([formerly] Sun Microsystems) 1990: Oak language for embedded systems needs to be reliable, easy to change, retarget efficiency is secondary implemented as

More information

Prashanth Kumar K(Head-Dept of Computers)

Prashanth Kumar K(Head-Dept of Computers) B.Sc (Computer Science) Object Oriented Programming with Java and Data Structures Unit-IV 1 1. What is Thread? Thread is a task or flow of execution that can be made to run using time-sharing principle.

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

CS506 Web Design & Development Final Term Solved MCQs with Reference

CS506 Web Design & Development Final Term Solved MCQs with Reference with Reference I am student in MCS (Virtual University of Pakistan). All the MCQs are solved by me. I followed the Moaaz pattern in Writing and Layout this document. Because many students are familiar

More information

Introduction Welcome! Before you start Course Assessments The course at a glance How to pass M257

Introduction Welcome! Before you start Course Assessments The course at a glance How to pass M257 Introduction Unit 1: Java Everywhere Prepared by: Dr. Abdallah Mohamed, AOU-KW 1 Introduction Welcome! Before you start Course Assessments The course at a glance How to pass M257 1. Java background 2.

More information

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Information Science and Engineering

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Information Science and Engineering INTERNAL ASSESSMENT TEST 2 Date : 28-09-15 Max Marks :50 Subject & Code : JAVA&J2EE(10IS753) Section: VII A&B Name of faculty : Mr.Sreenath M V Time : 11.30-1.00 PM Note: Answer any five questions 1) a)

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

7. MULTITHREDED PROGRAMMING

7. MULTITHREDED PROGRAMMING 7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread

More information

Exceptions and Working with Files

Exceptions and Working with Files Exceptions and Working with Files Creating your own Exceptions. You have a Party class that creates parties. It contains two fields, the name of the host and the number of guests. But you don t want to

More information

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java

More information

Java Programming Course Overview. Duration: 35 hours. Price: $900

Java Programming Course Overview. Duration: 35 hours. Price: $900 978.256.9077 admissions@brightstarinstitute.com Java Programming Duration: 35 hours Price: $900 Prerequisites: Basic programming skills in a structured language. Knowledge and experience with Object- Oriented

More information

Note: Each loop has 5 iterations in the ThreeLoopTest program.

Note: Each loop has 5 iterations in the ThreeLoopTest program. Lecture 23 Multithreading Introduction Multithreading is the ability to do multiple things at once with in the same application. It provides finer granularity of concurrency. A thread sometimes called

More information

CMSC 331 Second Midterm Exam

CMSC 331 Second Midterm Exam 1 20/ 2 80/ 331 First Midterm Exam 11 November 2003 3 20/ 4 40/ 5 10/ CMSC 331 Second Midterm Exam 6 15/ 7 15/ Name: Student ID#: 200/ You will have seventy-five (75) minutes to complete this closed book

More information

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets Java Applets Road Map Introduction to Java Applets Review applets that ship with JDK Make our own simple applets Introduce inheritance Introduce the applet environment html needed for applets Reading:

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring Exceptions BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom

More information

Unit 5 - Exception Handling & Multithreaded

Unit 5 - Exception Handling & Multithreaded Exceptions Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/application

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O

Week 12. Streams and File I/O. Overview of Streams and File I/O Text File I/O Week 12 Streams and File I/O Overview of Streams and File I/O Text File I/O 1 I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or a file

More information

PIC 20A Streams and I/O

PIC 20A Streams and I/O PIC 20A Streams and I/O Ernest Ryu UCLA Mathematics Last edited: December 7, 2017 Why streams? Often, you want to do I/O without paying attention to where you are reading from or writing to. You can read

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

OBJECT ORIENTED PROGRAMMING TYm. Allotted : 3 Hours Full Marks: 70

OBJECT ORIENTED PROGRAMMING TYm. Allotted : 3 Hours Full Marks: 70 I,.. CI/. T.cH/C8E/ODD SEM/SEM-5/CS-504D/2016-17... AiIIIII "-AmI u...iir e~ IlAULAKA ABUL KALAM AZAD UNIVERSITY TECHNOLOGY,~TBENGAL Paper Code: CS-504D OF OBJECT ORIENTED PROGRAMMING TYm. Allotted : 3

More information

Definition: A thread is a single sequential flow of control within a program.

Definition: A thread is a single sequential flow of control within a program. What Is a Thread? All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!" or sorts a list of names or computes a list of prime numbers.

More information

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

The Sun s Java Certification and its Possible Role in the Joint Teaching Material The Sun s Java Certification and its Possible Role in the Joint Teaching Material Nataša Ibrajter Faculty of Science Department of Mathematics and Informatics Novi Sad 1 Contents Kinds of Sun Certified

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS Core Java SYLLABUS COVERAGE Introduction. OOPS Package Exception Handling. Multithreading Applet, AWT, Event Handling Using NetBean, Ecllipse. Input Output Streams, Serialization Networking Collection

More information

A- Core Java Audience Prerequisites Approach Objectives 1. Introduction

A- Core Java Audience Prerequisites Approach Objectives 1. Introduction OGIES 6/7 A- Core Java The Core Java segment deals with the basics of Java. It is designed keeping in mind the basics of Java Programming Language that will help new students to understand the Java language,

More information

SCHEME OF COURSE WORK

SCHEME OF COURSE WORK SCHEME OF COURSE WORK Course Details: Course Title Object oriented programming through JAVA Course Code 15CT1109 L T P C : 3 0 0 3 Program: B.Tech. Specialization: Information Technology Semester IV Prerequisites

More information

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1 Exceptions: An OO Way for Handling Errors Introduction Rarely does a program runs successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. Such

More information

Unit 3 INFORMATION HIDING & REUSABILITY. -Inheritance basics -Using super -Method Overriding -Constructor call -Dynamic method

Unit 3 INFORMATION HIDING & REUSABILITY. -Inheritance basics -Using super -Method Overriding -Constructor call -Dynamic method Unit 3 INFORMATION HIDING & REUSABILITY -Inheritance basics -Using super -Method Overriding -Constructor call -Dynamic method Inheritance Inheritance is one of the cornerstones of objectoriented programming

More information

Note: Answer any five questions. Sun micro system officially describes java with a list of buzz words

Note: Answer any five questions. Sun micro system officially describes java with a list of buzz words INTERNAL ASSESSMENT TEST I Date : 30-08-2015 Max Marks: 50 Subject & Code: JAVA & J2EE (10IS753) Section : A & B Name of faculty: M V Sreenath Time : 8.30-10.00 AM 1.List and Explain features of Java.

More information

Complete Java Contents

Complete Java Contents Complete Java Contents Duration: 60 Hours (2.5 Months) Core Java (Duration: 25 Hours (1 Month)) Java Introduction Java Versions Java Features Downloading and Installing Java Setup Java Environment Developing

More information

John Cowell. Essential Java Fast. How to write object oriented software for the Internet. with 64 figures. Jp Springer

John Cowell. Essential Java Fast. How to write object oriented software for the Internet. with 64 figures. Jp Springer John Cowell Essential Java Fast How to write object oriented software for the Internet with 64 figures Jp Springer Contents 1 WHY USE JAVA? 1 Introduction 1 What is Java? 2 Is this book for you? 2 What

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

CPSC 319. Week 2 Java Basics. Xiaoyang Liu & Sorting Algorithms

CPSC 319. Week 2 Java Basics. Xiaoyang Liu & Sorting Algorithms CPSC 319 Week 2 Java Basics Xiaoyang Liu xiaoyali@ucalgary.ca & Sorting Algorithms Java Basics Variable Declarations Type Size Range boolean 1 bit true, false char 16 bits Unicode characters byte 8 bits

More information

Midterm assessment - MAKEUP Fall 2010

Midterm assessment - MAKEUP Fall 2010 M257 MTA Faculty of Computer Studies Information Technology and Computing Date: /1/2011 Duration: 60 minutes 1-Version 1 M 257: Putting Java to Work Midterm assessment - MAKEUP Fall 2010 Student Name:

More information

SYLLABUS JAVA COURSE DETAILS. DURATION: 60 Hours. With Live Hands-on Sessions J P I N F O T E C H

SYLLABUS JAVA COURSE DETAILS. DURATION: 60 Hours. With Live Hands-on Sessions J P I N F O T E C H JAVA COURSE DETAILS DURATION: 60 Hours With Live Hands-on Sessions J P I N F O T E C H P U D U C H E R R Y O F F I C E : # 4 5, K a m a r a j S a l a i, T h a t t a n c h a v a d y, P u d u c h e r r y

More information

copy.dept_change( CSE ); // Original Objects also changed

copy.dept_change( CSE ); // Original Objects also changed UNIT - III Topics Covered The Object class Reflection Interfaces Object cloning Inner classes Proxies I/O Streams Graphics programming Frame Components Working with 2D shapes. Object Clone Object Cloning

More information

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Course Overview This course teaches programmers the skills necessary to create Java programming system applications and satisfies the

More information

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction COMPSCI 230 S2 2016 Software Construction File Input/Output 2 Agenda & Reading Agenda: Introduction Byte Streams FileInputStream & FileOutputStream BufferedInputStream & BufferedOutputStream Character

More information

Introduction Unit 4: Input, output and exceptions

Introduction Unit 4: Input, output and exceptions Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.

More information

Reading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.

Reading from URL. Intent - open URL  get an input stream on the connection, and read from the input stream. Simple Networking Loading applets from the network. Applets are referenced in a HTML file. Java programs can use URLs to connect to and retrieve information over the network. Uniform Resource Locator (URL)

More information

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling

JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling Multithreaded Programming Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads;

More information