OOPJ PROGRAMS









Practicals
1.Write a program to print “Hello CGPIT” on the console.
public class pr1
{
    public static void main(String args[])
    {
        System.out.println("Hello CGPIT");
    }
}
output:

2.Write a program to print inputs given from command line arguments on the console.
public class pr2
{
    public static void main(String args[])
    {
        for(int i=0;i<args.length;i++)
        {
        System.out.println(args[i]);
        }
    }
}

output:

3.Write a program to check whether given number is Armstrong or not.
import java.util.Scanner;
public class ars
{
    public static void main(String args[])
    {
       int n,temp,sum=0,r;
        Scanner s1=new Scanner (System.in);
        System.out.println("Enter n=");
        n=s1.nextInt();
        temp=n;
        while(n>0)
        {
            r=n%10;
            sum=sum+(r*r*r);
            n=n/10;
           
        }

     if(temp==sum)
        {
            System.out.println("The no.is an armstrong no.");
        }
        else
        {
            System.out.println("The no.is not an armstrong no.");
        }
       
    }
}

output:

4.Write a program using switch which takes two command line arguments. First argument is a string (odd, even, avg, sum) specifies the operation and second argument (number N) is the upper limit of the range starting from 0. 
Ex. 1) Arguments: even 10; Output: 0 2 4 6 8 10.
 2) Arguments: sum 5; Output: 15
import java.util.*;
import java.lang.*;
public class argue
{
    public static void main(String args[])
    {
        int sum=0,temp;
        int n=Integer.parseInt(args[1]);
        switch(args[0])
        {
            case"odd":temp=1;
            while(temp<n)
            {
                if(temp%2==1)
                {
                    System.out.println(temp+" ");
                }
                temp++;
            }
            break;
            case"even":temp=1;
            while(temp<n)
            {
                if(temp%2==0)
                {
                    System.out.println(temp+" ");
                }
                temp++;
            }
            break;
            case"sum":
            while(n>0)
            {
                sum=sum+n;
                n--;
            }
            System.out.println("Sum is="+sum);
            break;
            case"avg": temp=n;
            while(n>0)
            {
                sum=sum+n;
                n--;
            }
            System.out.println("Average is-"+sum/temp);
            break;
            default:
            System.out.println("Wrong input");
        }
    }
}

output:

5. Write a program that finds factorials of a given number.
import java.util.Scanner;
public class factorial
{
    public static void main(String args[])
    {
        int i,n,fact=1;
        Scanner s1=new Scanner (System.in);
        System.out.print("Enter n=");
        n=s1.nextInt();
        for(i=1;i<=n;i++)
        {
            fact=fact*i;
        }
        System.out.print("Factorial n="+fact);
    }
}

output:


6.Write a program to take marks of five students and print the marks of students in descending order.
import java.util.Scanner;
public class pr6
{
    public static void main(String args[])
    {
        int a[]=new int[20];
        int i,j,n=5,temp;
        Scanner s1=new Scanner(System.in);
        System.out.println("Enter 5 subjects marks out of 50\n");
        for(i=0;i<n;i++)
        {
            System.out.print("Subject "+(i+1)+" marks-");
            a[i]=s1.nextInt();
        }
        System.out.println("Marks in Descending Order\n");
        for(i=0;i<n;i++)
        {
            for(j=i+1;j<n;j++)
            {
                if(a[i]<a[j])
                {
                    temp=a[i];
                    a[i]=a[j];
                    a[j]=temp;
                }
            }
            System.out.println(a[i]);
        }
    }
}

output:



7. Define a class Student which contain following: Data members: 1. Name of student 2.Enrollment number of student 3. Contact number of student Member Functions: 1. To get details of the student 2. To display details of the student Write a program to display details of one students.
import java.util.Scanner;
class student

{
   
    int eno,con;
    String name;
    Scanner s1=new Scanner (System.in);

    void get()
    {
        System.out.print("Enter your Name-");
        name=s1.next();
        System.out.println("Enter Your enrollnment no.=");
        eno=s1.nextInt();
        System.out.println("Enter contact no.=");
        con=s1.nextInt();
    }
    void display()
    {
        System.out.println("Name of the Student -"+name);
        System.out.println("The enrollnment number is"+eno);
        System.out.println("contact no.-"+con);
    }
};

class stud
{
    public static void main(String args[])
    {
        student b=new student();
        b.get();
        b.display();
    }
}

output:


8. Define a class of Bank_system which contain following: Data Members: 1. Name of account holder 2. Account number 3. Balance in the account Member Functions: 1. To get details of the account 2. To display the balance 3. To search account by account number Write program for above BankSystem that handles five customers.
import java.util.Scanner;
class bank
{
    String name;
    String accno;
    int bal;
    Scanner s1=new Scanner (System.in);

    void getdata()
    {
        System.out.print("Enter Bank Holder Name-");
        name=s1.next();
        System.out.print("\nEnter Account Number-");
        accno=s1.next();
        System.out.print("Enter Balance-");
        bal=s1.nextInt();
    }

    void display()
    {
        System.out.print("Bank Holder Name is-"+name);
        System.out.print("\nAccount No.-"+accno);
        System.out.print("\nBalance-"+bal);
    }

    public boolean search(String ac_no)
    {
        if(accno.equals(ac_no))
        {
            display();
            return(true);
        }
        return(false);
    }
}
public class pr8
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int n,i;
        System.out.print("Enter the number of Bank Holder-");
        n=sc.nextInt();
        bank s[]=new bank[n];
        for(i=0;i<s.length;i++)
        {
            s[i]=new bank();
            s[i].getdata();
        }

        int ch;
        do{
            System.out.println("\nBANK SYSTEM\n");
            System.out.print("\n1.Display all account details \n2.Search By Account Number \n3.Exit");
            System.out.println("\nEnter Your Choice-");
            ch=sc.nextInt();
            switch(ch)
            {
                case 1:
                for(i=0;i<s.length;i++)
                {
                    s[i].display();
                }
                break;

                case 2:
                System.out.println("Enter The Account no. you want to search=");
                String ac_no=sc.next();
                boolean found=false;
                for(i=0;i<s.length;i++)
                {
                    found=s[i].search(ac_no);
                    if(found){
                        break;
                    }
                }
                if(!found){
                    System.out.println("Search Failed! Account doesn't exist.!!");
                }
                break;

                case 3:
                System.out.println("Thank you Have a Great Day");
                break;
            }
        }
        while(ch!=3);
    }
}

output:


9.Define a class called TIMEC with Three integer data members for hours minutes and seconds and following constructors and functions.  Constructor to initialize the object to zero  Constructor to initialize the object to some constant value  Member function to add two TIME objects  Member function to display time in HH:MM:SS format Write a Java program that creates two TIME objects, add them and display the resultant time in HH:MM:SS format. 
class TimeC{
int hh, mm, ss;
public TimeC()
{
hh = 0;
mm = 0;
ss = 0;
}
public TimeC(int hour, int min, int sec){
hh = hour;
mm = min;
ss = sec;
}

TimeC Sum(TimeC t){
TimeC t4 = new TimeC();
t4.hh = t.hh + hh;
t4.mm = t.mm + mm;
t4.ss = t.ss + ss;
if(t4.ss > 60){
t4.ss -= 60;
t4.mm++;
}
if(t4.mm > 60){
t4.mm -= 60;
t4.hh++;
}
if(t4.hh > 24){
t4.hh = 0;
}
return t4;
}

void display(){
System.out.println("Time: "+hh+":"+mm+":"+ss);
}
}

class pr9{
public static void main(String args[]){
TimeC t1 = new TimeC(10,40,30);
TimeC t2 = new TimeC(12,30,50);
TimeC t3 = new TimeC();
t3 = t1.Sum(t2);
t3.display();
}
}

output:


10.Write a Java class ShapeArea which calculates the area of a square, rectangle and circle. Write a program to print the area of square, rectangle, and circle.Demonstrate the concept of method overloading

import java.util.Scanner;
class ShapeArea{
int area(int length){
return length * length;
}
int area(int length, int breadth){
return length * breadth;
}
double area(double radius){
double result = 3.14*radius*radius;
return result;
}
}

class Practical10{
public static void main(String args[]){
ShapeArea a = new ShapeArea();
Scanner sc = new Scanner(System.in);
System.out.println("Enter length:");
int l = sc.nextInt();
System.out.println("Area of square: "+a.area(l));
System.out.println("Enter length and breadth:");
int len = sc.nextInt();
int b = sc.nextInt();
System.out.println("Area of rectangle: "+a.area(len, b));
System.out.println("Enter radius:");
float r = sc.nextFloat();
System.out.println("Area of circle: "+a.area(r));
}
}

output:


11.Write a java program to find out the payroll system using single inheritance. Create one base class and one derived class. The base class "Emp" contains the data members: emp_name, emp_no,designation. The derived class "salary" contains the data members: Basic pay,home rent allowance (HRA). Write a java program to calculate salary for 5 employees. The formula for calculating salary: 
(Salary =Basic pay + HRA*(Basic Pay)+ HRA)
import java.util.Scanner;

class Emp
{
    String emp_name;
    String emp_no;
    String desig;
    Scanner s1=new Scanner (System.in);
    void getdata()
    {
        System.out.print("Enter Employee Name-");
        emp_name=s1.next();
        System.out.print("\nEnter Employee No.-");
        emp_no=s1.next();
        System.out.print("\nDesignation-");
        desig=s1.next();
    }
    void display()
    {
        System.out.print("EMPLOYEE NAME-"+emp_name);
        System.out.print("\nEMPLOYEE NUMBER-"+emp_no);
        System.out.print("\nDESIGNATION-"+desig);
    }
}

class Salary extends Emp
{
    float salary;
    int basic_pay;
    int hra;
    Scanner s2=new Scanner(System.in);
    void getdetails()
    {
        System.out.println("Enter the Basic Pay of the employee-");
        basic_pay=s2.nextInt();
        System.out.println("Enter the HRA of the employee-");
        hra=s2.nextInt();
    }
    void sal()
    {
        salary=basic_pay+hra*(basic_pay)+hra;
        System.out.println("The Salary of the employee is-"+salary);
    }
}

public class pr11
{
    public static void main(String args[])
    {
            Salary S[]=new Salary[5];
            for(int i=0;i<5;i++)
            {
                S[i]=new Salary();
                S[i].getdata();
                S[i].getdetails();
                S[i].sal();
            }
     }
}

output:

12.Create a class Product that has data members Product Id, Product Name, and Price. Create class ProductDetails by inheriting Product class and having a method to enter all product details. Create class DisplayDetails by inheriting Product Details class and having a method to display all the details of the product. Write a program to print details of two products using Multi-level inheritance.
import java.util.Scanner;

class PRODUCT
{
    int p_id;
    String p_name;
    int price;
}

class ProductDetails extends PRODUCT
{
    Scanner s1 = new Scanner(System.in);
    void getdata()
    {
        System.out.println("\nENTER THE NAME OF PRODUCT ");
        p_name = s1.nextLine();
        System.out.println("ENTER THE ID OF PRODUCT ");
        p_id = s1.nextInt();
        System.out.println("ENTER THE PRICE OF PRODUCT ");
        price = s1.nextInt();
    }
}

class DisplayDetails extends ProductDetails
{
    void display()
    {
        System.out.println("THE ID OF PRODUCT IS " + p_id);
        System.out.println("THE NAME OF PRODUCT IS " + p_name);
        System.out.println("THE PRICE OF PRODUCT IS " + price);
    }
}

public class P12
{
    public static void main(String args[])
    {
        DisplayDetails D[] = new DisplayDetails[2];
        for(int i=0;i<2;i++)
        {
            D[i] = new DisplayDetails();
            D[i].getdata();
            D[i].display();
        }
    }
}
output:-


13.Create a class Student which has data members enrollment no, exam number, and student name. Create class Exam by inheriting student class and having fields to store marks scored in three subjects. It has method to calculate results. Write a program to print results for two students. Note: Implement this using all usage of super keyword.
import java.util.Scanner;
class Student
{
    int enroll_no;
    int exam_no;
    String stu_name;
    Scanner s1=new Scanner(System.in);
    void getdata()
    {
        System.out.println("Enter Enrollnment no-");
        enroll_no=s1.nextInt();
        System.out.println("Enter Exam no-");
        exam_no=s1.nextInt();
        System.out.println("Enter Student Name-");
        stu_name=s1.next();
    }
}

class Exam extends Student
{
    Scanner s2=new Scanner(System.in);
    int m1,m2,m3;
     float cal;
    void getdata()
    {
        super.getdata();
        System.out.println("Enter the marks of subject 1(1-100marks)-");
        m1=s2.nextInt();
        System.out.println("Enter the marks of subject 2(1-100marks)-");
        m2=s1.nextInt();
       
        System.out.println("Enter the marks of subject 3(1-100marks)-");
        m3=s1.nextInt();
       
    }
    void calculate()
    {
        cal=(m1+m2+m3)*100/300;
        System.out.println("The Total percentage of student is-"+cal+"%");
       
    }
}

public class pr13
{
    public static void main(String args[])
    {
        Exam a[]=new Exam[2];
        for(int i=0;i<2;i++)
        {
            a[i]=new Exam();
            a[i].getdata();
            a[i].calculate();
        }
    }
}
output:-

14.Create an abstract class department with data members university, college,method display() and abstract method subject_list().Create subclasses CE and EE which implements the method subject_list().Write a program to display subjects offered by CE and EE departments
import java.util.Scanner;
abstract class department
{
    String university="Uka Tarsadia";
    String college="CGPIT";
     void display()
     {
        System.out.println("University Name="+university);
        System.out.println("College Name="+college);
     }
     abstract void subject_list();
}

class CE extends department
{
    int i;
    Scanner sc=new Scanner(System.in);
    String a[]=new String[4];
    void subject_list()
    {
        super.display();
        System.out.println("Enter subjects of CE Department");
        for(i=0;i<4;i++)
        {
            System.out.print("Subject"+(i+1)+"-");
            a[i]=sc.next();  
        }  
    }
    void display()
        {
          System.out.println("Subjects of CE departments-");
            for(i=0;i<4;i++)
            {
                System.out.println(a[i]);
            }
        }

}
class EE extends department
{
    int i;
    Scanner s1=new Scanner(System.in);
    String a[]=new String[4];
    void subject_list()
    {
        System.out.println("Enter subjects of EE Department");
        for(i=0;i<4;i++)
        {
            System.out.print("Subject"+(i+1)+"-");
            a[i]=s1.next();  
        }  
    }
    void displaysubject1()
        {
            System.out.println("Subjects of EE departments-");
            for(i=0;i<4;i++)
            {
                System.out.println(a[i]);
            }
        }

}

public class pr14
{
    public static void main(String args[])
   
    {
        CE c=new CE();
        c.subject_list();
        c.display();
       
        EE e=new EE();
        e.subject_list();
        e.displaysubject1();
    }
}

output:
University Name=Uka Tarsadia
College Name=CGPIT
Enter subjects of CE Department
Subject1-FOP
Subject2-DS
Subject3-DLD
Subject4-DBMS
Subjects of CE departments-
FOP
DS
DLD
DBMS
Enter subjects of EE Department
Subject1-FEE
Subject2-BEE
Subject3-MATHS
Subject4-NETWORKTHEORY
Subjects of EE departments-
FEE
BEE
MATHS
NETWORKTHEORY

15.Define an interface bird having the methods of food() and voice().Define two classes sparrow and peacock to implement the interface bird. Write a program to test the sparrow and peacock classes.
interface bird
{
    void food();
    void voice();
}
class sparrow implements bird
{
    public void food(){
        System.out.println("Sparrow Food=insects");
    }
    public void voice(){
        System.out.println("Sparrow Voice=chi chi\n");
    }
}
class peacocks implements bird
{
    public void food(){
        System.out.println("Peacocks Food= insects");
    }
    public void voice(){
        System.out.println("Peacock Voice=keh-keh");
    }
}
public class pr15
{
    public static void main(String args[])
    {
        bird b=new sparrow();
        b.food();
        b.voice();
        bird p=new peacocks();
        p.food();
        p.voice();
    }
}

output:
Sparrow Food=insects Sparrow Voice=chi chi Peacocks Food= insects Peacock Voice=keh-keh 

16
.Write a java program that import the user defined package and access the member variable of class that is inside the package.
package mypack; /*Package class*/
public class Myclass
{
    int a;
   public void set_value(int n)
    {
        a=n;
    }
    public void display_value()
    {
        System.out.println("The value of a is:"+a);
    }
}

PS E:\java\ javac -d. Myclass.java /*( creating a package)*/

/*Main class*/
public class PackageDemo
{
    public static void main(String args[])
    {
        mypack.Myclass obj=new mypack.Myclass();    /*calling the package Myclass*/
        obj.set_value(10);
        obj.display_value();
    }
}

class save=javac PackageDemo.java
Run output=java PackageDemo
output:-
The value of a is:10





17.Write a program to handle following exceptions: 
1 StringIndexOutOfBoundsException 
public class pr17s {
   public static void main(String[] args) {
      String str = "Hello how are you";
      for(int i=0; i<str.length(); i++) {
         System.out.println(str.charAt(i));
      }
      System.out.println(str.length());
      //Accessing element at greater than the length of the String
      try {
         System.out.println(str.charAt(40));
      }catch(StringIndexOutOfBoundsException e) {
         System.out.println("Exception occurred . . . . . . . . ");
      }
   }
}

output:
H e l l o h o w a r e y o u
17 Exception occurred . . . . . . . .
2. NullPointerException 

// A Java program to demonstrate that invoking a method
// on null causes NullPointerException
import java.util.*;

class nullpointer
{
    public static void main (String[] args)
    {
        // Initializing String variable with null value
        String ptr = null;

        // Checking if ptr.equals null or works fine.
        try
        {
            // This line of code throws NullPointerException
            // because ptr is null
            if (ptr.equals("gfg"))
                System.out.print("Same");
            else
                System.out.print("Not Same");
        }
        catch(NullPointerException e)
        {
            System.out.print("NullPointerException Caught");
        }
    }
}

Output:
NullPointerException Caught
3.NumberFormatException
public class NumberFormatExceptionHandlingTest {
   public static void main(String[] args) {
      try {
         new NumberFormatExceptionHandlingTest().intParsingMethod();
      } catch (NumberFormatException e) {
         System.out.println("We can catch the NumberFormatException");
      }
   }
   public void intParsingMethod() throws NumberFormatException{
      int x = Integer.parseInt("30k");
      System.out.println(x);
   }
}

output:
We can catch the NumberFormatException



18.Write a program to generate and handle a custom exception to
validate the entered phone number.

import java.util.Scanner;
class Validate extends Exception {
Validate(String s)
{
super(s);
}
}
class count
{
public static void main(String args[])
{
String ph=new String();
System.out.println("Enter Phone Number: ");
Scanner s =new Scanner(System.in);
ph=s.nextLine();
try {
int l=ph.length();
if(l==10)
{
for(int i=0;i<l;i++)
{
char c=ph.charAt(i);
if(!(c>=48 && c<=57))
throw new Validate("Incorrect Digits");

}
}

else
{
throw new Validate("Invalid Length of Phone Number");
}
System.out.println("Valid Number");
}
catch(Validate e)
{
System.out.println(e);
}
}
}

Output:-
Enter Phone Number: 985623542 Validate: Invalid Length of Phone Number

Enter Phone Number: 
1235648975
Valid Number




19.Write an application that executes two threads. One thread
Display“I’m Thread 1“every 1,000 milliseconds. And the other displays
“I’m Thread 2 “every 3,000 milliseconds. Create the threads by
a) implementing the Runnable interface &
b) extending Thread class.

import java.lang.*;
class demo{
void display(String s,int tp)
{
try{
int i=0;
while(i<10){
i++;
System.out.println(i+"I am "+s);
Thread.sleep(tp);
}

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

}
}
class ThreadDemo extends Thread {
int tp;
ThreadDemo(String s,int tp)
{
super(s);
this.tp=tp;

}

public void run() {
demo d1=new demo();
d1.display(Thread.currentThread().getName(),tp);
System.out.println(Thread.currentThread().getName()+" exiting\n\n\n");
}

public static void main(String[] args) throws Exception {

ThreadDemo t = new ThreadDemo("Thread 1",1000);
// this will call run() function
t.start();

Thread t2 = new ThreadDemo("Thread 2",3000);
// this will call run() function
t2.start();
}
}


output:-
1I am Thread 1 1I am Thread 2 2I am Thread 1 3I am Thread 1 4I am Thread 1 2I am Thread 2 5I am Thread 1 6I am Thread 1 7I am Thread 1 3I am Thread 2 8I am Thread 1 9I am Thread 1 4I am Thread 2 10I am Thread 1 Thread 1 exiting 5I am Thread 2 6I am Thread 2 7I am Thread 2 8I am Thread 2 9I am Thread 2 10I am Thread 2 Thread 2 exiting



20.Write a program to copy the content of one file into another
file.


import java.io.*;
class io {
public static void main(String[] args) throws Exception {
InputStream in = new FileInputStream(new File("in.txt"));
OutputStream out = new FileOutputStream(new File("out.txt"));
byte[] buf = new byte[1024];
int len;

while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();

}
}


output:-

In (folder)
Hello I am Server

Out(Folder)
Hello I am Server
Google Drive Link:-
click on this -->




















Comments

Post a Comment

Give your Feedback