Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 62

ASSIGNMENT 01-Java Tools and IDE, Simple Java Programs

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.

Ans Command : javap java.lang.Object

Output:

javap java.lang.Object
Compiled from "Object.java"

public class java.lang.Object {

public java.lang.Object();

public final native java.lang.Class<?> getClass();

public native int hashCode();

public boolean equals(java.lang.Object);

protected native java.lang.Object clone() throws


java.lang.CloneNotSupportedException;

public java.lang.String toString();

public final native void notify();

public final native void notifyAll();

public final void wait() throws java.lang.InterruptedException;

public final native void wait(long) throws


java.lang.InterruptedException;

public final void wait(long, int) throws


java.lang.InterruptedException;

protected void finalize() throws java.lang.Throwable;

static {};

Command : javap java.lang.String


Output:

Compiled from "String.java"

public final class java.lang.String implements


java.io.Serializable,

java.lang.Comparable<java.lang.String>, java.lang.CharSequence {

static final boolean COMPACT_STRINGS;

public static final java.util.Comparator<java.lang.String>


CASE_INSENSITIVE_ORDER;

static final byte LATIN1;

static final byte UTF16;

public java.lang.String();

public java.lang.String(java.lang.String);

public java.lang.String(char[]);

public java.lang.String(char[], int, int);

public java.lang.String(int[], int, int);

public java.lang.String(byte[], int, int, int);

public java.lang.String(byte[], int);

public java.lang.String(byte[], int, int, java.lang.String)


throws

java.io.UnsupportedEncodingException;

public java.lang.String(byte[], int, int,


java.nio.charset.Charset);

public java.lang.String(byte[], java.lang.String) throws


java.io.UnsupportedEncodingException;

public java.lang.String(byte[], java.nio.charset.Charset);

public java.lang.String(byte[], int, int);


public java.lang.String(byte[]);

public java.lang.String(java.lang.StringBuffer);

public java.lang.String(java.lang.StringBuilder);

public int length();

public boolean isEmpty();

public char charAt(int);

public int codePointAt(int);

public int codePointBefore(int);

public int codePointCount(int, int);

public int offsetByCodePoints(int, int);

public void getChars(int, int, char[], int);

public void getBytes(int, int, byte[], int);

public byte[] getBytes(java.lang.String) throws


java.io.UnsupportedEncodingException;

public byte[] getBytes(java.nio.charset.Charset);

public byte[] getBytes();

public boolean equals(java.lang.Object);

public boolean contentEquals(java.lang.StringBuffer);

public boolean contentEquals(java.lang.CharSequence);

public boolean equalsIgnoreCase(java.lang.String);

public int compareTo(java.lang.String);

public int compareToIgnoreCase(java.lang.String);

public boolean regionMatches(int, java.lang.String, int, int);

public boolean regionMatches(boolean, int, java.lang.String, int,


int);
public boolean startsWith(java.lang.String, int);

public boolean startsWith(java.lang.String);

public boolean endsWith(java.lang.String);

public int hashCode();

public int indexOf(int);

public int indexOf(int, int);

public int lastIndexOf(int);

public int lastIndexOf(int, int);

public int indexOf(java.lang.String);

public int indexOf(java.lang.String, int);

static int indexOf(byte[], byte, int, java.lang.String, int);

public int lastIndexOf(java.lang.String);

public int lastIndexOf(java.lang.String, int);

static int lastIndexOf(byte[], byte, int, java.lang.String, int);

public java.lang.String substring(int);

public java.lang.String substring(int, int);

public java.lang.CharSequence subSequence(int, int);

public java.lang.String concat(java.lang.String);

public java.lang.String replace(char, char);

public boolean matches(java.lang.String);

public boolean contains(java.lang.CharSequence);

public java.lang.String replaceFirst(java.lang.String,


java.lang.String);

public java.lang.String replaceAll(java.lang.String,


java.lang.String);
public java.lang.String replace(java.lang.CharSequence,
java.lang.CharSequence);

public java.lang.String[] split(java.lang.String, int);

public java.lang.String[] split(java.lang.String);

public static java.lang.String join(java.lang.CharSequence,


java.lang.CharSequence...);

public static java.lang.String join(java.lang.CharSequence,


java.lang.Iterable<? extends

java.lang.CharSequence>);

public java.lang.String toLowerCase(java.util.Locale);

public java.lang.String toLowerCase();

public java.lang.String toUpperCase(java.util.Locale);

public java.lang.String toUpperCase();

public java.lang.String trim();

public java.lang.String strip();

public java.lang.String stripLeading();

public java.lang.String stripTrailing();

public boolean isBlank();

public java.util.stream.Stream<java.lang.String> lines();

public java.lang.String toString();

public java.util.stream.IntStream chars();

public java.util.stream.IntStream codePoints();

public char[] toCharArray();

public static java.lang.String format(java.lang.String,


java.lang.Object...);
public static java.lang.String format(java.util.Locale,
java.lang.String, java.lang.Object...);

public static java.lang.String valueOf(java.lang.Object);

public static java.lang.String valueOf(char[]);

public static java.lang.String valueOf(char[], int, int);

public static java.lang.String copyValueOf(char[], int, int);

public static java.lang.String copyValueOf(char[]);

public static java.lang.String valueOf(boolean);

public static java.lang.String valueOf(char);

public static java.lang.String valueOf(int);

public static java.lang.String valueOf(long);

public static java.lang.String valueOf(float);

public static java.lang.String valueOf(double);

public native java.lang.String intern();

public java.lang.String repeat(int);

void getBytes(byte[], int, byte);

java.lang.String(char[], int, int, java.lang.Void);

java.lang.String(java.lang.AbstractStringBuilder,
java.lang.Void);

java.lang.String(byte[], byte);

byte coder();

byte[] value();

static void checkIndex(int, int);

static void checkOffset(int, int);

static void checkBoundsOffCount(int, int, int);

static void checkBoundsBeginEnd(int, int, int);


static java.lang.String valueOfCodePoint(int);

public int compareTo(java.lang.Object);

static {};

Command :$ javap java.util.Scanner

Compiled from "Scanner.java"

public final class java.util.Scanner implements


java.util.Iterator<java.lang.String>,

java.io.Closeable {

int modCount;

static final boolean $assertionsDisabled;

public java.util.Scanner(java.lang.Readable);

public java.util.Scanner(java.io.InputStream);

public java.util.Scanner(java.io.InputStream, java.lang.String);

public java.util.Scanner(java.io.InputStream,
java.nio.charset.Charset);

public java.util.Scanner(java.io.File) throws


java.io.FileNotFoundException;

public java.util.Scanner(java.io.File, java.lang.String) throws


java.io.FileNotFoundException;

public java.util.Scanner(java.io.File, java.nio.charset.Charset)


throws java.io.IOException;

public java.util.Scanner(java.nio.file.Path) throws


java.io.IOException;

public java.util.Scanner(java.nio.file.Path, java.lang.String)


throws java.io.IOException;
public java.util.Scanner(java.nio.file.Path,
java.nio.charset.Charset) throws java.io.IOException;

public java.util.Scanner(java.lang.String);

public java.util.Scanner(java.nio.channels.ReadableByteChannel);

public java.util.Scanner(java.nio.channels.ReadableByteChannel,
java.lang.String);

public java.util.Scanner(java.nio.channels.ReadableByteChannel,
java.nio.charset.Charset);

public void close();

public java.io.IOException ioException();

public java.util.regex.Pattern delimiter();

public java.util.Scanner useDelimiter(java.util.regex.Pattern);

public java.util.Scanner useDelimiter(java.lang.String);

public java.util.Locale locale();

public java.util.Scanner useLocale(java.util.Locale);

public int radix();

public java.util.Scanner useRadix(int);

public java.util.regex.MatchResult match();

public java.lang.String toString();

public boolean hasNext();

public java.lang.String next();

public void remove();

public boolean hasNext(java.lang.String);

public java.lang.String next(java.lang.String);

public boolean hasNext(java.util.regex.Pattern);

public java.lang.String next(java.util.regex.Pattern);


public boolean hasNextLine();

public java.lang.String nextLine();

public java.lang.String findInLine(java.lang.String);

public java.lang.String findInLine(java.util.regex.Pattern);

public java.lang.String findWithinHorizon(java.lang.String, int);

public java.lang.String
findWithinHorizon(java.util.regex.Pattern, int);

public java.util.Scanner skip(java.util.regex.Pattern);

public java.util.Scanner skip(java.lang.String);

public boolean hasNextBoolean();

public boolean nextBoolean();

public boolean hasNextByte();

public boolean hasNextByte(int);

public byte nextByte();

public byte nextByte(int);

public boolean hasNextShort();

public boolean hasNextShort(int);

public short nextShort();

public short nextShort(int);

public boolean hasNextInt();

public boolean hasNextInt(int);

public int nextInt();

public int nextInt(int);

public boolean hasNextLong();


public boolean hasNextLong(int);

public long nextLong();

public long nextLong(int);

public boolean hasNextFloat();

public float nextFloat();

public boolean hasNextDouble();

public double nextDouble();

public boolean hasNextBigInteger();

public boolean hasNextBigInteger(int);

public java.math.BigInteger nextBigInteger();

public java.math.BigInteger nextBigInteger(int);

public boolean hasNextBigDecimal();

public java.math.BigDecimal nextBigDecimal();

public java.util.Scanner reset();

public java.util.stream.Stream<java.lang.String> tokens();

public java.util.stream.Stream<java.util.regex.MatchResult>
findAll(java.util.regex.Pattern);

public java.util.stream.Stream<java.util.regex.MatchResult>
findAll(java.lang.String);

public java.lang.Object next();

static {};

COMMAND : javap -c Myclass

Output:

Compiled from "Myclass.java"


public class Myclass {

int num;

public Myclass();

Code:

0: aload_0

1: invokespecial #1 // Method java/lang/Object."<init>":()V

4: aload_0

5: iconst_0

6: putfield #2 // Field num:I

9: return

public Myclass(int);

Code:

0: aload_0

1: invokespecial #1 // Method java/lang/Object."<init>":()V

4: aload_0

5: iload_1

6: putfield #2 // Field num:I

9: return

public static void main(java.lang.String[]);

Code:

0: new #3 // class Myclass

3: dup

4: invokespecial #4 // Method "<init>":()V

7: astore_1

8: aload_0
9: arraylength

10: ifle 52

13: aload_0

14: iconst_0

15: aaload

16: invokestatic #5 // Method


java/lang/Integer.parseInt:(Ljava/lang/String;)I

19: istore_2

20: new #3 // class Myclass

23: dup

24: iload_2

25: invokespecial #6 // Method "<init>":(I)V

28: astore_3

29: getstatic #7 // Field


java/lang/System.out:Ljava/io/PrintStream;

32: aload_1

33: getfield #2 // Field num:I

36: invokevirtual #8 // Method java/io/PrintStream.println:(I)V

39: getstatic #7 // Field


java/lang/System.out:Ljava/io/PrintStream;

42: aload_3

43: getfield #2 // Field num:I

46: invokevirtual #8 // Method java/io/PrintStream.println:(I)V

49: goto 60
52: getstatic #7 // Field
java/lang/System.out:Ljava/io/PrintStream;

55: ldc #9 // String Insufficient argument

57: invokevirtual #10 // Method java/io/PrintStream.println:


(Ljava/lang/String;)V

60: return

b) Write a program to calculate perimeter and area of rectangle. (hint : area = length * breadth ,
perimeter=2*(length+breadth))

ans public class Main


{
public static void main (String args[])
{ float a ,b, c, d, perimeter,area;
a=c= 5;
b=d=4;
perimeter = 2*(a+b);
area = a*b;
System.out.println("Perimeter of Rectangle is: "+perimeter);
System.out.println("Area of Rectangle is: "+area);
}}

output : Perimeter of Rectangle is: 18.0


Area of Rectangle is: 20.0

c) Write a menu driven program to perform the following operations i. Calculate the volume of
cylinder. (hint : Volume: π × r² × h) ii. Find the factorial of given number. iii. Check the number is
Armstrong or not. iv. Exit

ans import java.util.*;


class menudrive
{
public static void main(String args[])
{
Scanner s= new Scanner(System.in);
System.out.println("\n1.Calculate the volume of cylinder");
System.out.println("2.Check the number is Armstrong or not.");
System.out.println("3.Find Factorial");
System.out.println("4.Exit")
System.out.print("\nEnter your choice :");
int choice=s.nextInt();
switch(choice)
{
case 1:
System.out.println("Enter the radius:");
double r=s.nextDouble();
System.out.println("Enter the height:");
double h=s.nextDouble();
double volume=((22*r*r*h)/7);
System.out.println("volume of Cylinder is: " +volume);
break;
case 2:
System.out.println("Enter number :");
int number=s.nextInt();
int originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)

System.out.println(number + " is an Armstrong number.");


else
System.out.println(number + " is not an Armstrong number.");
break;
case 3:
System.out.println("Enter number :");
int num=s.nextInt();
long factorial = 1;
for(int i = 1; i <= num; ++i)
{
// factorial = factorial * i;
factorial *= i;
}
System.out.printf("Factorial of %d = %d", num, factorial);
break;
case 4:
return 0;
default :System.out.println("Invalid input");
}

Output:

1.Calculate the volume of cylinder


2.Check the number is Armstrong or not.
3.Find Factorial
4.Exit
Enter your choice :1
Enter the radius:
5
Enter the height:
8
volume of Cylinder is: 628.5714285714286
-----------------------------------------------------------------
-----------------------------------------------------
1.Calculate the volume of cylinder
2.Check the number is Armstrong or not.
3.Find Factorial
4.Exit
Enter your choice :2
Enter number :
369
369 is not an Armstrong number.
-----------------------------------------------------------------
------------------------------------------------------
1.Calculate the volume of cylinder

2.Check the number is Armstrong or not.


3.Find Factorial
4.Exit
Enter your choice :3
Enter number :
5
Factorial of 5 = 120

d) Write a program to accept the array element and display in reverse order.

Ans import java.util.*;

public class ReverseArray


{
public static void main(String[] args)
{
//Initialize array
int [] arr = new int [5];
Scanner sc=new Scanner(String[] args);
System.out.println("Enter five numbers : ");
for (int i = 0; i < arr.length; i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = arr.length-1; i >= 0; i--)
{
System.out.print(arr[i] + " ");
}
}
}

Set B

a) Write a java program to display the system date and time in various formats shown below:
Current date is : 31/08/2021
Current date is : 08-31-2021
Current date is : Tuesday August 31 2021
Current date and time is : Fri August 31 15:25:59 IST 2021
Current date and time is : 31/08/21 15:25:59 PM +0530
Current time is : 15:25:59
Current week of year is : 35
Current week of month : 5
Current day of the year is : 243
Note: Use java.util.Date and java.text.SimpleDateFormat class

Ans Program:

import java.text.ParseException;  
import java.text.SimpleDateFormat;  
import java.util.Date;  
import java.util.Locale;  
public class NewClass {  
public static void main(String[] args) {  
    Date date = new Date();  
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");  
    String strDate = formatter.format(date);  
    System.out.println("Current date is: "+strDate);  
 
    formatter = new SimpleDateFormat("MM-dd-yyyy");  
    strDate = formatter.format(date);  
    System.out.println("Current date is: "+strDate);  
   
    formatter = new SimpleDateFormat("EEEEEE MMMM dd yyyy");  
    strDate = formatter.format(date);  
    System.out.println("Current date is: "+strDate);  
   
    formatter = new SimpleDateFormat("E MMMM dd HH:mm:ss z yyyy");  
    strDate = formatter.format(date);  
    System.out.println("Current date and time is: "+strDate);  
   
    formatter = new SimpleDateFormat("dd/MM/yy HH:mm:ss a Z");  
    strDate = formatter.format(date);  
    System.out.println("Current date and time is: "+strDate);  
   
    formatter = new SimpleDateFormat("hh:mm:ss");  
    strDate = formatter.format(date);  
    System.out.println("Current time is: "+strDate);  
 
    formatter = new SimpleDateFormat("w");  
    strDate = formatter.format(date);  
    System.out.println("Current week of year is: "+strDate);  
 
    formatter = new SimpleDateFormat("W");  
    strDate = formatter.format(date);  
    System.out.println("Current week of the month is: "+strDate);  
 
    formatter = new SimpleDateFormat("D");  
    strDate = formatter.format(date);  
    System.out.println("Current day of the year: "+strDate);  
}  
}  

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.

Ans public class MyNumber {

private int x;
public MyNumber(){
x=0;
}
public MyNumber(int x){
this.x=x;
}
public boolean isNegative(){

if(x&lt;0)
return true;
else return false;
}
public boolean isPositive(){
if(x&gt;0)
return true;
else return false;
}
public boolean isZero(){
if(x==0)
return true;
else return false;
}
public boolean isOdd(){
if(x%2!=0)
return true;
else return false;
}
public boolean isEven(){
if(x%2==0)
return true;
else return false;
}
public static void main(String [] args) throws ArrayIndexOutOfBoundsException
{
int x=Integer.parseInt(args[0]);
MyNumber m=new MyNumber(x);
if(m.isNegative())
System.out.println(&quot;Number is Negative&quot;);
if(m.isPositive())
System.out.println(&quot;Number is Positive&quot;);
if(m.isEven())
System.out.println(&quot;Number is Even&quot;);
if(m.isOdd())
System.out.println(&quot;Number is Odd&quot;);
if(m.isZero())
System.out.println(&quot;Number is Zero&quot;);
}
}

c) Write a menu driven program to perform the following operations on multidimensional array ie
matrix : i. Addition ii. Multiplication iii. Transpose of any matrix. iv. Exit

Ans import java.util.Arrays;

import java.util.Scanner;

public class Matrix {

  // main method
  public static void main(String[] args) {

    // Scanner class object


    Scanner scan = new Scanner(System.in);

    // declare two matrix


    int a[][] = { { 5, 6, 7 }, { 8, 9, 10 }, { 3, 1, 2 } };
    int b[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

    // create third matrix


    int c[][] = new int[3][3];
// display both matrix
    System.out.println("A = " + Arrays.deepToString(a));
    System.out.println("B = " + Arrays.deepToString(b));

    // variable to take choice


    int choice;

    // menu-driven
    do {
      // menu to choose the operation
      System.out.println("\nChoose the matrix operation,");
      System.out.println("----------------------------");
      System.out.println("1. Addition");
      System.out.println("2. Multiplication");
      System.out.println("3. Transpose");
      System.out.println("4. Exit");
      System.out.println("----------------------------");
      System.out.print("Enter your choice: ");
      choice = scan.nextInt();
      switch (choice) {
      case 1:
        c = add(a, b);
        System.out.println("Sum of matrix: ");
        System.out.println(Arrays.deepToString(c));
        break;
      case 2:
        c = multiply(a, b);
        System.out.println("Multiplication of matrix: ");
        System.out.println(Arrays.deepToString(c));
        break;
      case 3:
        System.out.println("Transpose of the first matrix: ");
        c = transpose(a);
        System.out.println(Arrays.deepToString(c));
        System.out.println("Transpose of the second matrix: ");
        c = transpose(b);
        System.out.println(Arrays.deepToString(c));
        break;
      case 4:
        System.out.println("Thank You.");
        return;
      default:
        System.out.println("Invalid input.");
        System.out.println("Please enter the correct input.");
      }
    } while (true);
  }

  // method to perform matrix addition and


  // return resultant matrix
  public static int[][] add(int[][] a, int[][] b) {

    // calculate row and column size of anyone matrix


    int row = a.length;
    int column = a[0].length;

    // declare a matrix to store resultant value


    int sum[][] = new int[row][column];
    // calculate sum of two matrices
    for (int i = 0; i < row; i++) {
      for (int j = 0; j < column; j++) {
        sum[i][j] = a[i][j] + b[i][j];
      }
    }

    // return resultant matrix


    return sum;
  }
  // method to perform matrix multiplication and
  // return resultant matrix
  // passed matrices can be square or non-square matrix
  public static int[][] multiply(int[][] a, int[][] b) {

    // find row size of first matrix


    int row = a.length;
    // find column size of second matrix
    int column = b[0].length;

    // declare new matrix to store result


    int product[][] = new int[row][column];

    // find product of both matrices


    // outer loop up to row of A
    for (int i = 0; i < row; i++) {
      // inner-1 loop utp0 column of B
      for (int j = 0; j < column; j++) {
        // assign 0 to the current element
        product[i][j] = 0;
        // inner-2 loop up to A[0].length
        for (int k = 0; k < a[0].length; k++) {
          product[i][j] += a[i][k] * b[k][j];
        }
      }
    }
    return product;
  }

  // method to find transpose of a matrix


  public static int[][] transpose(int[][] a) {

    // calculate row and column size


    int row = a.length;
    int column = a[0].length;

    // declare a matrix to store resultant


    int temp[][] = new int[row][column];

    // calculate transpose of matrix


    // outer loop for row
    for (int i = 0; i < row; i++) {
      // inner loop for column
      for (int j = 0; j < column; j++) {
        // formula
        temp[i][j] = a[j][i];
      }
    }

    // return resultant matrix


    return temp;
  }

}
Output:-
A = [[5, 6, 7], [8, 9, 10], [3, 1, 2]]
B = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Choose the matrix operation,


—————————-
1. Addition
2. Multiplication
3. Transpose
4. Exit

—————————-
Enter your choice: 1
Sum of matrix:
[[6, 8, 10], [12, 14, 16], [10, 9, 11]]
Choose the matrix operation,
—————————-
1. Addition
2. Multiplication
3. Transpose
4. Exit

—————————-
Enter your choice: 2
Multiplication of matrix:
[[78, 96, 114], [114, 141, 168], [21, 27, 33]]
Choose the matrix operation,
—————————-
1. Addition
2. Multiplication
3. Transpose
4. Exit

—————————-
Enter your choice: 3
Transpose of the first matrix:
[[5, 8, 3], [6, 9, 1], [7, 10, 2]]
Transpose of the second matrix:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Choose the matrix operation,
—————————-
1. Addition
2. Multiplication
3. Transpose
4. Exit

—————————-
Enter your choice: 5
Invalid input.
Please enter the correct input.
Choose the matrix operation,
—————————-
1. Addition
2. Multiplication
3. Transpose
4. Exit

—————————-
Enter your choice: 4
Thank You.
ASSIGNMENT NO -02 (ARRAY OF OBJECTS AND PACKAGES)

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.

Ans import java.util.Scanner;


public class Employee {
int id;
String name;
String deptname;
float salary;
static int numberofobjects=0;
Employee(){
id=0;
name="";
deptname="";
salary=0;
}
Employee(int id,String name,String deptname,float salary ){
this.id=id;
this.name=name;
this.deptname=deptname;
this.salary=salary;
numberofobjects++;
}
public void display(){
System.out.println("Employee Id :"+id);
System.out.println("Employee name: "+name);
System.out.println("Employee Department: "+deptname);
System.out.println("Employee Salary :"+salary);
}
public static void main(String[] args){
int n=0;
Scanner sc=new Scanner(System.in);
System.out.print("How many employees you want to enter :");
n=sc.nextInt();
Employee[] ob=new Employee[n];
for(int i=0;i<n;i++){
sc= new Scanner(System.in);
System.out.println("Enter Id of employee "+(i+1)+" :");
int id=sc.nextInt();
System.out.println("Enter Name of employee "+(i+1)+" :");
sc.nextLine();
String name= sc.nextLine();
System.out.println("Enter dept name of employee "+(i+1)+" :");
String deptname=sc.nextLine();
System.out.println("Enter salary of employee "+(i+1)+" :");
float salary = sc.nextFloat();
ob[i]=new Employee(id,name,deptname,salary);
System.out.println("\nNumber of Objects : "+numberofobjects);

}
for(int i=0;i<n;i++)
{
ob[i].display();
}
}
}

Output:

How many employees you want to enter :2


Enter Id of employee 1 :
1
Enter Name of employee 1 :
rohit
Enter dept name of employee 1 :
abc
Enter salary of employee 1 :
1000000
Number of Objects : 1
Enter Id of employee 2 :
2
Enter Name of employee 2 :
bairwa
Enter dept name of employee 2 :
90000000
Enter salary of employee 2 :
78888888
Number of Objects : 2
Employee Id :1
Employee name: rohit
Employee Department: abc
Employee Salary :1000000.0
Employee Id :2
Employee name: bairwa
Employee Department: 90000000
Employee Salary :7.8888888E7
b) Define Student class(roll_no, name, percentage) to create n objects of the Lab Assignments
Student class. Accept details from the user for each object. Define a static method
“sortStudent” which sorts the array on the basis of percentage.

Ans ANS import java.io.*;

class Student {
int rollNumber;
String name;
float per;
static int count=0;
public Student(){
rollNumber=0;
name=null;
per=0.0f;
}
public Student(int rollNumber,String name,float per){
this.rollNumber=rollNumber;
this.name=name;
this.per=per;
count++;
}
public static void count(){
System.out.println(&quot;Object &quot;+(count)+&quot; Created&quot;);
}
public void display(){
System.out.println(&quot;Roll Number: &quot;+rollNumber);
System.out.println(&quot;Name: &quot;+name);
System.out.println(&quot;Percentage: &quot;+per);
System.out.println(&quot;------------------------------&quot;);
}
}
public class StudentMain {
public static void main(String [] args)throws IOException{
Student s1=new Student(1,&quot;Rusher&quot;,56.76f);
Student.count();
Student s2=new Student(2,&quot;Naren&quot;,89.67f);
Student.count();
Student s3=new Student(3,&quot;Adi&quot;,99.54f);
Student.count();
s1.display();
s2.display();
s3.display();
}
}

c) Write a java program to accept 5 numbers using command line arguments sort and display
them.
Ans import java.io.*;
public class sort
{
public static void main(String[] args) throws IOException
{
BufferedReader br= new BufferedReader(new
InputStreamReader(System.in));
int [] arr=new int[5];
for(int i=0;i<5;i++) //Array Initialization
{
arr[i]=Integer.parseInt(br.readLine());
}
int temp = 0; //Temporary variable to store the element
for (int i = 0; i < 5; i++) //Holds each Array element
{
for (int j = i+1; j < 5; j++) //compares with remaining Array
elements
{
if(arr[i] > arr[j]) //Compare and swap
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in ascending order:
");
for (int i = 0; i < 5; i++)
{
System.out.print(arr[i] + " ");
}

}
}

Output:

java sort 4 6 1 7 8
Elements of array sorted in ascending order:
1 4 6 7 8

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.
Ans import java.util.*;
class a2a4
{
String fname,mname,lname;
int len;
void accept()
{
System.out.println("Enter First Name :");
Scanner s=new Scanner(System.in);
fname=s.next();
System.out.println("Enter Middle Name :");
mname=s.next();
System.out.println("Enter Last Name :");
lname=s.next();
len=mname.length();
String f=mname.substring(0,1);
String l=mname.substring(1,len);
f=f.toUpperCase();
mname=f+l;
}
void display()
{
System.out.println("Last Name :"+lname);
System.out.println("First Name :"+fname);
System.out.println("Middle Name :"+mname);
}
public static void main(String a[])
{
a2a4 p=new a2a4();
p.accept();
p.display();
}
}

Output:

Enter First Name :


rohit
Enter Middle Name :

rajesh
Enter Last Name :
bairwa
Last Name :bairwa
First Name :rohit
Middle Name :Rajesh

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.

Ans import TY.*;


import java.io.*;
class StudentInfo{
int rollno;
String name,grade;
public float gt,tyt,syt;
public float per;
public void get() throws IOException{
System.out.println("Enter roll number and name of the student:
");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
rollno=Integer.parseInt(br.readLine());
name=br.readLine();
}
}
public class StudentMarks {
public static void main(String[] args) throws IOException{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter the number of students:");
int n=Integer.parseInt(br.readLine());
SYMarks sy[]=new SYMarks[n];
TYMarks ty[]=new TYMarks[n];
StudentInfo si[]=new StudentInfo[n];
for(int i=0;i<n;i++)
{
si[i]=new StudentInfo();
sy[i]=new SYMarks();
ty[i]=new TYMarks();
si[i].get();
sy[i].get();
ty[i].get();
si[i].syt=sy[i].ct+sy[i].et+sy[i].mt;
si[i].tyt=ty[i].pm+ty[i].tm;
si[i].gt=si[i].syt+si[i].tyt;
si[i].per=(si[i].gt/1200)*100;
if(si[i].per>=70) si[i].grade="A";
else if(si[i].per>=60) si[i].grade="B";
else if(si[i].per>=50) si[i].grade="C";
else if(si[i].per>=40) si[i].grade="Pass";
else si[i].grade="Fail";

}
System.out.println("Roll No\tName\tSyTotal\tTyTotal\tGrandTotal\
tPercentage\tGrade");
for(int i=0;i<n;i++)
{
System.out.println(si[i].rollno+"\t"+si[i].name+"\t"+si[i].syt+"\
t"+si[i].tyt+"\t"+si[i].gt+"\t\
t"+si[i].per+"\t\t"+si[i].grade);
}
}
}

SYMarks.java

package TY;
import java.io.BufferedReader;
import java.io.*;
public class SYMarks {
public int ct,mt,et;
public void get() throws IOException{
System.out.println("Enter marks of students for computer, maths
and electronics subject out of 200
");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
ct=Integer.parseInt(br.readLine());
mt=Integer.parseInt(br.readLine());
et=Integer.parseInt(br.readLine());
}

TYMarks.java

package TY;
import java.io.*;
public class TYMarks {
public int tm,pm;
public void get() throws IOException{
System.out.println("Enter the marks of the theory out of 400 and
practicals out of 200: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
tm=Integer.parseInt(br.readLine());
pm=Integer.parseInt(br.readLine());
}
}

Output :

Enter the number of students:


1

Enter roll number and name of the student:


1
Rohit
Enter marks of students for computer, maths and electronics
subject out of 200
200
200
200
Enter the marks of the theory out of 400 and practicals out of
200:
399
199
Roll No Name SyTotal TyTotal GrandTotal Percentage Grade
1 Rohit 600.0 598.0 1198.0 99.833336 A

b) Define a class CricketPlayer (name,no_of_innings,no_of_times_notout, totatruns, bat_avg).


Create an array of n player objects .Calculate the batting average for each player using static
method avg(). Define a static sort method which sorts the array on the basis of average. Display
the player details in sorted order.

ANS import java.io.*;

class Cricket {
String name;
int inning, tofnotout, totalruns;
float batavg;
public Cricket(){
name=null;
inning=0;
tofnotout=0;
totalruns=0;
batavg=0;
}
public void get() throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(&quot;Enter the name, no of innings, no of times not out,
total runs: &quot;);
name=br.readLine();
inning=Integer.parseInt(br.readLine());
tofnotout=Integer.parseInt(br.readLine());
totalruns=Integer.parseInt(br.readLine());
}
public void put(){
System.out.println(&quot;Name=&quot;+name);
System.out.println(&quot;no of innings=&quot;+inning);
System.out.println(&quot;no times notout=&quot;+tofnotout);
System.out.println(&quot;total runs=&quot;+totalruns);
System.out.println(&quot;bat avg=&quot;+batavg);
}
static void avg(int n, Cricket c[]){
try{
for(int i=0;i&lt;n;i++){
c[i].batavg=c[i].totalruns/c[i].inning;
}
}catch(ArithmeticException e){
System.out.println(&quot;Invalid arg&quot;);
}
}
static void sort(int n, Cricket c[]){
String temp1;
int temp2,temp3,temp4;
float temp5;
for(int i=0;i&lt;n;i++){
for(int j=i+1;j&lt;n;j++){
if(c[i].batavg&lt;c[j].batavg){
temp1=c[i].name;

c[i].name=c[j].name;
c[j].name=temp1;
temp2=c[i].inning;
c[i].inning=c[j].inning;
c[j].inning=temp2;
temp3=c[i].tofnotout;
c[i].tofnotout=c[j].tofnotout;
c[j].tofnotout=temp3;
temp4=c[i].totalruns;
c[i].totalruns=c[j].totalruns;
c[j].totalruns=temp4;
temp5=c[i].batavg;
c[i].batavg=c[j].batavg;
c[j].batavg=temp5;
}
}
}
}
}
public class a4sa1 {
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println(&quot;Enter the limit:&quot;);
int n=Integer.parseInt(br.readLine());
Cricket c[]=new Cricket[n];
for(int i=0;i&lt;n;i++){
c[i]=new Cricket();
c[i].get();
}
Cricket.avg(n,c);
Cricket.sort(n, c);
for(int i=0;i&lt;n;i++){
c[i].put();
}
}
}

Assignment 3: Inheritance and Interfaces

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.

ANS import java.io.InputStreamReader;

import java.io.BufferedReader;
import java.io.IOException;
class Continent
{
String con;
InputStreamReader i = new InputStreamReader(System.in);
BufferedReader r = new BufferedReader(i);
void con_input() throws IOException
{
System.out.println(&quot;Enter Continent Name: &quot;);
con = r.readLine();
}
}
class Country extends Continent
{
String cou ;
void cou_input() throws IOException
{
System.out.println(&quot;Enter Country Name: &quot;);
cou = r.readLine();
}
}
class State extends Country
{
String sta;
void sta_input() throws IOException

{
System.out.println(&quot;Enter State Name: &quot;);
sta = r.readLine();
}
}
class Main extends State
{
String pla;
void pla_input()throws IOException
{
System.out.println(&quot;Enter Place Name : &quot;);
pla = r.readLine();

}
}
public class Find{
public static void main(String[] args)throws IOException
{
Main s = new Main();
s.con_input();
s.cou_input();
s.sta_input();
s.pla_input();
System.out.println(&quot;\n\nContinent: &quot;+s.con);
System.out.println(&quot;Country: &quot;+s.cou);
System.out.println(&quot;State: &quot;+s.sta);
System.out.println(&quot;Place :&quot; + s.pla);
}
}

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.

Ans import java.io.IOException;


import java.io.InputStreamReader;
abstract class Staff{
String name,address;
}
class FullTimeStaff extends Staff{
String department;
double salary;
public void accept() throws IOException{
System.out.println("Enter the name, address, department and
salary: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
name=br.readLine();
address=br.readLine();
department=br.readLine();
salary=Double.parseDouble(br.readLine());
}
public void display(){

System.out.println("Name: "+name);
System.out.println("Address: "+address);
System.out.println("Department: "+department);
System.out.println("Salary: "+salary);
System.out.println("----------------------");
}
}
class PartTimeStaff extends Staff{
int hours, rate;
public void accept() throws IOException{
System.out.println("Enter the name, address, No of working hours
and rate per hour: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
name=br.readLine();
address=br.readLine();
hours=Integer.parseInt(br.readLine());
rate=Integer.parseInt(br.readLine());
}
public void display(){
System.out.println("Name: "+name);
System.out.println("Address: "+address);
System.out.println("No of Working Hours: "+hours);
System.out.println("Rate per hour: "+rate);
System.out.println("----------------------");
}
}
public class sb1 {
public static void main(String [] args) throws IOException{
int i;
System.out.println("Select Any One: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("1.Full Time Staff");
System.out.println("2.Part Time Satff");
int ch=Integer.parseInt(br.readLine());
switch(ch){
case 1:
System.out.println("Enter the number of Full Time Staff: ");
int n=Integer.parseInt(br.readLine());
FullTimeStaff [] l=new FullTimeStaff[n];
for(i=0;i<n;i++){
l[i]=new FullTimeStaff();
l[i].accept();
}
for(i=0;i<n;i++){
l[i].display();
}
break;
case 2:
System.out.println("Enter the number of Part Time Staff: ");
int m=Integer.parseInt(br.readLine());
PartTimeStaff [] h=new PartTimeStaff[m];
for(i=0;i<m;i++){
h[i]=new PartTimeStaff();

h[i].accept();
}
for(i=0;i<m;i++){
h[i].display();
}
break;
}
}
}

Output:

Select Any One:


1.Full Time Staff
2.Part Time Satff
1
Enter the number of Full Time Staff:
2
Enter the name, address, department and salary:
Rohit
Pune
AB
19000
Enter the name, address, department and salary:
Karan
Mumbai
BA
18000
Name: Rohit
Address: Pune
Department: AB
Salary: 19000.0
----------------------
Name: Karan
Address: Mumbai
Department: BA
Salary: 18000.0

c) Define an interface “Operation” which has methods area(),volume().Define a constant PI


having a value 3.142.Create a class cylinder which implements this interface (members –
radius, height) Create one object and calculate the area and volume.

d)Write a program to find the cube of given number using function interface.

Ans import java.util.Scanner;

import java.lang.*;

public class threenum1


{
    public static void main(String args[])
    {
        int num;
  double a,b,c;
   
  Scanner sc = new Scanner(System.in);
 
        System.out.print("Enter The Number :\n\n");
        num = sc.nextInt();

  a=Math.pow(num,1);
  b=Math.pow(num,2);
  c=Math.pow(num,3);

  System.out.println("\nOutput Is = " + a + " ,"+ b +" ,"+ c +"\n\n");


 }
}

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.

Ans import java.io.BufferedReader;


import java.io.IOException;
import java.io.InputStreamReader;
abstract class Order{
String id,description;
}
class PurchaseOrder extends Order{
String Customername,Vendorname;
public void accept() throws IOException{
System.out.println("Enter the id,description,names of customers
and vendors: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
id=br.readLine();
description=br.readLine();
Customername=br.readLine();
Vendorname=br.readLine();
}
public void display(){
System.out.println("id: "+id);
System.out.println("Description: "+description);
System.out.println("Customername: "+Customername);
System.out.println("Vendorname: "+Vendorname);
System.out.println("----------------------");
}
}
class SalesOrder extends Order{
String Customername,Vendorname;
public void accept() throws IOException{
System.out.println("Enter the id,description,names of customers
and vendors: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
id=br.readLine();
description=br.readLine();
Customername=br.readLine();
Vendorname=br.readLine();
}
public void display(){
System.out.println("id: "+id);
System.out.println("Description: "+description);
System.out.println("Customername: "+Customername);
System.out.println("Vendorname: "+Vendorname);
System.out.println("----------------------");
}
}
public class Main {
public static void main(String [] args) throws IOException{

int i;
System.out.println("Select Any One: ");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("1.Purchase Order");
System.out.println("2.Sales Order");
int ch=Integer.parseInt(br.readLine());
switch(ch){
case 1:
System.out.println("Enter the number of purchase Orders: ");
int n=Integer.parseInt(br.readLine());
PurchaseOrder [] l=new PurchaseOrder[n];
for(i=0;i<n;i++){
l[i]=new PurchaseOrder();
l[i].accept();
}
for(i=0;i<n;i++){
l[i].display();
System.out.println ("Object is created");
}
break;
case 2:
System.out.println("Enter the number of sales orders: ");
int m=Integer.parseInt(br.readLine());
SalesOrder [] h=new SalesOrder[m];
for(i=0;i<m;i++){
h[i]=new SalesOrder();
h[i].accept();
}
for(i=0;i<m;i++){
h[i].display();
System.out.println(" Object is created ");
}
break;

}
}
}

Output:

Select Any One:


1.Purchase Order
2.Sales Order
1
Enter the number of purchase Orders:
2
Enter the id,description,names of customers and vendors:
1
Soap
Rahul
Gajni
Enter the id,description,names of customers and vendors:
2

Handwash
prince
abhishek
id: 1
Description: Soap
Customername: Rahul
Vendorname: Gajni
----------------------
Object is created
id: 2
Description: Handwash
Customername: prince
Vendorname: abhishek
----------------------
Object is created

b) Write a program to using marker interface create a class product(product_id, product_name,


product_cost, product_quantity) define a default and parameterized constructor. Create
objects of class product and display the contents of each object and Also display the object
count

ANS import java.util.*;

interface ProductMarker
{
}
class Product implements ProductMarker
{
int id;
String name;
int cost;
int quantity;
int count;
Product(){
id=0;
name=" ";
cost=0;
quantity=0;
}
Product(int id, String name, int cost, int quantity){
this.id=id;
this.name=name;
this.cost=cost;
this.quantity=quantity;
this.count++;
}
}
public class Products
{
public static void main(String[] args)
{
int count=0;
Scanner a = new Scanner(System.in);
System.out.println("How many product ?");
int number = a.nextInt();

System.out.println("\n");
Product products[] = new Product[number];
System.out.println("Enter Product data");
for(int k=0; k<number; k++)
{
System.out.println("Product Id ");
int id =a.nextInt();
System.out.println("Product name ");
String name = a.next();
System.out.println("Product cost ");
int cost = a.nextInt();
System.out.println("Product qantity ");
int quantity = a.nextInt();
System.out.println("\n");
products[k] = new Product(id, name, cost, quantity);
count++;
}
//Testing for marker interface
if(products[0] instanceof ProductMarker){
System.out.println("Class is using ProductMarker");
}
System.out.println(" Product details\n");
for(Product product:products)
{
System.out.println("Product Id " + product.id);
System.out.println("Product name " + product.name);
System.out.println("Product cost " + product.cost);
System.out.println("Product qantity " + product.quantity);
System.out.println("\n");
}
System.out.println("Total object is "+count);
}
}
Output:

How many product ?


2

Enter Product data


Product Id
1
Product name
XtraPen
Product cost
5
Product qantity
5

Product Id
2
Product name
XtraPencil
Product cost
2
Product qantity
4

Class is using ProductMarker


Product details
Product Id 1
Product name XtraPen
Product cost 5
Product qantity 5

Product Id 2
Product name XtraPencil
Product cost 2
Product qantity 4

Total object is 2
Assignment 4: Exception Handling and File Handling

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.
Ans import java.util.*;

class Patient
{
String name;
int age;
int oxylevel;
int HRCTreport;
patient(String name, int age, int oxylevel, int HRCTreport)
{
this.name = name;
this.age = age;
this.oxylevel = oxylevel;
this.HRCTreport = HRCTreport;
}
}
public class Main extends Exception
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("How many patient you want insert:");
int number = sc.nextInt();
patient[] ob = new patient[number];
for(int j=0; j<number; j++)
{
System.out.println("Enter Name ");
String name = sc.next();
System.out.println("Enter Age ");
int age = sc.nextInt();
System.out.println("Enter oxygen level");
int oxylevel = sc.nextInt();
System.out.println("Enter HRCT report");
int HRCTreport = sc.nextInt();
ob[j] = new patient(name, age, oxylevel, HRCTreport);
}

for(int j=0; j<number; j++)


{
if(ob[j].oxylevel < 95 && ob[j].HRCTreport > 10)
try
{

throw new NullPointerException("\n");


}
catch(Exception e)
{
System.out.println("Patient is Covid Positive(+) and Need to Hospitalized\
n");

}
else
{
System.out.println("name: "+ob[j].name);
System.out.println("age " + ob[j].age);
System.out.println("oxygen level " +ob[j].oxylevel);
System.out.println("HRCT report " + ob[j].HRCTreport);
System.out.println("\n");
}
}
}
}

Output:

How many patient you want insert:


2
Enter Name
abc
Enter Age
109
Enter oxygen level
70
Enter HRCT report
10
Enter Name
xyz
Enter Age
111
Enter oxygen level
60
Enter HRCT report
9
name: abc
age 109
oxygen level 70
HRCT report 10

name: xyz
age 111
oxygen level 60
HRCT report 9

c) 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).
Ans import java.io.*;

import java.util.*;
class read
{
public static void main(String args[]) throws IOException
{
FileReader f = new FileReader("sample.txt");
Scanner sc = new Scanner(f);
String CH,CH2;
while(sc.hasNext())
{
StringBuilder CH1 = new StringBuilder();
CH = sc.next();
CH2=CH.toUpperCase();
CH1.append(CH2);
CH1.reverse();
System.out.println(CH1);
}
f.close();
}
}

Output OLLEH
DLROW
321

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.
Ans import java.io.*;

import java.util.*;
class copy{
public static void main(String arg[]) throws Exception {
Scanner sc = new Scanner(System.in);
System.out.print("source file name :\n");
String file1 = sc.next();
System.out.print("destination file name :\n");
String file2 = sc.next();
FileReader fin = new FileReader(file1);
FileWriter fout = new FileWriter(file2, true);
int c;
while ((c = fin.read()) != -1) {
fout.write(c);
}
System.out.println("Copy finish...");
fin.close();
fout.close();
}
}

Output :source file name :

bookinfo.txt
destination file name :
info.txt
Copy finish...

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.
Ans import java.util.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Scanner;

class EmailId
{

String domainID,username,password;

EmailId()
{
domainID=”K7″;
username=”K”;
password=”constructc000″;
}

EmailId(String user,String pass,String domID)


{
domainID=domID;
username=user;
password=pass;
}
public static void main(String[] args) {
String user,pass, domID;
int p=-1,up=-1,u=-1,d=-1;

EmailId obj=new EmailId();

Scanner sc= new Scanner(System.in);


System.out.println(“Enter username”);
user=sc.nextLine();
System.out.println(“\nEnter password”);
pass=sc.nextLine();
System.out.println(“\nEnter Domain ID”);
domID=sc.nextLine();
System.out.println(“Enter a date in dd/mm/yyyy format”);
String date = sc.next();

EmailId obj1=new EmailId(user,pass,domID);

if((obj.username).equals(obj1.username))
{
u=1;
if(obj.password.equals(obj1.password))
{
up=1;
}
else
{
p=0;
}
}
else
{
u=0;
}

if(dateValidation(date)==true)
d=1;
else
d=0;

if(d==1)
{
if(u==0)
{

try{
throw new InvalidUsernameException(user);
}

catch (Exception e) {
System.out.println(e) ;
}
}

if (p==0){
{
try{

throw new InvalidPasswordException(pass);


}
catch (Exception e) {
System.out.println(e) ;
}
}
}

if(up==1)
{
System.out.println(“Valid email id”);
}
}
else{
System.out.println(“Not a Valid email id”);
}

public static boolean dateValidation(String date)


{
boolean status = false;

if (checkDate(date)) {
DateFormat dateFormat = new SimpleDateFormat(“dd/MM/yyyy”);
dateFormat.setLenient(false);
try {
dateFormat.parse(date);
status = true;
} catch (Exception e) {
status = false;
}
}
return status;
}

static boolean checkDate(String date) {


String pattern = “(0?[1-9]|[12][0-9]|3[01])\\/(0?[1-9]|1[0-2])\\/([0-9]{4})”;
boolean flag = false;
if (date.matches(pattern)) {
flag = true;
}
return flag;

class InvalidUsernameException extends Exception{


String num1;
InvalidUsernameException(String num2) {
num1=num2;
}
public String toString(){
return (“exception in thread ‘main’ InvalidUsernameException: Username: “+
num1 + ” doesn’t match”) ;
}
}

class InvalidPasswordException extends Exception{


String num1;
InvalidPasswordException(String num2) {
num1=num2;
}
public String toString(){
return (“exception in thread ‘main’ InvalidPasswordException: Username: “+
num1 + ” doesn’t match”) ;
}
}

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
Ans import java .io.*;

class InvalidDateException extends Exception


{
}
class MyDate
{
    int day,mon,yr;
        void accept(int d,int m,int y)
        {
            day=d;
            mon=m;
            yr=y;
        }
        void display()
        {
            System.out.println(&quot;Date is valid : &quot;+day+&quot;/&quot;
+mon+&quot;/&quot;+yr);
        }
}
class DateMain
{
    public static void main(String arg[]) throws Exception
    {
        System.out.println(&quot;Enter Date  :  dd mm yyyy &quot;);
        BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
        int day=Integer.parseInt(br.readLine());
        int mon=Integer.parseInt(br.readLine());
        int yr=Integer.parseInt(br.readLine());
        int flag=0;
        try
            {
                    if(mon&lt;=0 || mon&gt;12)
                        throw  new InvalidDateException();
                    else
                    {
                        if(mon==1 || mon==3 || mon==5 || mon==7 || mon==8 ||
mon==10 || mon==12)
                        {
                            if(day&gt;=1 &amp;&amp; day &lt;=31)      
                                flag=1;
                            else
                                throw  new InvalidDateException();
                        }
                        else if (mon==2)
                        {
                            if(yr%4==0)
                            {
                                if(day&gt;=1 &amp;&amp; day&lt;=29)

                                    flag=1;
                                else throw  new InvalidDateException();
                            }
                            else
                            {
                                if(day&gt;=1 &amp;&amp; day&lt;=28)
                                    flag=1;
                                else throw  new InvalidDateException();
                            }
                        }
                        else                
                        {
                            if(mon==4 || mon == 6 || mon== 9 || mon==11)
                            {
                                if(day&gt;=1 &amp;&amp; day &lt;=30)
                                    flag=1;
                                else throw  new InvalidDateException();
                            }
                        }
                    }
                if(flag== 1)
                {
                    MyDate dt = new MyDate();
                    dt.accept(day,mon,yr);
                    dt.display();
                }
            }
        catch (InvalidDateException mm)
        {
            System.out.println(&quot;Invalid Date&quot;);
        }
       
    }

Assignment 5: GUI Designing, Event Handling

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.

Ans import javax.swing.*;


import java.awt.*;
import java.awt.event.*;
//appletviewer Calculator1.html
public class Calculator1 extends JApplet
{
public void init()
{
CalculatorPanel calc=new CalculatorPanel();
getContentPane().add(calc);
}
}
class CalculatorPanel extends JPanel implements ActionListener
{
JButton
n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
static JTextField result=new JTextField("0",45);
static String lastCommand=null;
JOptionPane p=new JOptionPane();
double preRes=0,secVal=0,res;
private static void assign(String no)
{
if((result.getText()).equals("0"))
result.setText(no);
else if(lastCommand=="=")
{
result.setText(no);
lastCommand=null;
}
else
result.setText(result.getText()+no);
}
public CalculatorPanel()
{
setLayout(new BorderLayout());
result.setEditable(false);
result.setSize(300,200);
add(result,BorderLayout.NORTH);
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(4,4));
n7=new JButton("7");
panel.add(n7);
n7.addActionListener(this);
n8=new JButton("8");
panel.add(n8);

n8.addActionListener(this);
n9=new JButton("9");
panel.add(n9);
n9.addActionListener(this);
div=new JButton("/");
panel.add(div);
div.addActionListener(this);
n4=new JButton("4");
panel.add(n4);
n4.addActionListener(this);
n5=new JButton("5");
panel.add(n5);
n5.addActionListener(this);
n6=new JButton("6");
panel.add(n6);
n6.addActionListener(this);
mul=new JButton("*");
panel.add(mul);
mul.addActionListener(this);
n1=new JButton("1");
panel.add(n1);
n1.addActionListener(this);
n2=new JButton("2");
panel.add(n2);
n2.addActionListener(this);
n3=new JButton("3");
panel.add(n3);
n3.addActionListener(this);
minus=new JButton("-");
panel.add(minus);
minus.addActionListener(this);
dot=new JButton(".");
panel.add(dot);
dot.addActionListener(this);
n0=new JButton("0");
panel.add(n0);
n0.addActionListener(this);
equal=new JButton("=");
panel.add(equal);
equal.addActionListener(this);
plus=new JButton("+");
panel.add(plus);
plus.addActionListener(this);
add(panel,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==n1) assign("1");
else if(ae.getSource()==n2) assign("2");
else if(ae.getSource()==n3) assign("3");
else if(ae.getSource()==n4) assign("4");
else if(ae.getSource()==n5) assign("5");

else if(ae.getSource()==n6) assign("6");


else if(ae.getSource()==n7) assign("7");
else if(ae.getSource()==n8) assign("8");
else if(ae.getSource()==n9) assign("9");
else if(ae.getSource()==n0) assign("0");
else if(ae.getSource()==dot)
{
if(((result.getText()).indexOf("."))==-1)
result.setText(result.getText()+".");
}
else if(ae.getSource()==minus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="-";
result.setText("0");
}
else if(ae.getSource()==div)
{
preRes=Double.parseDouble(result.getText());
lastCommand="/";
result.setText("0");
}
else if(ae.getSource()==equal)
{
secVal=Double.parseDouble(result.getText());
if(lastCommand.equals("/"))
res=preRes/secVal;
else if(lastCommand.equals("*"))
res=preRes*secVal;
else if(lastCommand.equals("-"))
res=preRes-secVal;
else if(lastCommand.equals("+"))
res=preRes+secVal;
result.setText(" "+res);
lastCommand="=";
}
else if(ae.getSource()==mul)
{
preRes=Double.parseDouble(result.getText());
lastCommand="*";
result.setText("0");
}

else if(ae.getSource()==plus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="+";
result.setText("0");
}
}
}

2nd File : Calculator1.html 


(need this file to create applet)

<html>
<body>
<applet code="Calculator1.java" width ="300" height
="300">
</applet>
</body>
</html>

b) Design a screen to handle the Mouse Events such as MOUSE_MOVED and


MOUSE_CLICK and display the position of the Mouse_Click in a
TextField.
Ans import java.awt.*;

import java.awt.event.*;
class MyFrame extends Frame
{
    TextField t,t1;
    Label l,l1;
    int x,y;
    Panel p;
    MyFrame(String title)
    {
        super(title);
        setLayout(new FlowLayout());
       
        p=new Panel();
        p.setLayout(new GridLayout(2,2,5,5));
        t=new TextField(20);
        l= new Label("Co-ordinates of clicking");
        l1= new Label("Co-ordinates of movement");
        t1=new TextField(20);
        p.add(l);
        p.add(t);
        p.add(l1);
        p.add(t1);
        add(p);
        addMouseListener(new MyClick());
        addMouseMotionListener(new MyMove());
        setSize(500,500);
        setVisible(true);
    }
    class MyClick extends MouseAdapter
    {
        public void mouseClicked(MouseEvent me)
        {
            x=me.getX();
            y=me.getY();
            t.setText("X="+x+" Y="+y);
        }
    }
    class MyMove extends MouseMotionAdapter
    {
        public void mouseMoved(MouseEvent me)
        {
            x=me.getX();
            y=me.getY();
            t1.setText("X="+ x +" Y="+y);
        }
    }
}
class Slip4
{
    public static void main(String args[])
    {
        MyFrame f = new MyFrame("Slip Number 4");
    }
}

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.

Ans
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class Swing2 extends JFrame implements ActionListener


{
    JLabel l1,l2,l3;
        JButton b;
        JRadioButton r1,r2,r3;
        JCheckBox c1,c2,c3;
        JTextField t1,t2;
        ButtonGroup b1;
        JPanel p1,p2;
    static int cnt;
        private StringBuffer s1=new StringBuffer();
       
        Swing2()
        {
           
                b1=new ButtonGroup();
                p1=new JPanel();
                p2=new JPanel();
                b=new JButton("Clear");
                b.addActionListener(this);
               
                r1=new JRadioButton("FY");
                r2=new JRadioButton("SY");
                r3=new JRadioButton("TY");
               
                b1.add(r1);
                b1.add(r2);
                b1.add(r3);
                r1.addActionListener(this);
                r2.addActionListener(this);
                r3.addActionListener(this);
               
                c1=new JCheckBox("Music");
                c2=new JCheckBox("Dance");
                c3=new JCheckBox("Sports");
               
                c1.addActionListener(this);
                c2.addActionListener(this);
                c3.addActionListener(this);
               
                l1=new JLabel("Your Name");
                l2=new JLabel("Your Class");
                l3=new JLabel("Your Hobbies");
                t1=new JTextField(20);
                t2=new JTextField(30);
               
                p1.setLayout(new GridLayout(5,2));
                p1.add(l1);p1.add(t1);
                p1.add(l2);p1.add(l3);
                p1.add(r1);p1.add(c1);
                p1.add(r2); p1.add(c2);
                p1.add(r3);p1.add(c3);
               
                p2.setLayout(new FlowLayout());
                p2.add(b);
                p2.add(t2);
               
                setLayout(new BorderLayout());
                add(p1,BorderLayout.NORTH);
                add(p2,BorderLayout.EAST);

            setSize(400,200);
                setVisible(true);
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
   
        public void actionPerformed(ActionEvent e)
        {
           
                if(e.getSource()==r1)
                {
                    cnt++;
                    if(cnt==1)
                    {
                        String s =t1.getText();
                            s1.append("Name = ");
                            s1.append(s);
                    }
                    s1.append(" Class = FY");
                }
                else if(e.getSource()==r2)
                {
                    cnt++;
                    if(cnt==1)
                    {
                        String s =t1.getText();
                            s1.append("Name = ");
                            s1.append(s);
                    }
                    s1.append(" Class = SY");
                }
                else if(e.getSource()==r3)
                {
                    cnt++;
                    if(cnt==1)
                    {
                        String s =t1.getText();
                            s1.append("Name = ");
                            s1.append(s);
                    }
                    s1.append(" Class = TY");
                }

           
                else if(e.getSource()==c1)
                {
                    s1.append(" Hobbies = Music");
                }
                else if(e.getSource()==c2)
                {
                    s1.append(" Hobbies = Dance");
                }
                else if(e.getSource()==c3)
                {
                    s1.append(" Hobbies = Sports");
                }
           
                t2.setText(new String(s1));
                //              t2.setText(s2);
               
                if(e.getSource()==b)
                {
                    t2.setText(" ");
                        t1.setText(" ");
                }
           
        }
   
        public static void main(String arg[])
        {
            Swing2 s=new Swing2();
               
        }
}

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.
Ans import java.awt.*;
import java.awt.event.*;
class InvalidPasswordException extends Exception
{
InvalidPasswordException()
{
System.out.println(” User name and Password is not same”);
}
}
public class PasswordDemo extends Frame implements ActionListener
{
Label uname,upass;
TextField nametext;
TextField passtext,msg;
Button login,Clear;
Panel p;
int attempt=0;
char c= ‘ * ‘ ;

public void login()


{
p=new Panel();
uname=new Label(“Use Name: ” ,Label.CENTER);
upass=new Label (“Password: “,Label.RIGHT);

nametext=new TextField(20);
passtext =new TextField(20);
passtext.setEchoChar(c);
msg=new TextField(10);
msg.setEditable(false);

login=new Button(“Login”);
Clear=new Button(“Clear”);
login.addActionListener(this);
Clear.addActionListener(this);

p.add(uname);
p.add(nametext);
p.add(upass);
p.add(passtext);
p.add(login);
p.add(Clear);
p.add(msg);
add(p);

setTitle(“Login “);
setSize(290,200);
setResizable(false);
setVisible(true);
}

public void actionPerformed(ActionEvent ae)


{
Button btn=(Button)(ae.getSource());
if(attempt<3)
{
if((btn.getLabel())==”Clear”)
{
nametext.setText(“”);
passtext.setText(“”);
}
if((btn.getLabel()).equals(“Login”))
{
try
{
String user=nametext.getText();
String upass=passtext.getText();

if(user.compareTo(upass)==0)
{
msg.setText(“Valid”);
System.out.println(“Username is valid”);
}
else
{
throw new InvalidPasswordException();
}
}
catch(Exception e)
{
msg.setText(“Error”);
}
attempt++;
}
}
else
{
System.out.println(“you are using 3 attempt”);
System.exit(0);
}
}
public static void main(String args[])
{
PasswordDemo pd=new PasswordDemo();
pd.login();
}
}
Or
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class InvalidPasswordException extends Exception
{}
class Slip17 extends JFrame implements ActionListener
{
    JLabel name, pass;
    JTextField nameText;
    JPasswordField passText;
    JButton login, end;
    static int cnt=0;
        Slip17()
    {
         name = new JLabel("Name : ");
         pass = new JLabel("Password : ");
         nameText = new JTextField(20);
         passText = new JPasswordField(20);
         login = new JButton("Login");
         end = new JButton("End");
         login.addActionListener(this);
          end.addActionListener(this);              
                              setLayout(new GridLayout(3,2));
          add(name);
          add(nameText);
          add(pass);
          add(passText);
          add(login);
          add(end);
          setTitle("Login Check");
          setSize(300,300);                              
                                   
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setVisible(true);
     }
     public void actionPerformed(ActionEvent e)
     {
               if(e.getSource()==end)
          {
                        System.exit(0);
   
          }
          if(e.getSource()==login)
          {
             try
             {
                 String user = nameText.getText();
                 String pass = new String(passText.getPassword());
                                   if(user.compareTo(pass)==0)
                 {  JOptionPane.showMessageDialog(null,"Login
Successful","Login",JOptionPane.INFORMATION_MESSAGE);
                     System.exit(0);
                  }
                  else
                  {
                      throw new InvalidPasswordException();
                  }
                }
                catch(Exception e1)
                {
                    cnt++;
                    JOptionPane.showMessageDialog(null,"Login
Failed","Login",JOptionPane.ERROR_MESSAGE);
                     nameText.setText("");
                     passText.setText("");
                     nameText.requestFocus();
                     if(cnt == 3)
                    {
           JOptionPane.showMessageDialog(null,"3 Attempts
Over","Login",JOptionPane.ERROR_MESSAGE);
                        System.exit(0);          
                                                             }
                }      
         }              
   }
  public static void main(String args[])
 {
                new Slip17();
 }
}

You might also like