Java Manual

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Java Manual as PDF for free.

More details

  • Words: 9,182
  • Pages: 64
JAVA LAB MANUAL

BHARAT INSTITUTE OF ENGINEERING & TECHNOLOGY

JAVA LAB MANUAL

BIET

TABLE OF CONTENTS 1. Lab Plan 2. Introduction to Java 3. Unit – I (Basic Java) a. Introduction to main concepts used in Unit – 1 b. Experiment – 1 (Quadratic Equation Roots) c. Experiment – 2 (Fibonacci Series) d. Experiment – 3 (Prime Numbers) e. Experiment – 4 (Matrix Multiply) f. Experiment – 5 (Tokenize Integers and get SUM) g. Experiment – 6 (Palindrome) h. Experiment – 7 (Names Sorting) 4. Unit – a. b. c.

II (Streams API & Data Structures) Experiment – 8 (File Properties) Experiment – 9 (Display File) Experiment – 10 (Word Count & Character Count)

5. Unit – III (User Interface & Event Handling) a. Experiment – 11 (Message in Applet) b. Experiment – 12 (Interest Applet) c. Experiment – 13 (Mouse Events) d. Experiment – 14 (Draw Lines)

6. Unit – IV (Threads, Client Server, Reflection API) a. Experiment – 15 (Multiple Threads) b. Experiment – 16 (Producer Consumer) c. Experiment – 17 (Polymorphism implementation)

2

JAVA LAB MANUAL

BIET

Introduction to JAVA Java Programming Language: Java is a very popular and widely used programming language and it was not be an exaggeration to say it is the most widely used programming language in industry now. The reason for its wide popularity was probably the well thought of goals of the programming language. Among other attractive features, the following stand out in ensuring it gets wide acceptability. 1. 2. 3. 4. 5. 6. 7.

Ease of use Object Oriented Very strong API Focus on removing hard to use and error-prone constructs Platform Independence Open Source encouraging collaborative development. Security (Sandbox)

When people refer to the term JAVA, they are actually referring to any one or all three of the following. The JAVA Programming Language The Java Virtual Machine The JAVA Application Programming Interface All three together along with the numerous tools that provide for a strong programming environment, making programming easy and encouraging rapid application development has made Java one of the most popular programming languages. The JAVA Virtual Machine: Contrary to other popular languages, JAVA follows a half-compiled, half-interpreted approach to achieve the famed platform independence. Java inventors also defined a platform independent java machine language called Byte-Code into which java Compiler compiles all Java Programs. This byte code is the machine language of the Java Virtual Machine and is platform independent. Java Virtual Machine is a software interpreter which interprets byte code (.class files) and executes them on the target machine on which the byte code in running. Java inventors provided reference implementations of Java Virtual machine on some of the most popular machine architectures and

3

JAVA LAB MANUAL

BIET

encouraged vendors in developing the same for almost all machine architectures by providing the reference implementation. Since the byte code is machine independent, JAVA programs can be compiled once (into byte code) and executed on any machine architecture provided there is a JVM implementation on that architecture. Java Application Programming Interface: Java comes with a pretty exhaustive application programming interface which covers a wide ranging set of tasks which programmers need. By providing a easy to use application programming interface, JAVA makes the task of the programmer some what easy, allowing him to focus on the solution to his problem not having to worry about implementing simple data structures, working on lower level file interaction, etc. Java API has classes that provide support for large number of GUI widgets, Input & Output Streams, Database interaction, Socket communication libraries, utility data structures, simple data types, reflection API among other things. The API also is designed with extensibility and provides scope for alternate implementations by a thoughtful separation of Interfaces and implementations. Installation: The latest version of JAVA (1.6 at the time of writing this revision of manual) is freely downloadable from www.java.sun.com. All machines in our Java lab have JAVA 1.5 or higher installed at C:\Program Files\Java. On the Linux/Solaris side, the students should run the command “which javac” on their shell to figure out the path of Java installation. Java Compiler: Java Compiler is the utility that compiles Java programs to their corresponding Byte Code(.class files). Javac is platform independent, for the simple reason that both source(input) and output of the javac program are platform independent. Java Compiler or “javac” as it is commonly called would be available in C:\Program Files\Java\jdk1.5.0_01\bin. Java Interpreter: Java interpreter or the Java Virtual Machine (It is called so because interpreter is a machine emulator executing each instruction in byte-code, line by line) is the software which executes Byte-Code. The interpreter is machine dependent because it interprets machine independent byte-code on a given machine architecture. The Java interpreter or “java” as it is commonly called would be available in C:\Program Files\Java\jdk1.5.0_01\bin Environment Variables: PATH: This should have the path of “javac” and other utilities, so they can be invoked directly without having to give the full absolute path.

4

JAVA LAB MANUAL

BIET

CLASS PATH: This environment variable is used to hold all paths in which Java Byte code of all c lasses which one hopes to use in his or her program. For example, classpath environment variable should have the path till lib directly in Java installation if we plan to use the Java API classes which we most certainly will. CLASSPATH should also have path of all user defined packages that would be used. Packages: Packages are actually groups of related classes and also serve the purpose of avoiding namespace cluttering. You can define your own packages and put your classes in that package. Example: Let us say I want to create 2 classes called Stack and Queue. I would create a package called edu.biet.cse.generic and put these classes in that package. To do so, I have to do the following: 1. Create a directory structure edu/biet/cse/generic is some folder x. 2. Put my Stack and Queue classes in that directory with the first line of these .java files indicating that they belong to package edu.biet.cse.generic. 3. Compile all files in the package by going into the generic directory and saying “javac *.java” 4. If I want to use these classes, I put the path “x” in CLASSPATH environment variable. 5. In the java file where I want to use the classes in this package, I would put an import edu.biet.cse.generic.* statement before going ahead and using the class. JAVA API Packages: JAVA API groups all interfaces and classes into a set of packages depending on the functionality they are addressing and supporting. Java.lang package offers the basic data types and basic classes and is automatically imported without any explicit import from programmers. All other packages have to be explicitly imported by the programmers depending on the need. Importing classes means that the classes would be loaded by the Java Loader into JVM and takes time. So, it is advisable to only import those packages and classes which would be used. Other commonly used packages in JAVA API are java.io, java.util, java.sql, java.awt, javax.swing, java.net, etc. JAVA API Documentation: What does it contain? API documentation contains the list of all p ackages, classes, interfaces and a description of all methods and their signatures among other things. The documentation is the most definitive source of API available and how to use for the programmers and is actually generated directly from source code using the JAVA doc utility. In fact, it is 5

JAVA LAB MANUAL

BIET

recommended that we use JAVA Doc to generate similar documentation for all JAVA classes we write as a matter of practice. Where is it available? JAVA API documentation is a must for all JAVA programmers and can be downloaded from Java.sun.com. Without documentation handy, it is highly unlikely you would be using the API support in JAVA to a good extent. Java API is available on all our machines in C:\Program Files\Java\jdk1.5.0_01\docs. How to use? Clicking on C:\program files\Java\jdk1.5.0_01\docs\index.html will lead you to a page where there will be a link to API specification. Click on the framed version. From the resultant page, you can navigate to any package, class, interface and look at its documentation and go to any related classes following the necessary navigation links. Starting with a Simple program: Program: Public class HelloWorld { Public static void main(String[] args) { System.out.println(“Hello World”); } } Notes: JAVA is a complete object-based language. Everything in JAVA is encapsulated in classes. Main in the class which you give to the interpreter is the entry point to a Java program. The JAVA interpreter will call the static main directly with command line options without creating an object. Steps to run a Java Program: 1. Compile Command: To compile, “javac HelloWorld.java” 2. Run Interpreter Command: To interpret, “java HelloWorld” Note: Compiler will generate HelloWorld.class which is the byte code. The Interpret will interpret HelloWorld.class by invoking HelloWorld.main().

6

JAVA LAB MANUAL

BIET

Introduction to Unit - I This unit covers the basics of Java. In this unit, students work on programs that expose them to basic syntactic structures of Java, arithmetic operations, classes, objects, access specifiers, core Java API libraries java.lang, java.util, class methods among other things. Main API Classes Used: 1. java.lang.Float 2. java.lang.Integer 3. java.lang.String 4. java.lang.System 5. java.lang.InputStream 6. java.util.StringTokenizer Language Concepts Learnt: I. User Defined Data Types (Classes): One of the fundamental concepts in any object oriented language (Java is no exception) is the concept of creating user defined data types that encapsulate properties and behavior and selectively exposing public behavior. II. Class Methods & Object Methods: For any user defined data type, there will possibly be properties at an instance (one instance of that data type) level called instance variables or member variables and class variables or class properties which have the same value across all instances of the class. These properties are meaningful at the class level and have values irrespective of whether a member of the class has been instantiated or not. These properties can be variables or methods. III. Member Variables: Properties of instances of class are called member variables. Mathematically speaking, class is a set and objects are members of a set. Every element of a set is identified by certain behavior (methods) which is the c ommon behavior and properties whose values might vary from member of the set to another or stay the same. IV. Access Specifiers (Private, Public): To allow for data hiding, there are different specifiers through which access to class members (variables & methods) can be controlled. Public means the member is available for use directly outside the class. Private means only available for internal methods. 7

JAVA LAB MANUAL

V. Arithmetic Operations: The reminder/modulo operators.

BIET

usual

plus,

minus,

multiplication,

division,

VI. Basic Data Types (int, float, Boolean): Though java is object based, a few basic data types have both a class equivalent and a basic data type. Example: int is a basic data type and Integer is its class equivalent. VII. Conditional Statement (if), loop statements (for): The conditional and looping constructs are pretty much the same as C type languages.

8

JAVA LAB MANUAL

BIET

Experiment 1: Quadratic Equation Roots 1. Problem Statement: Write a Java Program that prints all real solutions to the quadratic equation ax**2+bx+c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b**2 – 4ac is negative, display a message stating that there are no real solutions. 2. Solution Design: Design a class named QuadEq which has the constants a, b and c and member variables and the two roots as member variables. All member variables have to be private. Design 3 public methods, one to computeRoots, the other two methods are getter methods to give the roots stored in member variables. Write a public method called hasRealRoots() that return Boolean true if the equation has real roots and otherwise returns false. Class Name: QuadEq Properties/Member Variables: int a,b,c; double root1, root2; Constructors: QuadEq(int, int,int) Public Interface: Boolean hasRealRoots(), int computeRoots(), double getRoot1(), double getRoot2(); Private Methods: None Java API Classes used: 1. java.lang.System 2. java.lang.Math 3. Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Creates a QuadEq object with a given value of a, b, c. 2. Calls the method hasRealRoots() on the above object and if true, call computeRoots() and print the 2 roots by calling getRoot1() and getRoot2(); 3. If hasRealRoots() returns false, print saying the equation does not have real roots. 4. Test Cases: Test 1: Input: a = 1, b = 4, c = 4 Expected Output: Root1 = 2, Root2 = 2 Test 2: Input: a = 9, b = 2, c = 5 Expected Output: No real roots 9

JAVA LAB MANUAL

BIET

5. Reference Implementation: ########################################################### File name: QuadEq.java public class QuadEq { private int a = 0; private int b = 0; private int c = 0; private double root1 = 0; private double root2 = 0; public QuadEq(int arga, int argb, int argc) { a = arga; b = argb; c = argc; } public boolean hasRealRoots() { double Det = b*b - 4*a*c; return (Det >= 0); } public void computeRoots() { double Det = b*b - 4*a*c; Det = java.lang.Math.sqrt(Det); root1 = (-b + Det)/2*a; root2 = (-b - Det)/2*a; } 10

JAVA LAB MANUAL

BIET

public double getRoot1() { return root1; } public double getRoot2() { return root2; } } class QuadEquationTest { public static void main(String[] args) { int a = 9, b = 2, c = 5; QuadEq myQuadEq = new QuadEq(a,b,c); if(myQuadEq.hasRealRoots()) { myQuadEq.computeRoots(); System.out.println("Root1:" + myQuadEq.getRoot1()); System.out.println("Root2:" + myQuadEq.getRoot2()); } else { System.out.println("The given equation has imaginary roots"); } } } ########################################################### 6. Execution: 1. javac QuadEq.java 2. java QuadEquationTest 11

JAVA LAB MANUAL

BIET

Output:

Experiment 2: Fibonacci Sequence 1. Problem Statement: The Fibonacci sequence is defined by the following rule. The first two values in the sequence are 1 and 1. Every subsequent value is the sum of the two values preceding it. Write a Java program that uses both recursive and non-recursive functions to print the nth value in the Fibonacci sequence. 2. Solution Design: Write a class Fibonacci with 2 static methods. The methods are static because nth Fibonacci number is property of Fibonacci class and there is no concept of object of Fibonacci series because there is really only one Fibonacci series in the world. The 2 static methods return nth element in Fibonacci series given n and can be names nthFiboRecursive and nthFiboNonRecursive. Both yield the same result for a given n, but each follow a different implementation style (one is a recursive algorithm and the other non-recursive) and hence could lead to different performance times for high values of n. The idea is for the student to appreciate the time-overhead of using recursive algorithms and how it can exponentially increase with n vs. the conceptual simplicity of a recursive algorithm. Class Name: Fibonacci Properties/Member Variables: None Public Interface: static int nthFiboRecursive(int), static int ntheFiboNonRecursive() Private Methods: None Java API Classes used: 1. java.lang.System 3. Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Take a large value of n (say between 30 to 100) 2. Call nthFiboRecursive with n from step 1. 3. Call nthFiboNonRecursive with n from step 1. 4. Test Cases: Test 1: Input: n = 30

12

JAVA LAB MANUAL

BIET

5. Reference Implementation: #################################################################### File name: Fibonacci.java public class Fibonacci { public static int nthFiboRecursive(int n) { if((n == 1) || (n == 2)) { return 1; } else { return (Fibonacci.nthFiboRecursive(n - 1) + Fibonacci.nthFiboRecursive(n - 2)); } } public static int nthFiboNonRecursive(int n) { if((n == 1) || (n == 2)) { return 1; } else { int Lower = 1; int Higher = 1; int count = n - 2; while(count != 0) { int temp = Lower + Higher; Lower = Higher; Higher = temp; 13

JAVA LAB MANUAL

BIET

count--; } return Higher; } } } class FibonacciTest { public static void main(String[] args) { int n = 30; System.out.println(Fibonacci.nthFiboRecursive(n)); System.out.println(Fibonacci.nthFiboNonRecursive(n)); } } ##################################################################################

6. Execution: 1. javac Fibonacci.java 2. java FibonacciTest OUT PUT:

14

JAVA LAB MANUAL

BIET

Experiment – 3: Prime Numbers 1. Problem Statement: Write a Java Program that prompts the user for an integer and then prints out all prime numbers up to that integer. 2. Solution Design: Write a class called Prime that has two static methods, one (isPrime) which returns true if a given number is prime and false otherwise and another which takes n and prints all prime numbers less than n by calling the previous method to determine if a number is prime or not. The reason these methods are static is because these are class methods and there are no properties that are object specific. Class Name: PrimeNumbers Properties/Member Variables: None Public Interface: static boolean isPrime(int), static void allLowerPrimes(int) Private Methods: None JAVA API Classes Used: 1. java.lang.System 3. Unit Testing Code: Write a main method in the same class above or preferably in a different class that does the following. 1. Take an input value n. 2. Call the allLowerPrimes(n) method of the Prime class. 4. Test Cases: Test1: Input: n = 23 Output: All prime numbers less than or equal to 23.

15

JAVA LAB MANUAL

BIET

5. Reference Implementation: ########################################################### File name: Prime.java public class Prime { public static boolean isPrime(int n) { if((n == 0) || (n == 1)) { return false; } else if(n == 2) { return true; } else { int Median = (n/2) + 1; boolean isPrime = true; for(int i=2; i<=Median; i++) { if((n % i) == 0) { isPrime = false; break; } } return isPrime; } }

16

JAVA LAB MANUAL

BIET

public static void allLowerPrimes(int n) { for(int i = 0;i <=n; i++) { if(Prime.isPrime(i)) { System.out.println(i); } } } } class PrimeTest { public static void main(String[] args) { int n = 23; Prime.allLowerPrimes(n); } } ########################################################### 6. Execution: 1. javac Prime.java 2. java PrimeTest OUT PUT:

17

JAVA LAB MANUAL

BIET

Experiment – 4: Matrix Multiplication 1. Problem Statement: Write a Java program to multiply two given matrices. 2. Solution Design: Write a class Matrix which encapsulates all properties of a matrix including number of rows, columns, the values of the matrix and whether the matrix is populated with data. The class should provide access methods to get rows, cols, cell data, whether data is populated or not. The class should also have public methods to display matrix and multiply this matrix with another matrix. The class should provide a constructor which takes number of rows and cols only and another which takes number of rows and cols and a String which has blank separated matrix data. For unpopulated Matrix, the class should provide a method which will allow copying of data from another Matrix. We also want a method which checks whether we can multiply this matrix with another matrix checking the rows and cols. Class Name: Matrix Member Variables: int mNumRows, int mNumCols, int[][] mData, Boolean misDataPopulated. Public Interface: Boolean isDataPopulated(), int getNumRows(), int getNumCols(), int get CellElement(int, int), Matrix multiply(Matrix), Boolean canMultiply(Matrix), void CopydataFrom(Matrix), void display(); Constructors: Matrix(int, int); Matrix(int, int, String); JAVA API Classes Used: 1. java.util.StringTokenizer 2. java.lang.System 3. Unit Testing Code: Write a main method in the same Matrix class or in another Test class which does the following. 1. Create a Matrix object by supplying data in a String. 2. Create another Matrix object using the same approach. 3. check whether we can multiply the 2 matrices by calling canMultiply() 4. If we can multiply, call multiply method 5. display the result matrix by calling display method. 4. Test Cases: Test1: Input: Create a 3*2 and a 2*3 matrix and multiply them. Expected output: Check the result to verify output 18

JAVA LAB MANUAL

BIET

Test2: Input: Create a 3*2 and a 3*2 matrix and multiply them. Expected output: Cannot multiply matrices. 5. Reference Implementation: #################################################################### File: Matrix.java import java.util.StringTokenizer; public class Matrix { private int mNumRows = 0; private int mNumCols = 0; private int [ ][ ] mData; private boolean mIsDataPopulated = false; public Matrix(int argRows, int argCols) { mNumRows = argRows; mNumCols = argCols; mData = new int[mNumRows][mNumCols]; } public Matrix(int argRows, int argCols, String argIntData) { mNumRows = argRows; mNumCols = argCols; mData = new int[mNumRows][mNumCols]; StringTokenizer str = new StringTokenizer(argIntData); int count = str.countTokens(); if(count != (mNumRows * mNumCols)) { System.out.println("Matrix Cell Items not matching count of rows and cols"); }

19

JAVA LAB MANUAL

BIET

else { for(int row=0;row<mNumRows;row++) { for(int col=0;col<mNumCols;col++) { mData[row][col] = (new Integer(str.nextToken())).intValue(); } } } mIsDataPopulated = true; } public boolean isDataPopulated() { return mIsDataPopulated; } public int getNumRows() { return mNumRows; } public int getNumCols() { return mNumCols; } public int getCellElement(int row, int col) { return mData[row][col]; } public boolean copyDataFrom(Matrix anotherMatrix) { if(!anotherMatrix.isDataPopulated()) { 20

JAVA LAB MANUAL

BIET

return false; } else if((anotherMatrix.getNumRows() != mNumRows) || (anotherMatrix.getNumCols() != mNumCols)) { return false; } else { mIsDataPopulated = true; for(int i = 0;i < mNumRows;i++) { for(int j = 0; j < mNumCols;j++) { mData[ i ][ j ] = anotherMatrix.getCellElement(i,j); } } return true; } } public boolean canMultiply(Matrix anotherMatrix) { if(mNumCols == anotherMatrix.getNumRows()) { return true; } else { return false; } } public Matrix multiply(Matrix anotherMatrix) { Matrix resultMatrix = null; if(canMultiply(anotherMatrix)) { StringBuffer Result = new StringBuffer(""); 21

JAVA LAB MANUAL

BIET

for(int i = 0; i < mNumRows; i++) { for(int j = 0; j < anotherMatrix.getNumCols(); j++) { int element = 0; for(int k = 0; k < mNumCols; k++) { element+= getCellElement(i,k)*anotherMatrix.getCellElement(k,j); } Result.append((new Integer(element)).toString()); Result.append(" "); } } resultMatrix=new Matrix(mNumRows,anotherMatrix.getNumCols(),Result.toString()); } return resultMatrix; } public void display() { for(int i=0;i < mNumRows; i++) { for(int j=0; j < mNumCols; j++) { System.out.print(getCellElement(i,j) + " "); } System.out.println(""); } } }

22

JAVA LAB MANUAL

BIET

class MatrixMultiplyTest { public static void main(String[] args) { int Rows1 = 3; int Cols1 = 2; String MatrixStr1 = "1 2 3 4 5 6"; Matrix Matrix1 = new Matrix(3,2,MatrixStr1); System.out.println("Input Matrix 1"); Matrix1.display(); int Rows2 = 2; int Cols2 = 3; String MatrixStr2 = "1 2 3 4 5 6"; Matrix Matrix2 = new Matrix(2,3,MatrixStr2); System.out.println("Input Matrix 2"); Matrix2.display(); if(Matrix1.canMultiply(Matrix2)) { Matrix Mul = Matrix1.multiply(Matrix2); System.out.println("The result of multiplying Matrix1 and Matrix 2 is:"); Mul.display(); } } } #################################################################### 6. Execution: 1. javac Matrix.java 2. java MatrixMultiplyTest OUT PUT:

Experiment – 5: Sum of Integers given as input in one line 23

JAVA LAB MANUAL

BIET

1. Problem Statement: Write a Java program that read a line of Integers and then displays each integer, and the sum of all Integers (use StringTokenizer class) 2. Solution Design: Write a class MyIntegerSeries which encapsulates an ArrayList of Integers (to allow for dynamic growth depending on how many Integers are there in the String) and a public method called getSUMofSeries() which will give the sum of all Integers. The constructor should take a String and tokenize it to populate the ArrayList of Integers. Class Name: MyIntegerSeries Member Variables: ArrayList mIntegerList Public Interface: int getSUMofSeries() Constructors: MyIntegerSeries(String) Private Members: None Java API Classes used: 1. java.lang.String 2. java.lang.System 3. java.util.StringTokenizer 3. Unit Testing Code: Write a main method in MyIntergerSeries class or a test class which does the following. 1. Create an object of MyInetgerSeries class by giving a String of Integers. 2. Call the getSUMofSeries() method in the above object to get the SUM. 3. Display the SUM. 4. Test Cases: Test1: Input: String: “1 2 3 4 5 6 7 8 9 10” Expected Output: 55

5. Reference Implementation: 24

JAVA LAB MANUAL

BIET

########################################################### File: MyIntegerSeries.java import java.util.StringTokenizer; import java.util.ArrayList; public class MyIntegerSeries { private ArrayList mIntegerList = null; public MyIntegerSeries(String str) { StringTokenizer st = new StringTokenizer(str); mIntegerList = new ArrayList(); while(st.hasMoreTokens()) { mIntegerList.add(new Integer(st.nextToken())); } } public int getSUMofSeries() { int sum = 0; for(int i = 0; i < mIntegerList.size(); i++) { sum += (mIntegerList.get(i)).intValue(); } return sum; } } class IntegerSUMTest { public static void main(String[] args) { String test = "1 2 3 4 5 6 7 8 9 10"; MyIntegerSeries obj = new MyIntegerSeries(test); System.out.println(obj.getSUMofSeries()); } } ########################################################### 6. Execution 1. javac MyInetgerSeries.java 2. java IntegerSUMTest OUTPUT:

Experiment – 6: Palindrome 25

JAVA LAB MANUAL

BIET

1. Problem Statement: Write a Java program that checks whether a given string is a palindrome or not. Ex: MADAM is a palindrome. 2. Solution Design: Write a class Palindrome that has a static method (isPalindrome) which takes a String as argument and returns true if the String is a palindrome, otherwise returns false. The algorithm just reverses the String after taking the String into a StringBuffer and compares both. If the String and its reverse are same, we can say the given input String is a Palindrome. Class Name: Palindrome Properties/Member Variables: None Public Interface: static Boolean isPalindrome(String); Private Methods: None JAVA API Classes Used: 1. java.lang.StringBuffer 2. java.lang.System 3. Unit Testing Code: Write a main method in the same class or in another class which does the followi ng. 1. Takes a String as input. 2. Calls the method isPalindrome() with the above String. 3. Check the return value and print the corresponding message. 4. Test Cases: Test1: Input: String = “MALAYALAM” Expected output: The string MALAYALAM is a Palindrome. Test2: Input: String = “Madam” Expected output: The string Madam is a Palindrome. Test3: Input: String = “Hellh” Expected output: The string Hellh is not a Palindrome.

5. Reference Implementation: 26

JAVA LAB MANUAL

BIET

################################################## ######### File: Palindrome.java public class Palindrome { public static boolean isPalindrome(String str) { StringBuffer buf1 = new StringBuffer(str); StringBuffer buf2 = new StringBuffer(str); buf1.reverse(); if((buf1.toString()).equals(buf2.toString())) { return true; } return false; } } class PalindromeTest { public static void main(String[ ] args) { String test = "Madam"; if(Palindrome.isPalindrome(test.toLowerCase())) { System.out.println("The string:" + test + " is a Palindrome"); } else { System.out.println("The string:" + test + " is not a Palindrome"); } } } ########################################################### 27

JAVA LAB MANUAL

BIET

6. Execution: 1. javac Palindrome.java 2. java PalindromeTest Out put:

Experiment – 7: Names Sort

28

JAVA LAB MANUAL

BIET

1. Problem Statement: Write a Java program for sorting a given list of names in ascending order. 2. Solution Design: Write a class NameSort that encapsulates a list (array) of names with a constructor that takes an array of names and stores them in a private array member variable, and two public methods, one of which sort the list of names in the array member variable and the other that displays the names in the array. Class Name: NameSort Member Variables: String[] mNamesList Constructor: NameSort(String[]); Public Interface: void sortNames(); void displayNamesList(); Private Methods: None JAVA 1. 2. 3. 4.

API Classes Used: java.lang.String java.lang.System java.util.Scanner java.util.Arrays

3. Unit Testing Code: Write a main method either in the class NameSort or in another class which does the following. 1. Read the count of names to be input 2. Read the names. 3. Create an object of NameSort 4. Call displayNamesList 5. Call sortNames 6. Call displayNamesList 4. Test Cases: Test 1: Input: count = 4; Names = “ABC”, “XYZ”, “HELLO” Expected Output: “ABC”, “HELLO”, “XYZ” Test2: Input: count = 6; Names = “gui”, ”bad”, ”design”, ”other”, “hello”, “what” Expected output: “bad”, “design”, “gui”, “hello”, “other”, “what”

5. Reference Implementation:

29

JAVA LAB MANUAL

BIET

########################################################### File: NameSort.java import java.lang.*; import java.util.*; public class NameSort { public NameSort(String[ ] argNames) { mNamesList = new String[argNames.length]; System.arraycopy(argNames,0,mNamesList,0,argNames.length); } public void sortNames( ) { Arrays.sort(mNamesList); } public void displayNamesList( ) { System.out.println("The Ordered List now is:"); for(int i=0;i < mNamesList.length; i++) { System.out.println(mNamesList[ I ]); } } private String[ ] mNamesList; }

class NameSortTest { 30

JAVA LAB MANUAL

BIET

public static void main(String[ ] args) { System.out.println("Please enter the number of elements in the array"); Scanner sc = new Scanner(System.in); int count = sc.nextInt( ); sc.nextLine( ); String[ ] NamesArray = new String[count]; System.out.println("Enter each name in a line"); for(int i=0;i < count;i++) { NamesArray[ i ] = new String(sc.nextLine( )); } sc.close( ); NameSort myNameSort = new NameSort(NamesArray); myNameSort.sortNames( ); myNameSort.displayNamesList( ); } } ########################################################### 6. Execution: 1. javac NameSort.java 2. java NameSortTest OUT PUT:

Introduction to Unit - II

31

JAVA LAB MANUAL

BIET

This unit introduces Streams, which are the JAVA way of providing API for programmers to read data or write data from and to different data source. The streams API interface is all grouped into java.io package and includes Stream Interfaces, Stream Classes, Buffered Interfaces, Buffered Classes and other general purpose utility classes related to input/output. Main JAVA API Classes used:  Java.io.File  Java.io.DataInputStream  Java.io.BufferedReader  Java.io.FileInputStream  Java.io.FileOutputStream  Java.io.DataOutputStream Language Concepts Learnt: 1. Programming to Interface: Java API has Interfaces like DataInput and DataOutput which are implemented by various Input and Output Stream classes. This kind of Interface based API allows the users to program at a high level thereby reducing the program’s dependency on a specific implementation. 2. Reading data from files: This unit shows you how you can use classes from JAVA API to read from files. 3. Writing data to files: This unit shows you how you can use classes from JAVA API to write to files. 4. Understanding File related exceptions: This unit exposes you to some of the exceptions possible while doing IO related operations and what they indicate. 5. Finding out File properties: This unit shows you class that encapsulates file properties in Java, internally using the local File management system to get the properties. 6. Common Data Structures: Assuming you are already familiar with common data structures and their operations, this unit gives you a chance to look at JAVA API classes implementing the most common data structures that can be directly used in your JAVA programs without you having to implement the basic data structures. Of course, it would be good for students to see the public interface o f these data structures and understand how the interface has been designed and understand core OO principles of data abstraction which are behind the design of JAVA API. 7. IOStream Library Hierarchy: JAVA API library follows a very logical hierarchy of interfaces and implementation classes that allows for extensibility either by extending interfaces or by changing implementations as the user wants. 32

JAVA LAB MANUAL

BIET

Understanding the hierarchy and appreciating its design would certainly help students get the essence of object oriented programming and programming for extensibility. Experiment – 8: File Properties 1. Problem Statement: Write a Java Program that reads one file name from the user then displays information about whether the file exists, whether the file is read able, whether the file is writable, the type of file and the length of the file in bytes. 2. Solution Design: Write a class named MyFile which would have method called displayFileProperties() that would print all the properties of file like whether the file exists, what is the absolute path of the file, whether the file is readable and writable, whether it is a regular file or a directory and size of file in bytes. The constructor of the class should take a path (absolute or relative) as argument. Class Name: MyFile Constructor: public MyFile(String) Public Interface: void displayFileProperties() Private Members: File & String Private Methods: None 3. Unit Testing Code: Write a main method in MyFile or another class which will create a MyFile object with a given File Path String and calls the displayFileProperties() method on the object. 4. Test Cases: Test1: Valid file name with full path Test2: Valid file name with relative path Test3: invalid file

5. Reference Implementation: #################################################################### 33

JAVA LAB MANUAL

BIET

File: MyFile.java import java.io.*; public class MyFile { private File mFile; private String mName; public MyFile(String argFileName) { mFile = new File(argFileName); mName = new String(argFileName); } public void displayFileProperties( ) { if(!mFile.exists( )) { System.out.println("The file with path" +\"+ mName +\"+ " does not exist"); return; } System.out.println("The file with path" + \"+ mName +\" + " exists"); System.out.println("The corresponding absolute path is:" + mFile.getAbsolutePath( )); if(mFile.canRead( )) { System.out.println("The file:" + mName + " is readable"); } if(mFile.canWrite( )) { System.out.println("The file:" + mName + " is writable"); } if(mFile.isDirectory( )) { System.out.println(mName + " is a Directory"); } else { System.out.println(mName + " is a File"); 34

JAVA LAB MANUAL

BIET

System.out.println("The file size is :" + mFile.length( )); } } } class FilePropertiesTest { public static void main(String[ ] args) { String File = "hi.txt"; MyFile obj = new MyFile(File); obj.displayFileProperties( ); } } #################################################################### 6. Execution: 1. javac MyFile.java 2. java FilePropertiesTest OUTPUT:

Experiment – 9: File Contents 1. Problem Statement:

35

JAVA LAB MANUAL

BIET

Write a Java program that reads a file and displays a file on the screen, and displays the file on the screen with a line number before each line. 2. Solution Design: Write a class called FileDisplay which checks whether a given file exists, i sReadable, is a file filetype, reads the file using an InputStream and display the file to command line as is and with line number, one line at a time. 3. Unit Testing Code: Write a main method in DisplayFile or another class which creates an object of DisplayFile, checks for basic file properties and then calls the displayFile and displayFilewithLineNumber methods to print the contents of the file. 4. Test Cases: Test1: A valid text file in your file system 5. Reference Implementation: ##################################################################################

File: FileDisplay.java import java.io.*; public class FileDisplay { private String mName; private File mFileHandle; public FileDisplay(String str) { mName = new String(str); mFileHandle = new File(mName); } public boolean isExistsFile() { return (mFileHandle.exists()); } public boolean isReadableFile() { return (mFileHandle.canRead()); }

36

JAVA LAB MANUAL

BIET

public boolean isRegularFile() { return (mFileHandle.isFile()); } public void displayFileContents() { try { BufferedReader lBr = new BufferedReader(new FileReader(mFileHandle)); String lNextLine = lBr.readLine(); while(lNextLine != null) { System.out.println(lNextLine); lNextLine = lBr.readLine(); } lBr.close(); } catch(Exception e) { e.printStackTrace(); } } public void displayFileContentsWithLineNumber() { try { int lineCount = 0; BufferedReader lBr = new BufferedReader(new FileReader(mFileHandle)); String lNextLine = lBr.readLine(); while(lNextLine != null) { lineCount++; System.out.println(lineCount + ":" + lNextLine); 37

JAVA LAB MANUAL

BIET

lNextLine = lBr.readLine(); } lBr.close(); } catch(Exception e) { e.printStackTrace(); } } }

class FileDisplayTest { public static void main(String[] args) { String str = "hi.txt"; FileDisplay lDisplay = new FileDisplay(str); if((lDisplay.isExistsFile()) && (lDisplay.isRegularFile()) && (lDisplay.isReadableFile())) { System.out.println("File Contents of" + str + " are :"); lDisplay.displayFileContents(); System.out.println("File Contents with line number of" + str + " are :"); lDisplay.displayFileContentsWithLineNumber(); } } } ##################################################################################

6. Execution: 1. javac FileDisplay.java 2. java FileDisplayTest 38

JAVA LAB MANUAL

BIET

out put:

Experiment – 10: Character Count in a File 1. Problem Statement:

39

JAVA LAB MANUAL

BIET

Write a Java program that displays the number of characters, lines and words in a text file. 2. Solution Design: Write a class FileCharacterCount that has methods to check for basic file properties and than opens a file using InputStream class and reads one line at a time, tokenizes the line on spaces, gets word count and takes the length of like and adds it to character count and this comes up with line count, word count and character count of the file. 3. Unit Testing Code: Write a main method is this class or some other class that creates an object of FileCharacterCount and calls the methods computerCharacterCount() and displayCount methods to get counts. 4. Test Cases: Test1: Any valid text file in your file system 5. Reference Implementation: #################################################################### File: FileCharacterCount.java import java.io.*; import java.util.*; public class FileCharacterCount { private String mName; private File mFileHandle; private int mLineCount = 0; private int mWordCount = 0; private int mCharacterCount = 0; public FileCharacterCount(String str) { mName = new String(str); mFileHandle = new File(mName); } public boolean isExistsFile() { return (mFileHandle.exists()); }

40

JAVA LAB MANUAL

BIET

public boolean isReadableFile() { return (mFileHandle.canRead()); } public boolean isRegularFile() { return (mFileHandle.isFile()); } public void computeCharacterCount() { try { BufferedReader lBr = new BufferedReader(new FileReader(mFileHandle)); String lNextLine = lBr.readLine(); while(lNextLine != null) { System.out.println(lNextLine); mLineCount++; mCharacterCount = mCharacterCount + lNextLine.length() + 1; StringTokenizer st = new StringTokenizer(lNextLine); while(st.hasMoreTokens()) { st.nextToken(); mWordCount++; } lNextLine = lBr.readLine(); } lBr.close(); } catch(Exception e) { e.printStackTrace(); } } 41

JAVA LAB MANUAL

BIET

public void displayCounts() { System.out.println("The line count is:" + mLineCount); System.out.println("The word count is:" + mWordCount); System.out.println("The character count is:" + mCharacterCount); } } class FileCharacterCountTest { public static void main(String[] args) { String str = "hi.txt"; FileCharacterCount lFile = new FileCharacterCount(str); if((lFile.isExistsFile()) && (lFile.isRegularFile()) && (lFile.isReadableFile())) { lFile.computeCharacterCount(); lFile.displayCounts(); } } } #################################################################### 6. Execution: 1. javac FileCharacterCount.java 2. java FileCharacterCount

Introduction to Unit – III This unit covers the support for rich user interface development in Java. In this unit, students work on programs that expose them to various user interface elements/widgets provided by Java to help construct rich user interface either in desktop applications or 42

JAVA LAB MANUAL

BIET

on web using applets which are java objects within HTML. Java supports UI components starting from the simple ones like button, textbox to complex components like table, tree and components that can contain other components in them like panels, frames, etc. Java API packages that would be predominately used are java.awt and javax.swing and java.awt.event. JAVA also supports an event model which allows programs to register callbacks on events of interest on a UI object. Main API Classes Used: 1. java.awt.Button. 2. java.awt.event.ActionListener 3. java.awt.event.MouseListener 4. java.awt.TextField Language Concepts Learnt: 1. User Interface Development: Building rich user interface to functionality of software makes it easy for users to use the software there-by enhancing the utility of the software. Java offers a vast library of widgets that could be used directly to construct your own interfaces. 2. Event driven programming: It is a concept where the software does some action based on an action that user performs on the user interface and otherwise stays idle waiting for a user action. This kind of programming is pretty common for software which is built for the purpose of users using the services of the software on an interactive basis as and when they need some functionality supported by the software. 3. Listeners: Any number of listeners might be interested in specific events caused by an explicit action done by the user on a user interface widget and each listener might do totally different things based on the event being generated. JAVA provides a powerful and elegant mechanism to realize this kind of publish subscriber model driven by events generated based on actions, with components acting as publishers publishing information on user action and subscribers registering with publishers to ensure they get all messages from publishers for the registered event. 4. Applets: Java provides support for embedding objects in HTML allowing users to build rich JAVA powered user interface application accessible from web. Because applet running on web cannot by default be considered non-malicious, JAVA implements a sandbox security model which places sufficient restrictions on what an applet can and cannot do to ensure client’s system is not compromised on a malicious attack. 5. Model View Controller pattern: JAVA user interface library follows MVC pattern that allows multiple views to be attached to a given model and java library

43

JAVA LAB MANUAL

BIET

automatically ensures all views are updated when the model changes using a publish-subscribe internal implementation.

Experiment – 11: Message in Applet 1. Problem Statement: Write an applet that displays a simple message.

44

JAVA LAB MANUAL

BIET

2. Solution Design: Write a class MyDisplayApplet class which extends JApplet class and implements the init method by adding a JLabel with a message to the content pane of the applet. Set the size of the applet to some reasonable size. 3. Unit Testing Code: Insert the applet as an object inside html code by using applet tag and giving code, width and height attributes to the tag. 4. Test Cases: Test1: go to the AppletTest.html in your favorite browser. 5. Reference Implementation: #################################################################### File: MyDisplayApplet.java import javax.swing.*; import javax.swing.border.*; import java.awt.*; public class MyDisplayApplet extends JApplet { public void init() { JLabel lLabel = new JLabel("Welcome to Applet World!", SwingConstants.CENTER); getContentPane().add(lLabel); lLabel.setBorder(new javax.swing.border.EmptyBorder(0,0,0,0)); setPreferredSize(new Dimension(400,300)); setVisible(true); } }

File: AppletTest.html 45

JAVA LAB MANUAL

BIET

####################################################################

6. Execution: 1. javac MyDisplayApplet.java 2. goto AppletTest.html in browser.

Experiment – 12: Loan Repayment Applet 1. Problem Statement: Write an applet that computes the payment of a loan based on the amount of the loan, the interest rate and the number of months. It takes one parameter from the browser: Monthly rate; if true, the interest rate is per month; other wise the interest rate is annual. 2. Solution Design: Design a class called InterestApplet extending JApplet and building a UI that has 3 TextFields that allows the user to enter amount, interest rate and number of months loaned, a button called Compute which when clicked will compute interest and sho w it in another TextField labeled Interest. The rate entered is taken as monthly rate or yearly rate based on parameter input coming from Browser. 3. Unit Testing Code: Write a html file which will invoke this applet using applet tag with code, height and width attributes and another parameter called MonthyRate set to false meaning the rate entered by ser will be annual interest rate. 4. Test Cases: Test1: Amount: 100, Months = 12, Interest = 18 Test2: Amount: 1500, Months 29, Interest = 12 5. Reference Implementation: #################################################################### File: InterestApplet.java import javax.swing.*; 46

JAVA LAB MANUAL

BIET

import javax.swing.border.*; import java.awt.*; import java.awt.event.*; public class InterestApplet extends JApplet { private private private private

JTextField JTextField JTextField JTextField

mRepaymentAmountText = null; mLoanText = null; mIntRateText = null; mNumMonthsText = null;

private String mIsMonthlyRate = ""; public void init() { mIsMonthlyRate = new String(getParameter("MonthlyRate")); getContentPane().setLayout(new GridLayout(4,2)); JLabel lLabelAmount = new JLabel("Loan Amount:", SwingConstants.LEFT); JLabel lLabelIntRate = new JLabel("Interest Rate:", SwingConstants.LEFT); JLabel lLabelMonths = new JLabel("Number of Months:", SwingConstants.LEFT); JButton lButtonRepaymentAmount = new JButton( "Show Repayment Amount"); mLoanText = new JTextField(); mLoanText.setEnabled(true); mIntRateText = new JTextField(); mIntRateText.setEnabled(true); mNumMonthsText = new JTextField(); mNumMonthsText.setEnabled(true); mRepaymentAmountText = new JTextField(); mRepaymentAmountText.setEnabled(false);

47

JAVA LAB MANUAL

BIET

getContentPane().add(lLabelAmount); getContentPane().add(mLoanText); getContentPane().add(lLabelIntRate); getContentPane().add(mIntRateText); getContentPane().add(lLabelMonths); getContentPane().add(mNumMonthsText); getContentPane().add(lButtonRepaymentAmount); getContentPane().add(mRepaymentAmountText); lButtonRepaymentAmount.addActionListener( new InterestActionListener()); setPreferredSize(new Dimension(400,300)); setVisible(true); } public class InterestActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { float mLoan = (new Float(mLoanText.getText())).floatValue(); float mRate = (new Float(mIntRateText.getText())).floatValue(); float mNumMonths = (new Integer(mNumMonthsText.getText())).intValue(); if(mIsMonthlyRate.equals("true")) { float totalInterest = mLoan*(mRate/100)*mNumMonths; totalInterest += mLoan; mRepaymentAmountText.setText( (new Float(totalInterest)).toString()); } else { float totalInterest = mLoan*(mRate/(12*100))*mNumMonths; totalInterest += mLoan; 48

JAVA LAB MANUAL

BIET

mRepaymentAmountText.setText( (new Float(totalInterest)).toString()); } } } } File: InterestAppletTest.html #################################################################### 6. Execution: 1. javac InterestApplet.java 2. go to InterestAppletTest.html in your browser.

Experiment – 13: Handling Mouse Events 1. Problem Statement: Write a Java Program to handle mouse events. 2. Solution Design: 49

JAVA LAB MANUAL

BIET

Write a class MouseEventsApplet that extends JApplet and implements the MouseListener interface. The init method will just create a simple UI and all the MouseListener methods are implemented by displaying a corresponding message in the status section of Applet. 3. Unit Testing Code: Write a simple html and include the MouseEventsApplet object using the Applet tag and passing code, height and width attributes. 4. Test Cases: Test1: Test by moving the mouse into and out of the applet and by clicking the mouse in the applet and see the applet status message change. 5. Reference Implementation: #################################################################### File: MouseEventsApplet.java import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; public class MouseEventsApplet extends JApplet implements MouseListener { public void init() { JLabel lLabel = new JLabel("Welcome to Applet World!", SwingConstants.CENTER); getContentPane().add(lLabel); lLabel.setBorder(new javax.swing.border.EmptyBorder(0,0,0,0)); setPreferredSize(new Dimension(400,300)); setVisible(true); addMouseListener(this); }

public void mouseClicked(MouseEvent e) { showStatus("Mouse was clicked"); } 50

JAVA LAB MANUAL

BIET

public void mouseEntered(MouseEvent e) { showStatus("Mouse Entered"); } public void mouseExited(MouseEvent e) { showStatus("Mouse Exited"); } public void mousePressed(MouseEvent e) { showStatus("Mouse was Pressed"); } public void mouseReleased(MouseEvent e) { showStatus("Mouse was Released"); } } File: MouseEventsAppletTest.html #################################################################### 6. Execution: 1. javac MouseEventsApplet.java 2. go to MouseEventsAppletTest.html in your browser

51

JAVA LAB MANUAL

BIET

Experiment – 14: Draw Lines 1. Problem Statement: Write a Java Program that allows the user to draw line, rectangles. 2. Solution Design: Write a class called MyCanvas which encapsulates a Canvas object to which a mouseListener is added. When the mouse is clicked, the point where the click was done will be added to the ArrayList of points. When the button called DrawLine is clicked, the pointsArray is checked for entries and if there are more than 2 points selected a line is drawn in the paint method from point1 to point 2. 3. Unit Testing Code: Main method in MyCanvas class which creates the MyCanvas object and adds it to a frame and displays it. 4. Test Cases: Test1: Click on more than 2 points in canvas and than click button. A line will be drawn. Test2: Click on 0 or 1 points in canvas and click draw line button. A message will be displayed saying line cannot be drawn. 5. Reference Implementation: #################################################################### File: MyCanvas.java import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.border.*; import java.util.*; public class MyCanvas extends JPanel { private Canvas mCanvas = null; private ArrayList mPointsSelected; private int mActionSelected = 0; public MyCanvas() 52

JAVA LAB MANUAL

BIET

{ setLayout(new BorderLayout()); mCanvas = new Canvas(); mCanvas.addMouseListener(new MyMouseListener()); add(mCanvas, BorderLayout.CENTER); JPanel lButtonPanel = new JPanel(); lButtonPanel.setLayout(new GridLayout(1,1)); JButton lDrawLineButton = new JButton("Draw Line"); lDrawLineButton.addActionListener(new MyActionListener()); lButtonPanel.add(lDrawLineButton); add(lButtonPanel, BorderLayout.SOUTH); mPointsSelected = new ArrayList(); } public class MyMouseListener extends MouseAdapter { public void mouseClicked(MouseEvent e) { mPointsSelected.add(e.getPoint()); } } public class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { if(mPointsSelected.size() >= 2) { repaint(); revalidate(); //mPointsSelected.clear(); } else { System.out.println("Not enough points to draw a line"); } } } 53

JAVA LAB MANUAL

BIET

public synchronized void paint(Graphics g) { if(mPointsSelected.size() >= 2) { Point pnt1 = mPointsSelected.get(0); Point pnt2 = mPointsSelected.get(1); int x1 = (int) pnt1.getX(); int y1 = (int) pnt1.getY(); int x2 = (int) pnt2.getX(); int y2 = (int) pnt2.getY(); //g.setColor(new Color(255,0,0)); mCanvas.getGraphics().drawLine(x1,y1,x2,y2); mPointsSelected.clear(); } } public static void main(String[] args) { JFrame lFrame = new JFrame(); lFrame.getContentPane().setLayout(new GridLayout(1,1)); MyCanvas lCanvas = new MyCanvas(); lFrame.getContentPane().add(lCanvas); lFrame.setSize(400,150); lFrame.show(); } } #################################################################### 6. Execution: 1. javac MyCanvas.java 2. java MyCanvas Introduction to Unit - IV

54

JAVA LAB MANUAL

BIET

This unit covers JAVA’s features for parallel programming using threads and JAVA’s support for building client/server application using socket programming. The packages in JAVA API you would be exposed to are java.lang for Thread related classes and java.net for socket programming related data. Main API Classes Used: 1. java.lang.Thread 2. java.lang.Runnable 3. java.net.ClientSocket 4. java.net.ServerSocket 5. ObjectInputStream 6. ObjectOutputStream Language Concepts Learnt: 1. Parallel Programming means we have more than one execution threads running in parallel as far as the user goes as against conventional programs w hich have one line of execution 2. Threads is JAVA’s API for providing the users the ability to have multiple lines of execution in a given program. Threads allow users to start parallel lines of execution, suspend it and share data across multiple threads. 3. Synchronization in JAVA allows users to control parallel access to shared objects from multiple threads to ensure shared objects do not get into inconsistent states. 4. Socket Programming allows users to write server programs that are running on a machine tied to a socket and listening for client requests for service and respond to them. Clients need to know the machine and socket on which the service is running so it can use the server for a service. It also needs to know the protocol or the message format which the server would understand. 5. Server Socket is distinct from client socket because it is a listening socket only there to listen to new client connections all the time.

6. Client Socket is used by clients to open a socket on the client side which will connect to the server through server socket and get linked up to a unique socket

55

JAVA LAB MANUAL

BIET

on the server side for a given connection so message can be exchanged between client and server till one of the parties closes the connection. 7. Reflection API is JAVA’s support for RTTI (runtime type identification) and allows for objects to be created at runtime, messages to be invoked at runtime with parameters also constructed at runtime.

Experiment – 15: Multiple Threads 1. Problem Statement: Write a Java Program for creating multiple threads. 2. Solution Design: 56

JAVA LAB MANUAL

BIET

Write a class MyThread that extends Thread and has a static Counter and a thread number as members. The run method should call the method called incrementCounter which would be a static method the MyThread class and increments the ourCounter variable value and prints its value with the Thread id of the Thread object which invokes this method. incrementCounter method should be synchronized so multiple threads do not try to increment the counter at precisely the same time. Class: MyThread Interface: run() Other Methods: static incrementCounter() Members: int for thread id and a static ourCounter. 3. Unit Testing Code: A main in the same class or in another test class that creates multiple thread objects with different ids. The threads are started both of them with a certain time -lag. 4. Test Cases: Test1: create 2 threads with ids 0 & 1 and start them. 5. Reference Implementation: #################################################################### File: MyThread.java public class MyThread extends Thread { public static int ourCounter = 0; private int mId; public MyThread(int id) { mId = id; } public void run() { while(true) { incrementCounter(); try { Thread.sleep(300); } catch(Exception e) 57

JAVA LAB MANUAL

BIET

{ e.printStackTrace(); } } } synchronized public void incrementCounter() { MyThread.ourCounter = MyThread.ourCounter + 1; System.out.println(mId + ":" + MyThread.ourCounter); } } File: MyThreadTest.java public class MyThreadTest { public static void main(String[] args) { MyThread thread1 = new MyThread(0); MyThread thread2 = new MyThread(1); thread1.start(); try { Thread.sleep(600); } catch(Exception e) { } thread2.start(); } } #################################################################### 6. Execution: 1. javac MyThread.java 2. javac MyThreadTest.java 3. java MyThreadTest

58

JAVA LAB MANUAL

BIET

Experiment – 16: Producer – Consumer Problem 1. Problem Statement: Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication. 2. Solution Design: Write a class called ProducerThread that extends Thread class and implements the run method by adding in an infinite loop Integer objects into a global stack object. Write a class called CosumerThread that extends Thread class and implements the run method by popping from a global stack in an infinite loop. Write a class called ProducerConsumerExample that create the 2 threads, both running infinitely and one producing for the other to consume at its convenience. 3. Unit Testing Code: Let the producer add a series of elements to the stack and notice that the last item produced will be the next item consumed if you make the producer and consumer item print what they produce and consume respectively. 4. Test Cases: Test1: Series of Integers 1, 2, 3, 4, …… being produced with a counter. 5. Reference Implementation: #################################################################### File: ProducerThread.java import java.util.*; public class ProducerThread extends Thread { public void run() { while(true) { Integer lInt = new Integer("30"); ProducerConsumerExample.ourStack.push(lInt); System.out.println("Produced:"); } } } 59

JAVA LAB MANUAL

BIET

File: ConsumerThread.java import java.util.*; public class ConsumerThread extends Thread { public void run() { while(true) { while(ProducerConsumerExample.ourStack.empty()) { try { Thread.sleep(200); } catch(Exception e) { } } System.out.println("The item consumed is: " + (ProducerConsumerExample.ourStack.pop()).intValue()); } } }

File: ProducerConsumerExample.java import java.util.*; public class ProducerConsumerExample { public static Stack ourStack = new Stack(); public static void main(String[] args) { Thread prod = new ProducerThread(); prod.start(); Thread consu = new ConsumerThread(); 60

JAVA LAB MANUAL

BIET

consu.start(); } } #################################################################### 6. Execution: 1. javac ProducerThread.java 2. javac ConsumerThread.java 3. javac ProducerConsumerExample.java Experiment – 17: Runtime polymorphism Illustration. 1. Problem Statement: Write a Java program that illustrates how run time polymorphism is achieved. 2. Solution Design: Write a simple class called MyParent which has a default constructor and a public method called displayMessage which display a message indicating the message is coming from an object of this class. Write another class called MyChild that inherits from MyParent and overrides displayMessage() method to print a message indicating that the object is of MyChild type. Now write a test class which has a main method in which we create an ArrayList of MyParent type objects and add to it first an object of MyParent type and then an object of MyChild type. To first see how JAVA’s runtime polymorphism works, call the displayMessage method on each of the ArrayList objects. Than in another loop use the JAVA Reflection API’s Classes Class, Object, Method to dynamically get the type of the object in the ArrayList, get a method reference to displayMessage and invoke the method on the obj in question with an object array with no elements as arguments to this method. Classes: MyParent, MyChild, RunTimePolymorphismTest Public Methods: displayMessage() in MyParent and overridden in MyChild, a class that inherits from MyParent. Member Variables: None 3. Unit Testing Code: In the main, we are first relying on JAVA’s runtime polymorphism and than doing our own runtime polymorphism and ensuring that the result is the same in both cases. 4. Test Cases: Test1: ArrayList of Base Class Type MyParent populated with at-least 2 objects, one of Base Class Type and the other of Derived Class Type. Java’s internal Runtime polymorphism and our implementation of polymorphism should yield the same result. 61

JAVA LAB MANUAL

BIET

5. Reference Implementation: #################################################################### File: MyParent.java public class MyParent { public MyParent() { } public void displayMessage() { System.out.println("This is an object of parent class"); } } File: MyChild.java public class MyChild extends MyParent { public MyChild() { super(); } public void displayMessage() { System.out.println("This is an object of child class"); } } File: RuntimePolymorphismTest.java import java.util.*; import java.lang.reflect.*; public class RuntimePolymorphismTest { public static void main(String[] args) 62

JAVA LAB MANUAL

BIET

{ ArrayList<MyParent> lList = new ArrayList<MyParent>(); lList.add(new MyParent()); lList.add(new MyChild()); System.out.println("Let us see a demo of runtime polymorphism first!"); for(int i=0; i < 2; i++) { ((MyParent)(lList.get(i))).displayMessage(); } System.out.println("Manually implemented runtime polymorphism!"); for(int i=0; i < 2; i++) { try { Object obj = lList.get(i); // zero orgument method and hence array of 0 elements Class cls = obj.getClass(); Class[] clsArr = new Class[0]; Object[] objArr = new Object[0]; Method mtd = cls.getMethod("displayMessage",clsArr); mtd.invoke(obj,objArr); } catch(Exception e) { e.printStackTrace(); } } } } #################################################################### 6. Execution: 1. javac MyParent.java 2. javac MyChild.java 63

JAVA LAB MANUAL

BIET

3. javac RuntimePolymorphismTest.java 4. java RuntimePolymorphismTest

64

Related Documents

Java Manual
June 2020 7
Manual Java Script
November 2019 25
Manual Java - C#
June 2020 10
Manual De Java
November 2019 15
Manual Java Swing
November 2019 10