Lab 3 Programming in Java - CS 359 and Project Design
Lab 3 Programming in Java - CS 359 and Project Design
WORKBOOK
Programming in Java - CS 359 and Project Design
T. Y. B. Sc. (Computer Science)
SEMESTER V
Student Name:
College:
Year: Division:
Prepared by:
Ms. Rashmi Baghel. Nowrosjee WadiaCollege, Hadapsar, Pune.
Page 3 of 70
Table of Contents
1 Introduction 4-6
Introduction
Bring variation and variety in experiments carried out by different students in a batch
The Object Oriented Programming using Java, practical syllabus is divided into five
assignments. Each assignment has problems divided into three sets A, B and C.
Set A is used for implementing the basic algorithms or implementing data structure
along with its basic operations. Set A is mandatory.
Set B is used to demonstrate small variations on the implementations carried out in set
A to improve its applicability. Depending on the time availability the students should
be encouraged to complete set B.
Set C prepares the students for the viva in the subject. Students should spend
additional time either at home or in the Lab and solve these problems so that they get
a deeper understanding of the subject.
Page 5 of 70
Students should prepare oneself before hand for the Assignment by reading the
relevant material.
Instructor will specify which problems to solve in the lab during the allotted slot and
student should complete them and get verified by the instructor. However student
should spend additional hours in Lab and at home to cover as many problems as
possible given in this work book.
Explain the assignment and related concepts in around ten minutes using white board
if required or by demonstrating the software.
The value should also be entered on assignment completion page of the respective
Lab course.
Page 6 of 70
You have to ensure appropriate hardware and software is made available to each
student.
Project Design
1 Project Synopsis
2 Behavioral Models
3 Architectural Models
5 Screen Design
University Exam Seat Number has successfully completed the course work
for CS 359 - Programming in Java and has scored Marks out of 15.
Instructor Head
CS – 359
Object Oriented
Programming
Using Java
Page 9 of 70
Objectives
2. java:- This command starts Java runtime environment, loads the specified .class file
and executes the main method.
Syntax: java fileName
4. jdb: - jdb helps you find and fix bugs in Java language programs. This debugger has
limited functionality.
Syntax: jdb [ options ] [ class ] [ arguments ]
options : Command-line options.
class : Name of the class to begin debugging.
arguments : Arguments passed to the main() method of class.
After starting the debugger, the jdb commands can be executed. The important jdb
commands are:
i. help, or?: The most important jdb command, help displays the list of
recognized commands with a brief description.
ii. run: After starting jdb, and setting any necessary breakpoints, you can use
this command to start the execution the debugged application.
Page 11 of 70
5. javap: - The javap tool allows you to query any class and find out its list of methods
and constants.
javap [ options ] class
Example: javap java.lang.String It is a disassembler which allows the bytecodes of a
class file to be viewed when used with a classname and the –c option.
javap -c class
Setting CLASSPATH
The classpath is the path that the Java runtime environment searches for classes and
other resource files. The class path can be set using either the –classpath option or by
setting the CLASSPATH environment variable.
The -classpath option is preferred because you can set it individually for each
application without affecting other applications and without other applications
modifying its value.
Page 12 of 70
The default value of the class path is ".", meaning that only the current directory is
searched. Specifying either the CLASSPATH variable or the -cp command line
switch overrides this value.
Example
CLASSPATH=.:/usr/local/classes.jar:/home/user1/myclasses
export CLASSPATH
To retain the existing classpath setting, use $CLASSPATH in the new list.
export CLASSPATH=$CLASSPATH:/home/user1/myclasses
About Eclipse
/**
Member function
@param x Represents the new value of num
@return void No return value */
Type the following command: javadoc MyClass.java. See the HTML documentation file
MyClass.html.
switch (ch)
{
case 'S':
System.out.println("Sunday");
break;
case 'M':
System.out.println("Monday");
break;
case 'T':
System.out.println("Tuesday");
break;
case 'W':
System.out.println("Wednesday");
break;
Page 15 of 70
case 't':
System.out.println("Thursday");
break;
case 'F':
System.out.println("Friday");
break;
case 's':
System.out.println("Saturday");
break;
}
}
}
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" "); //display 2D array
}
System.out.println();
}
}
}
Page 16 of 70
Lab Assignment
Set A
a) Using javap, view the methods of the following classes from the lang package:
java.lang.Object , java.lang.String and java.util.Scanner. and also Compile sample
program 8. Type the following command and view the bytecodes. javap -c MyClass.
Set B
a) Write a java program to display the system date and time in various formats shown
below:
Page 17 of 70
b) Define a class MyNumber having one private int data member. Write a default
constructor to initialize it to 0 and another constructor to initialize it to a value
(Use this). Write methods isNegative, isPositive, isZero, isOdd, isEven. Create an
object in main. Use command line arguments to pass a value to the object
(Hint : convert string argument to integer) and perform the above tests. Provide
javadoc comments for all constructors and methods and generate the html help file.
Set C
a) Write a program to accept n names of country and display them in descending
order.
b) Write a menu driven program to perform the following operations on 2D array:
i. Sum of diagonal elements
ii. Sum of upper diagonal elements
iii. Sum of lower diagonal elements
iv. Exit
c) Write a program to display the 1 to 15 tables.
(1*1=1 2*1=2 ……. 15 * 1 = 15
1*2=2 2*2=4 15 * 2 = 30
1*3=3 2*3=6 15 * 3 = 45
… … …..
1 * 10 = 10 2 * 10 = 20 15 * 10 = 150)
Assignment Evaluation
Practical In-charge
Page 18 of 70
Objectives
Defining a class.
Creating an array of objects.
Creating a package.(Using package command)
Using packages(Using import command)
Reading
You should read the following topics before starting this exercise:
Ready Reference
class classname
{
type instance-variable1;
type instance-variable2;
//...
type instance-variableN;
type methodname1(parameter-list)
{
//bodyofmethod
}
type methodname2(parameter-list)
{
//bodyofmethod
}
//...
type methodnameN(parameter-list)
{
//bodyofmethod
}
}
Page 19 of 70
Example :
class Student
{
private int rollNumber;
private String name;
Student() //constructor
{
rollNumber=0;name=null;
}
Student(int rollNumber,String name)
//paramterised constructor
{
this.rollNumber=rollNumber;
this.name=name;
}
void display()
{
System.out.println("Rollnumber="+rollNumber);
System.out.println("Name="+name);
}
}
Creating objects:
Syntax
ClassName referenceName;
referenceName = new ClassName()
OR
Example :
Student s1 = new Student();
Student s2 = new Student(10,"ABC");
Constructor:
Types of Constructors
1. Default Constructor
2. Parameterised Constructor
Page 20 of 70
Example :
Student s1 = new Student();
Student s2 = new Student(100,"XYZ");
Syntax :
Example
class Student
{
private int rollNumber;
private String name;
public String toString()
{
return "RollNumber = " +rollNumber + "Name = " +name;
}
}
Syntax :
ClassName[ ] arrayName = new ClassName[size];
Example :
Student[ ] studentArray = new Student[10];
Example :
for(i=0;i<10;i++)
studentArray[i] = new Student();
Page 21 of 70
Wrapper classes : The wrapper class in Java provides the mechanism to convert
primitive into object and object into primitive.
Method Purpose
Output:
20 20 20
Example : //Program to demonsrtrate unwrapping
public class WrapperExample2
{
public static void main(String args[])
{
//Converting Integer to int
Integer a=new Integer(3);
int i = a.intValue(); //converting Integer to int
int j = a; //unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}
}
Output:
333
Page 22 of 70
Simple I/O
Syntax :
Or
For this,you will have write the following statement at the beginning:
import java.io.*;
Packages:
Creating a package :
To create a user defined package, the package statement should be written in the source
code file. This statement should be written as the first line of the program. Save the
program in a directory of the same name as the package.
Syntax :
package packageName;
Accessing a package
Syntax :
import packageName.*; //importsallclasses
import packageName.className; //importsspecifiedclass
Note that the package can have a hierarchy of subpackages. In that case, the pack age
name should be qualified using its parentpackages.
Example :
project.sourcecode.java
Here,the package named project contains one subpackage named source code which
contains a subpackage named java.
Page 23 of 70
Access Rules :
The access rules for member so for class are given in the table below.
Self-Activity
Sample program 3 : To read Student roll number and name from the console
and display them (Using BufferedReader).
import java.io.*;
class ConsoleInput
{
public static void main(String[] args)
{
int rollNumber;
String name;
BufferedReaderbr = new BufferedReader (newInputStreamReader(System.in));
System.out.println("Entertherollnumber:");
rollNumber = Integer.parseInt(br.readLine());
System.out.println("Enter the name:");
name = br.readLine();
System.out.println("RollNumber = " +rollNumber);
System.out.println("Name = "+name);
}
}
Page 25 of 70
Sample program 4: To read Student roll number and name from the Console
and display them (Using Scannerclass).
import java.util.Scanner;
class ScannerTest
{
public static void main(Stringargs[]) throwsException
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter your rollno and name:");
int rollno = sc.nextInt();
String name = sc.next();
System.out.println("Rollno :" + rollno + "Name : " +name);
sc.close();
}
}
//B.java
package P1.P2; //P2 is a subpackage of P1
public class B
{
public void display()
{
System.out.println("IndisplayofB");
}
}
//PackageTest.java
import P1.*;
import P1.P2.*;
class PackageTest
{
public static void main (String args[])
{
A obj1 = new A();
obj1.display();
B obj2 = new B();
Obj2.display();
}
}
Create folder P1.Save A.java in folder P1.Create folder P2 in side P1.Save B.java in P2.
Lab Assignments
Set A
a) Create an employee class(id,name,deptname,salary). Define a default and
parameterized constructor. Use ‘this’ keyword to initialize instance variables.
Keep a count of objects created. Create objects using parameterized constructor
and display the object count after each object is created.(Use static member and
method). Also display the contents of each object.
Student class. Accept details from the user for each object. Define a static
method “sortStudent” which sorts the array on the basis of percentage.
c) Write a java program to accept 5 numbers using command line arguments sort and
display them.
d) Write a java program that take input as a person name in the format of first, middle
and last name and then print it in the form last, first and middle name, where in the
middle name first character is capital letter.
Set B
a) Write a Java program to create a Package “SY” which has a class SYMarks
(members – ComputerTotal, MathsTotal, and ElectronicsTotal). Create another
package TY which has a class TYMarks (members – Theory, Practicals). Create n
objects of Student class (having rollNumber, name, SYMarks and TYMarks). Add
the marks of SY and TY computer subjects and calculate the Grade (‘A’ for >= 70,
‘B’ for >= 60 ‘C’ for >= 50 , Pass Class for > =40 else ‘FAIL’) and display the result
of the student in proper format.
a) Write a package for String operation which has two classes Con and Comp. Con class
has to concatenates two strings and comp class compares two strings. Also display
proper message on execution.
b) Create four member variables for Customer class. Assign public, private, protected
and default access modifiers respectively to these variables. Try to access these
variables from other classes (Same package and Different package)
Assignment Evaluation
Practical In-charge
Page 28 of 70
Objectives
Reading
You should read the following topics before starting this exercise:
Concept of inheritance.
Use of extends keyword.
Concept of abstract class.
Defining an interface.
Use of implements keyword.
Ready Reference
Inheriting a class :
The syntax to create sub class is:
Types of Inheritance
Access in subclass
Example:
classA
{
protected int num;
A(int num)
{
this.num=num;
}
}
class B extends A
{
int num;
B(int a, int b)
{
super(a); //should be the first line in the subclass constructor
this.num=b;
}
void display()
{
System.out.println("In A, num = "+super.num);
System.out.println("In B, num = "+num);
}
}
Overriding methods
Redefining superclass methods in a subclass is called overriding. The signature of the
subclass method should be the same as the superclass method.
Syntax
class A
{
void method1(int num)
{
//code
}
}
class B extends A
{
void method1(int x)
{
//code
}
}
Page 30 of 70
Dynamic binding
When over-riding is used ,the method call is resolved during run-time i.e. depending on
the object type, the corresponding method will be invoked.
Example :
A ref;
ref = new A();
ref.method1(10); //calls method of class
A ref = new B();
ref.method1(20); //calls method of classB
Abstract class
An abstract class is a class which cannot be instantiated. It is only used to create
subclasses. A class which has abstract methods must be declared abstract.
An abstract class can have data members, constructors, method definitions and method
declarations.
Syntax :
abstract class ClassName
{
...
}
Abstract method
An abstract method is a method which has no definition. The definition is provided by
the subclass.
Syntax :
abstract returnType method(arguments);
Interface
An interface is a pure abstract class i.e. it has only abstract methods and final variables.
An interface can be implemented by multiple classes.
Syntax :
interface InterfaceName
{
//abstract methods
//final variables
}
Example:
interface MyInterface
{
void method1();
void method2();
int size=10; //finalandstatic
}
class MyClass implements MyInterface
{
//definemethod1andmethod2
}
Page 31 of 70
Marker Interface :
An interface that does not contain methods, fields, and constants is known as marker
interface. In other words, an empty interface is known as marker interface or tag interface. It
delivers the run-time type information about an object. It is the reason that the JVM and
compiler have additional information about an object.
The Serializable and Cloneable interfaces are the example of marker interface. In short, it
indicates a signal or command to the JVM. The declaration of marker interface is the same as
interface in Java but the interface must be empty.
Example:
public interface Serializable
{
…..
}
Functional Interfaces
A functional interface in Java is an interface that contains only a single abstract
(unimplemented) method. A functional interface can contain default and static methods
which do have an implementation, in addition to the single unimplemented method.
Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces.
It is a new feature in Java, which helps to achieve functional programming approach.
Syntax :
public interface MyFunctionalInterface()
{
// abstract method
public void functionalMethod();
}
Example :
The below interface is a functional interface in Java, since it only contains a single non-
implemented method execute()
lambda Expression
A Java lambda expression is thus a function which can be created without belonging to any
class. Java lambda expressions are commonly used to implement simple event listeners /
callbacks, or in functional programming with the Java Streams API.
Syntax :
lambda operator -> body
Multiple parameters :
(t1, t2) -> System.out.println("Multiple parameters: "
+ t1 + ", " + t2);
OR
MyFunctionalInterfacefunctionalInterface = () ->
{
// basic functionality logic goes here
}
Example :
MyFunctionalInterface lambda = () ->
{
System.out.println("Executing...");
}
A Java lambda expression implements a single method from a Java interface. In order to
know what method the lambda expression implements, the interface can only contain a single
unimplemented method i.e. functional interface.
Self-Activity
Execute all the sample programs
Sample program 1 : To demonstrate Inheritance concept.
class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent
{
Page 33 of 70
class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Sample Program 3 : To illustrate Interfaces.
interface Result
{
final static float pi-3.14f;
float compute(float x, float y);
}
Page 34 of 70
super(radius);
this.height=height;
}
public double area() //overriding
{
return java.util.Math.PI*radius*radius*height;
}
}
public class Test
{
public static void main (String []args)
{
Shape s;
s = new Circle(5.2);
System.out.println(“Area of circle =”+s.area());
s = new Cylinder(5,2.5);
System.out.println(“Area of cylinder=”+s.area());
}
}
@FunctionalInterface
interface PrintNumber
{
public void print(int num1);
}
Lab Assignments
Set A
a) Write a program for multilevel inheritance such that country is inherited from
continent. State is inherited from country. Display the place, state, country
and continent.
Page 36 of 70
b) Define an abstract class Staff with protected members id and name. Define a
parameterized constructor. Define one subclass OfficeStaff with member
department. Create n objects of OfficeStaff and display all details.
d) Write a program to find the cube of given number using function interface.
Set B
a) Create an abstract class “order” having members id,description.Create two
subclasses “Purchase Order” and “Sales Order” having members customer name
and Vendor name respectively.Define methods accept and display in all cases.
Create 3 objects each of Purchase Order and Sales Order and accept and display
details.
For the third option, a search is to be made on the basis of the entered registration
Number.
Assignment Evaluation
Practical In-charge
Page 37 of 70
Objectives
Reading
You should read the following topics before starting this exercise:
Concept of Exception and Exception class hierarchy.
Use of try, catch, throw, throws and finally keywords
Defining user defined exception classes
Concept of streams and Types of streams
Byte and Character stream classes and File class .
Ready Reference
Throwable
Error Exception
Runtime Exception
Unchecked Error Checked Exception
Unchecked Exception
Syntax :
try
{
// code that may cause an exception
}
catch (ExceptionType1 object)
{
// handle the exception
}
catch (ExceptionType2 object)
{
// handle the exception
}
finally
{
// this code is always executed
}
Example:
try
{
int a = Integer.parseInt(args[0]);
...
}
catch(NumberFormatException e)
{
System.out.println(“ Exception Caught” ) ;
}
Example:
catch(NumberFormatException e)
{
System.out.println(“Caught and rethrown” ) ;
throw e;
}
We can explicitly create an exception object and throw it.
For Example:
throw new NumberFormatException();
throws keyword:
If the method cannot handle the exception, it must declare a list of exceptions it may cause.
Page 39 of 70
This list is specified using the throws keyword in the method header.
All checked exceptions muct be caught or declared.
Syntax:
returnType methodName(arguments) throws ExceptionType1
[,ExceptionType2...]
{
//method body
}
Example:
Unchecked Exceptions:
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked
thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread
state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.
Checked Exceptions:
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable
Page 40 of 70
interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
A user defined exception class can be created by extending the Exception class.
class UserDefinedException extends Exception
{
//code
}
When that exception situation occurs, an object of this exception class can be created and
thrown.
For example, if we are accepting an integer whose valid values are only positive, then we
can throw an “InvalidNumberException” for any negative value entered.
java.io.File class
Example :
File f1=new File(“/home/java/a.txt”);
Methods
boolean canRead()- Returns True if the file is readable.
boolean canWrite()- Returns True if the file is writeable.
String getName()- Returns the name of the File with any directory names omitted.
boolean exists()- Returns true if file exists
String getAbsolutePath()- Returns the complete filename.
Otherwise, if the File is a relative file specification, it returns the relative filename appended
to the current working directory.
String getParent() - Returns the directory of the File. If the File is an absolute
specification.
String getPath() - Returns the full name of the file, including the directory name.
boolean isDirectory() - Returns true if File Object is a directory
boolean isFile() - Returns true if File Object is a file
long lastModified() - Returns the modification time of the file (which should be used
for comparison with other file times only, and not interpreted as any particular time
format).
long length() - Returns the length of the file.
boolean delete() - deletes a file or directory. Returns true after successful deletion of a
file.
boolean mkdir () - Creates a directory.
boolean renameTo(File dest) - Renames a file or directory. Returns true after
successful renaming
Directories
A directory is a File that contains a list of other files & directories. When you create a File
object and it is a directory, the isDirectory() method will return true. In this case list method
can be used to extract the list of other files & directories inside.
Streams
A stream is a sequence of bytes. When writing data to a stream, the stream is called an output
stream. When reading data from a stream, the stream is called an input stream. If a stream has
a buffer in memory, it is a buffered stream. Binary Streams contain binary data. Character
Streams have character data and are used for storing and retrieving text.
ByteStrea
CharacterStrea
ByteStrea ByteStrea
Reader Writer
There are four top level abstract stream classes: InputStream, OutputStream, Reader, and
Writer.
1. InputStream. A stream to read binary data.
2. OutputStream. A stream to write binary data.
3. Reader. A stream to read characters.
4. Writer. A stream to write characters.
ByteStream Classes
a. InputStream Methods-
3. int read(byte buffer[ ], int offset, int numbytes) - Attempts to read up to numbytes
bytes into buffer starting at buffer[offset]. Returns actual number of bytes that are
read. At the end returns –1.
4. void close() - to close the input stream
5. void mark(int numbytes) - places a mark at current point in input stream & remain
valid till number of bytes are read.
6. void reset() - Resets pointer to previously set mark/ goes back to stream beginning.
7. long skip(long numbytes) - skips number of bytes.
8. int available() - Returns number of bytes currently available for reading.
b. OutputStream Methods-
1. void close() - to close the OutputStream
2. void write (int b) - Writes a single byte to an output stream.
3. void write(byte buffer[ ]) - Writes a complete array of bytes to an output stream.
4.void write (byte buffer[ ], int offset, int numbytes) - Writes a sub range of numbytes
bytes from the array buffer, beginning at buffer[offset].
5. void flush() - clears the buffer.
CharacterStream Classes
Reader : Reader is an abstract class that defines Java’s method of streaming character input.
All methods in this class will throw an IOException.
Writer : Is an abstract class that defines streaming character output. All the methods in this
class returns a void value & throws an IOException.
Methods :
Example:
File f = new File("data.dat"); //Open the file for both reading and writing
RandomAccessFile rand = new RandomAccessFile(f,"rw");
rand.seek(f.length()); //Seek to end of file
rand.writeBytes("Append this line at the end"); //Write end of file
rand.close();
System.out.println("Write-Successful");
Self Activity
Sample program 1 : To demonstrate exceptions.
class NegativeNumberException extends Exception
{
NegativeNumberException(int n)
{
System.out.println(“Negative input : “ + n);
}
}
public class ExceptionTest
{
public static void main( String args[] )
{
int num, i, sum=0;
try
{
num = Integer.parseInt(args[0]);
if(num < 0)
throw new NegativeNumberException(num);
Page 46 of 70
{
System.out.println ("IO exception =" + e );
}
System.out.println ("No of lines containing “ +
string_to_find + “ = ” + num_lines);
} // main
} //class TextFileReadApp
Sample program 3 :/* Program to write and read primitive types to a file */
import java.io.*;
class PrimitiveTypes
{
public static void main(String args[]) throws IOException
{
FileOutputStream fos = new FileOutputStream("info.dat");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(25);
dos.writeBoolean(true);
dos.writeChar('A');
dos.writeDouble(5.45);
fos.close();
FileInputStream fis = new FileInputStream("info.dat") ;
DataInputStream dis = new DataInputStream(fis);
int num = dis.readInt();
boolean b = dis.readBoolean();
char ch = dis.readChar();
double dbl = dis.readDouble();
System.out.println("Int- "+num +"\nBoolean- "+b);
System.out.println("\nCharacter- "+ch+"\nDouble- "+dbl);
fis.close();
} //main
} //class
Sample program 4 : /* Program to read integers from a file using Scanner class*/
import java.io.*;
import java.util.*;
class ReadIntegers
{
public static void main(String args[]) throws IOException
{
FileReader file = new FileReader("numbers.txt");
Scanner sc = new Scanner(file);
int sum=0, num;
while(sc.hasNext())
{
num = sc.nextInt();
System.out.println("Number = "+ num);
sum = sum+num;
}
System.out.println("The sum = "+ sum); file.close();
}//main
Page 48 of 70
} //class
Lab Assignments
Set A
a) Define a class patient (patient_name, patient_age,
patient_oxy_level,patient_HRCT_report). Create an object of patient. Handle
appropriate exception while patient oxygen level less than 95% and HRCT scan report
greater than 10, then throw user defined Exception “Patient is Covid Positive(+) and
Need to Hospitalized” otherwise display its information.
b) Write a program to read a text file “sample.txt” and display the contents of a file in
reverse order and also original contents change the case (display in upper case).
c) Accept the names of two files and copy the contents of the first to the second.
First file having Book name and Author name in file. Second file having the contents
of First file and also add the comment ‘end of file’ at the end.
Set B
a) Write a program to read book information (bookid, bookname, bookprice, bookqty) in
file “book.dat”. Write a menu driven program to perform the following operations
using Random access file:
i. Search for a specific book by name.
ii. Display all book and total cost
b) Define class EmailId with members ,username and password. Define default and
parameterized constructors. Accept values from the command line Throw user
defined exceptions – “InvalidUsernameException” or “InvalidPasswordException” if
the username and password are invalid.
c) Define a class MyDate (day, month, year) with methods to accept and display a
MyDate object. Accept date as dd, mm, yyyy. Throw user defined exception
“InvalidDateException” if the date is invalid.
Examples of invalid dates : 03 15 2019, 31 6 2000, 29 2 2021
Set C
a) Write a menu driven program to perform the following operations on a set of integers
as shown in the following figure. A load operation should generate 10 random
integers (2 digit) and display the number on screen. The save operation should save
the number to a file “number.txt”. The short menu provides various operations and the
result is displayed on the screen.
b) Write a java program to accept Employee name from the user and check whether it is
valid or not. If it is not valid then throw user defined Exception “Name is Invalid”
otherwise display it.(Name should contain only characters)
Page 49 of 70
Assignment Evaluation
Practical In-charge
Page 50 of 70
Objectives
Reading
You should read the following topics before starting this exercise
Ready Reference
Graphical User Interface elements are implemented in two java packages – AWT and Swing.
Swing is the newer package and swing classes are based on AWT classes.
Swing Architecture:
The design of the Swing component classes is based on the Model-View-Controller
architecture, or MVC.
1. The model stores the data.
2. The view creates the visual representation from the data in the model.
3. The controller deals with user interaction and modifies the model and/or the
view.
Swing Classes:
The following table lists some important Swing classes and their description.
Class Description
Box Container that uses a BoxLayout.
JApplet Base class for Swing applets.
JButton Selectable component that supports text/image display.
JCheckBox Selectable component that displays state to user.
JCheckBoxMenuItem Selectable component for a menu; displays state to user.
JColorChooser For selecting colors.
JComboBox For selecting from a drop-down list of choices.
JComponent Base class for Swing components.
JDesktopPane Container for internal frames.
JDialog Base class for pop-up subwindows.
JEditorPane For editing and display of formatted content.
JFileChooser For selecting files and directories.
Page 51 of 70
Layout Manager
The job of a layout manager is to arrange components on a container. Each container has a
layout manager associated with it. To change the layout manager for a container, use the
setLayout() method.
Syntax :
Page 52 of 70
setLayout(LayoutManager obj)
Examples:
Important Containers:
1. JFrame –
This is a top-level container which can hold components and containers like panels.
Constructors
JFrame()
JFrame(String title)
Important Methods
setSize(int width, int height) - Specifies size of the frame in pixels.
setLocation(int x, int y) - Specifies upper left corner
setVisible(boolean visible) -Set true to display the frame
setTitle(String title) - Sets the frame title
setDefaultCloseOperation(int mode) -Specifies the operation when frame is closed.
The modes are:
JFrame.EXIT_ON_CLOSE
JFrame.DO_NOTHING_ON_CLOSE
JFrame.HIDE_ON_CLOSE
JFrame.DISPOSE_ON_CLOSE
2. JPanel -
This is a middle-level container which can hold components and can be added to other
containers like frame and panels.
Constructors
public javax.swing.JPanel(java.awt.LayoutManager, boolean);
public javax.swing.JPanel(java.awt.LayoutManager);
public javax.swing.JPanel(boolean);
public javax.swing.JPanel();
Important Components :
1. Label : With the JLabel class, you can display unselectable text and images.
Constructors-
JLabel(Icon i)
JLabel(Icon I , int n)
JLabel(String s)
JLabel(String s, Icon i, int n)
JLabel(String s, int n)
JLabel()
The int argument specifies the horizontal alignment of the label's contents within its
drawing area; defined in the SwingConstants interface (which JLabel implements):
LEFT (default), CENTER, RIGHT, LEADING, or TRAILING.
Methods-
1. Set or get the text displayed by the label.
void setText(String) String getText()
2. Set or get the image displayed by the label.
void setIcon (Icon) Icon getIcon()
3. Set or get the image displayed by the label when it's disabled. If you don't specify a
disabled image, then the look-and-feel creates one by manipulating the default image.
void setDisabledIcon(Icon) Icon getDisabledIcon()
4. Set or get where in the label its contents should be placed. For vertical alignment:
TOP, CENTER (the default), and BOTTOM.
void setHorizontalAlignment(int)
void setVerticalAlignment(int)
int getHorizontalAlignment()
int getVerticalAlignment()
2. Button : A Swing button can display both text and an image. The underlined letter in
each button's text shows the mnemonic which is the keyboard alternative.
Constructors-
JButton(Icon I)
JButton(String s)
JButton(String s, Icon I)
Methods-
void setDisabledIcon(Icon)
void setPressedIcon(Icon)
void setSelectedIcon(Icon)
void setRolloverIcon(Icon)
String getText()
Page 54 of 70
void setText(String)
Event- ActionEvent
3. Check boxes :
Class - JCheckBox
Constructors-
JCheckBox(Icon i)
JCheckBox(Icon i,booean state)
JCheckBox(String s)
JCheckBox(String s, boolean state)
JCheckBox(String s, Icon i)
JCheckBox(String s, Icon I, boolean state)
Methods-
void setSelected(boolean state)
String getText()
void setText(String s)
Event- ItemEvent
4. Radio Buttons :
Class- JRadioButton
Constructors-
JRadioButton (String s)
JRadioButton(String s, boolean state)
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
JRadioButton()
5. Combo Boxes :
Class- JComboBox
Constructors-
JComboBox()
Methods-
void addItem(Object)
Object getItemAt(int)
Object getSelectedItem()
int getItemCount()
Event- ItemEvent
6. List
Constructor- JList(ListModel)
Page 55 of 70
List models-
1. SINGLE_SELECTION - Only one item can be selected at a time.
When the user selects an item, any previously selected item is
deselected first.
2. SINGLE_INTERVAL_SELECTION- Multiple, contiguous items can
be selected. When the user begins a new selection range, any
previously selected items are deselected first.
3. MULTIPLE_INTERVAL_SELECTION- The default. Any
combination of items can be selected. The user must explicitly deselect
items.
Methods-
boolean isSelectedIndex(int)
void setSelectedIndex(int)
void setSelectedIndices(int[])
void setSelectedValue(Object, boolean)
void setSelectedInterval(int, int)
int getSelectedIndex()
int getMinSelectionIndex()
int getMaxSelectionIndex()
int[] getSelectedIndices()
Object getSelectedValue()
Object[] getSelectedValues()
Example-
listModel = new DefaultListModel();
listModel.addElement("India");
listModel.addElement("Japan");
listModel.addElement("France");
listModel.addElement("Denmark");
list = new JList(listModel);
Event- ActionEvent
7. Text:
classes All text related classes are inherited from JTextComponent class
a. JTextField
Creates a text field. The int argument specifies the desired width in columns.
The String argument contains the field's initial text. The Document argument
provides a custom document for the field.
Constructors-
JTextField()
JTextField(String)
JTextField(String, int)
JTextField(int)
JTextField(Document, String, int)
b. JPasswordField
Creates a password field. When present, the int argument specifies the
desired width in columns. The String argument contains the field's initial
text. The Document argument provides a custom document for the field.
Constructors-
Page 56 of 70
JPasswordField()
JPasswordField(String)
JPasswordField(String, int)
JPasswordField(int)
JPasswordField(Document, String, int)
Methods-
1. Set or get the text displayed by the text field.
void setText(String) String getText()
2. Set or get the text displayed by the text field.
char[] getPassword()
3. Set or get whether the user can edit the text in the text field.
void setEditable(boolean) boolean isEditable()
4. Set or get the number of columns displayed by the text field.
This is really just a hint for computing the field's preferred
width.
void setColumns(int); int getColumns()
5. Get the width of the text field's columns.
This value is established implicitly by the font.
int getColumnWidth()
6. Set or get the echo character i.e. the character displayed
instead of the actual characters typed by the user.
void setEchoChar(char) char getEchoChar()
Event- ActionEvent
c. JTextArea
Represents a text area which can hold multiple lines of text
Constructors-
JTextArea (int row, int cols)
JTextArea (String s, int row, int cols)
Methods-
void setColumns (int cols)
void setRows (int rows)
void append(String s)
void setLineWrap (boolean)
8. Dialog Boxes:
Types-
1. Modal- wont let the user interact with the remaining windows of
application
until first deals with it. Ex- when user wants to read a file, user must
specify file name before prg. can begin read operation.
2. Modeless dialog box- Lets the user enters information in both, the dialog
box & remainder of application ex- toolbar.
Swing has a JOptionPane class, that lets you put a simple dialog box.
Methods in JOption Class
1. static void showMessageDialog()- Shows a message with ok button.
2. static int showConfirmDialog()- shows a message & gets users options
from set of options.
Page 57 of 70
3. static int showOptionDialog- shows a message & get users options from
set of options.
4. String showInputDialog()- shows a message with one line of user input.
9. Menu:
Creating and Setting Up Menu Bars
Constructor or Method Purpose
JMenuBar() Creates a menu bar.
JMenu add(JMenu) Creates a menu bar.
void setJMenuBar(JMenuBar) Sets or gets the menu bar of an applet,
JMenuBar getJMenuBar() dialog, frame, internal frame, or root pane.
JMenuItem add(JMenuItem) Adds a menu item to the current end of the menu.
JMenuItem add(Action) If the argument is an Action object, then the menu
JMenuItem add(String) creates a menu item. If the argument is a string,
then the menu automatically creates a JMenuItem
object that displays the specified text.
void addSeparator() Adds a separator to the current end of the menu.
JMenuItem insert(JMenuItem, Inserts a menu item or separator into the menu at
int) JMenuItem insert(Action, the specified position. The first menu item is at
int) position 0, the second at position 1, and so on.
void insert(String, int) The JMenuItem, Action, and String arguments are
void insertSeparator(int) treated the same as in the corresponding add
methods.
void remove(JMenuItem) Removes the specified item(s) from the menu. If
void remove(int) the argument is an integer, then it specifies the
void removeAll() position of the menu item to be removed.
Event handling is an important part of GUI based applications. Events are generated by
event sources. A mouse click, Window closed, key typed etc. are examples of events.
All java events are sub-classes of java.awt.AWTEvent class.
Event Description
ComponentEvent Indicates that a component object (e.g. Button, List, TextField)
is moved, resized, rendered invisible or made visible again.
FocusEvent Indicates that a component has gained or lost the input focus.
KeyEvent Generated by a component object (such as TextField) when a
key is pressed, released or typed.
MouseEvent Indicates that a mouse action occurred in a component. E.g.
mouse is pressed, releases, clicked (pressed and released),
moved or dragged.
ContainerEvent Indicates that a container’s contents are changed because a
component was added or removed.
WindowEvent Indicates that a window has changed its status. This low level
event is generated by a Window object when it is opened,
closed, activated, deactivated, iconified, deiconified or when
focus is transferred into or out of the Window.
Event Description
ActionEvent Indicates that a component-defined action occurred. This high-
level event is generated by a component (such as Button) when
the component-specific action occurs (such as being pressed).
AdjustmentEvent The adjustment event is emitted by Adjustable objects like
scrollbars.
ItemEvent Indicates that an item was selected or deselected. This high-
level event is generated by an ItemSelectable object (such as a
List) when an item is selected or deselected by the user.
TextEvent Indicates that an object’s text changed. This high-level event is
generated by an object (such as TextComponent) when its text
changes.
The following table lists the events, their corresponding listeners and the method to add
the listener to the component.
Listener Methods:
Methods Description
ComponentListener
componentResized(ComponentEvent e) Invoked when component’s size changes.
componentMoved(ComponentEvent e) Invoked when component’s position changes.
componentShown(ComponentEvent e) Invoked when component has been made visible.
componentHidden(ComponentEvent e) Invoked when component has been made invisible.
FocusListener
focusGained(FocusEvent e) Invoked Invoked when component gains the keyboard focus.
focusLost(FocusEvent e) when component loses the keyboard focus.
KeyListener
keyTyped(KeyEvent e) Invoked when a key is typed.
keyPressed(KeyEvent e ) Invoked when a key is pressed.
keyReleased (KeyEvent e) Invoked when a key is released.
MouseListener
mouseClicked(MouseEvent e) Invoked when a mouse button is clicked (i.e. pressed
and released) on a component.
mousePressed(MouseEvent e) Invoked when a mouse button is pressed on a
component.
mouseReleased(MouseEvent e) Invoked when a mouse button is released on a
component.
mouseEntered(MouseEvent e) Invoked when a mouse enters a component.
mouseExited(MouseEvent e) Invoked when a mouse exits a component.
MouseMotionListener
mouseDragged(MouseEvent e) Invoked when a mouse button is pressed on a
component and then dragged.
mouseMoved(MouseEvent e) Invoked when a the mouse cursor is moved on to a
component but mouse button is not pressed.
ContainerListener
Page 61 of 70
TextListener
textValueChanged(ActionEvent e) Invoked when the value of the text has changed.
Adapter Classes:
All high level listeners contain only one method to handle the high-level events. But most
low level event listeners are designed to listen to multiple event subtypes (i.e. the
MouseListener listens to mouse-down, mouse-up, mouse-enter, etc.). AWT provides a set of
abstract “adapter” classes, which implements each listener interface. These allow programs to
easily subclass the Adapters and override only the methods representing event types they are
interested in, instead of implementing all methods in listener interfaces.
Applet methods:
Method Purpose
init( ) Automatically called to perform initialization of the applet. Executed only
once.
start( ) Called every time the applet moves into sight on the Web browser to
allow the applet to start up its normal operations.
stop( ) Called every time the applet moves out of sight on the Web browser to
allow the applet to shut off expensive operations.
destroy( ) Called when the applet is being unloaded from the page to perform final
release of resources when the applet is no longer used.
paint() Called each time the applets output needs to be redrawn.
Running an applet
1. Compile the applet code using javac
2. Use the java tool – appletviewer to view the applet (embed the APPLET tag in
comments in the code)
3. Use the APPLET tag in an HTML page and load the applet in a browser
Using appletviewer:
1. Write the HTML APPLET tag in comments in the source file.
2. Compile the applet source code using javac.
3. Use appletviewer ClassName.class to view the applet.
Using browser:
1. Create an HTML file containing the APPLET tag.
2. Compile the applet source code using javac.
3. In the web browser, open the HTML file.
The PARAM tag allows us to pass information to an applet when it starts running. A
parameter is a NAME – VALUE pair. Every parameter is identified by a name and it has a
value.
Example:
<APPLET NAME = "MyApplet.class" WIDTH = 100 HEIGHT = 100>
<PARAM NAME = "ImageSource" VALUE = "project/images/">
<PARAM NAME = "BackgroundColor" VALUE = "0xc0c0c0">
<PARAM NAME = "FontColor" VALUE = "Red">
</APPLET>
The Applet can retrieve information about the parameters using the getParameter() method.
String getParameter(String parameterName);
Example:
String dirName = getParameter(“ImageSource”);
Color c = new Color( Integer.parseInt(getParameter(“BackgroundColor”)));
Self Activity
Sample program 1: Program to demonstrate Button and text field
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class JButtonDemo extends JFrame implements ActionListener
{
JTextField jtf;
JButton jb;
public JButtonDemo()
{
setLayout(new FlowLayout());
jtf = new JTextField(15);
add (jtf);
jb = new JButton (“Click Me”);
jb.addActionListener (this);
add(jb);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
jtf.setText (ae.getActionCommand());
}
public static void main(String[] args)
{
new JButtonDemo();
}
}
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseMoved(MouseEvent me)
{
l.setText("Mouse moved : X = "+ me.getX() + "Y = " +
me.getY());
}
});
setSize(200,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new EventTest();
}
}
Sample program 5 : Program to display a message in an applet
import java.awt.*;
import java.applet.*;
/* <applet code="MyApplet.class" width=200 height=100>
</applet>
*/
Page 67 of 70
import java.awt.*;
import javax.swing.* ;
import java.applet.*;
/* <applet code="MyApplet.class" width=200 height=100>
</applet>
*/
public class MyApplet extends Applet
{
JPanel p;
JTextField t;
JButton b;
public void init()
{
p = new JPanel();
p.setLayout(new FlowLayout());
t = new JTextField(20);
b = new JButton("Click");
p.add(t);
p.add(b);
add(p);
}
}
Save this as MyApplet.java Compile the file. Execute it using command – appletviewer
MyApplet.class.
Page 68 of 70
Lab Assignments
Set A
a) Write a java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +, -, *, % operations. Add a text field to display the
result.
Simple Calculator
1 2 3 +
4 5 6 -
7 8 9 *
0 . = /
Set B
a) Create the following GUI screen using appropriate layout managers. Accept the name,
class , hobbies of the user and apply the changes and display the selected options in a
text box.
Arial
b) Write a Java program to design a screen using Awt that will take a user name and
password. If the user name and password are not same, raise an Exception with
appropriate message. User can have 3 login chances only. Use clear button to clear
the TextFields.
Page 69 of 70
Set C
a) Write a java program to create the following GUI for user registration form
Co-WIN Registration
AdharCard No. :
Birth Year :
Mobile No. :
Select Hospital :
Submit
a) Write Java program to design three text boxes and two buttons using swing . Enter
different strings in first and second textbox. On clicking the First command button,
concatenation of two strings should be displayed in third text box and on clicking
second command button , reverse of string should display in third text box.
b) Create an Applet which displays a message in the center of the screen. The message
indicates the events taking place on the applet window. Handle events like mouse
click, mouse moved, mouse dragged, mouse pressed, and key pressed. The message
should update each time an event occurs. The message should give details of the event
such as which mouse button was pressed, which key is pressed etc. (Hint: Use
Page 70 of 70
c) Write a java program to create the following GUI for user registration form. Perform
the following validations: i. Password should be minimum 6 characters containing
atleast one uppercase letter, one digit and one symbol. ii. Confirm password and
password fields should match. iii. The Captcha should generate two random 2 digit
numbers and accept the sum from the user. If above conditions are met, display
“Registration Successful” otherwise “Registration Failed” after the user clicks the
Submit button.
d) Write a menu driven program to perform the following operations on a set of integers.
The Load operation should generate 50 random integers (2 digits) and display the
numbers on the screen. The save operation should save the numbers to a file
“numbers.txt”. The Compute menu provides various operations and the result is
displayed in a message box. The Search operation accepts a number from the user in
an input dialog and displays the search result in a message dialog. The sort operation
sorts the numbers and displays the sorted data on the screen.
Numbers :
Assignment Evaluation
Practical In-charge
PROJECT DESIGN
MEMBER 1 :_______________________________________
MEMBER 2 :_______________________________________
MEMBER 3 :_______________________________________
Nowrosjee Wadia College
T.Y.B.Sc (Computer Science) Project
Academic Year 2024-2025
Practical In-Charge :
Nowrosjee Wadia College
T.Y.B.Sc (Computer Science) Project
Academic Year 2024-2025
Practical In-Charge :
Nowrosjee Wadia College
T.Y.B.Sc (Computer Science) Project
Academic Year 2024-2025
Practical In-Charge :
Nowrosjee Wadia College
T.Y.B.Sc (Computer Science) Project
Academic Year 2024-2025
Practical In-Charge :
Nowrosjee Wadia College
T.Y.B.Sc (Computer Science) Project
Academic Year 2024-2025
Practical In-Charge :