Skip to content

Programming

✅ in questions denotes the no of question appearence. More the tick in question, possess high importance from examination point of view.

Chapter 1

  1. Write a program to sort any five names in alphabetical order.
  2. Write a program to print “Hello Nepal” in console. ✅
    class Two{
        public static void main(String[] args) {
            System.out.println("Hello Nepal");
        }
    }
    
  3. Write a program to show usage of various data types in Java.
  4. Write a function that takes an array of integers as an argument and returns sum of even numbers in that array.
    class Four {
        public static void main(String[] args) {
            int[] array = { 1, 2, 3, 4, 5 };
            int sum = sumArray(array);
            System.out.println("Sum : "+sum);
        }
    
        public static int sumArray(int[] array){
            int sum = 0;
            for(int num:array){
                sum += num;
            }
            return sum;
        }
    }
    
  5. Write a program to generate the following triangle using for loop.
    1  
    0  1  
    1  0  1  
    0  1  0  1
    
    class Five{
        public static void main(String[] args){
            for(int i = 1; i <= 4; i++){ // First we are running loop from 1 to 4.
                for(int j = 0; j < i; j++){ // Then we are running loop from 0 until i.
                    System.out.print((j+i)%2+" "); // Sum of i and j modulus of 2 equals the alternate of 1 and 0. 
                }
                System.out.println();
            }
        }
    }
    
    // Practiced Algorithms
    
    // System.out.print((int)(temp+Math.pow(-1,j))+" ");
    // (int)(+Math.pow(-1,))
    // System.out.print((j+1)%2+" ");
    

Chapter 2

  1. Write a program which has two classes A and B, where A should act as Parent class and B should inherit from A.
    class A{
        void display(){
            System.out.println("This is from class A");
        }
    }
    class B extends A{
        void display(){
            System.out.println("This is from class B");
        }
    }
    
    class Demo{
        public static void main(String[] args){
            A aObject = new A();
            B bObject = new B();
    
            aObject.display();
            bObject.display();
            // bObject.super.display();
        }
    }
    
  2. Create a class Employee with id, name, post and salary. Create parameterized constructor to initialize the instance variables. Override the toString( ) method to display the employee details.
    class Employee {
        private int id;
        private String name;
        private String post;
        private double salary;
    
        Employee(int id, String name, String post, double salary) {
            this.id = id;
            this.name = name;
            this.post = post;
            this.salary = salary;
        }
    
        // This overrides the toString() method.
        // Returns a string representation of the object. In general, the toString
        // method returns a string that "textually represents" this object. The result
        // should be a concise but informative representation that is easy for a person
        // to read. It is recommended that all subclasses override this method.
        public String toString() {
            return "ID : " + this.id + "\nName : " + this.name + "\nPost : " + this.post + "\nSalary : " + this.salary;
        }
    }
    
    class Two {
        public static void main(String[] args) {
            Employee employeeOne = new Employee(12, "Arjun", "Manager", 12345.90);
            String employee = employeeOne.toString();
            System.out.println(employee);
        }
    }
    
    // System.out.println("ID : "+id);
    // System.out.println("Name : "+name);
    // System.out.println("Post : "+post);
    // System.out.println("Salary : "+salary);
    
  3. Create a class Parts with instance variable sno, name, model, price, constructors to initialize the object, a method to calculate commission which calculates 10% of the price of each item and a method to display the details. Derive a new class PartsVAT with a method to calculate 13% VAT of the item. Write necessary constructors to that use the super constructors. Test the classes using a main method in third classes.
    class Parts {
        private int sno;
        private String name;
        private String model;
        private double price;
    
        Parts(int sno, String name, String model, double price) {
            this.sno = sno;
            this.name = name;
            this.model = model;
            this.price = price;
        }
    
        public int getSno() {
            return sno;
        }
        public String getName() {
            return name;
        }
        public double getPrice() {
            return price;
        }
        public String getModel() {
            return model;
        }
    
        public double tax() {
            return 0.1 * this.price;
        }
    
        public void display() {
            System.out.println("\nS.N. : " + this.getSno() + "\nName : " + this.getName() + "\nModel : " + this.getModel()
                    + "\nPirce : " + this.getPrice() + "\nTax : " + this.tax());
        }
    }
    
    class PartsVAT extends Parts {
        PartsVAT(int sno, String name, String model, double price) {
            super(sno, name, model, price);
        }
    
        public double tax() {
            return 0.13 * getPrice();
        }
    
        public void display() {
            System.out.println("\nS.N. : " + this.getSno() + "\nName : " + this.getName() + "\nModel : " + this.getModel()
                    + "\nPirce : " + this.getPrice() + "\nTax : " + this.tax());
        }
    }
    
    class Three{
        public static void main(String[] args){
            PartsVAT obj = new PartsVAT(12, "Tesla", "Y", 400000.00d);
            obj.display();
    
            Parts objOne = new Parts(11, "Audi", "R8", 650000.00d);
            objOne.display();
        }   
    }
    
  4. Write an interface Exam with a method pass (int pass) that returns a Boolean. Write another interface Classify with a method division (int average) which returns a string. Write class Result which implements both Exams and Classify. The pass method should return true if score is greater than 50 otherwise false. The division method must return “First” when average is more than 80, “Second when average is more than 50 otherwise ”No Divison”.
    interface Exam {
        public boolean pass(int average);
    }
    
    interface Classify {
        public String division(int average);
    }
    
    public class Result implements Exam, Classify {
        public boolean pass(int average) { // Interface implement garda method ko agadi jahile pani public rakhne natra "attempting to assign weaker access privileges; was public" error message aaucha.
            if (average > 50) {
                return true;
            } else {
                return false;
            }
        }
    
        public String division(int average) {
            if (average > 80) {
                return "First Division";
            } else if (average > 50) {
                return "Second Division";
            } else {
                return "No Division";
            }
        }
    }
    
    class ResultDemo {
        public static void main(String[] args) {
            Result resultObj = new Result();
            int average = 45;
            boolean pass = resultObj.pass(average);
            String div = resultObj.division(average);
            System.out.println("Pass : " + pass + "\nDivision : " + div);
        }
    }
    
  5. Write a Java program to demonstrate runtime polymorphism via method overriding. Write the following classes: Animal as a base class, Cat (derived class of Animal) and Cow (derived class of Animal). Write a method eat( ) in Animal class and override that method in the derived classes.
    abstract class Animal{ // Define a abstract class.
        abstract void eat(); // Define a abstract method.
    }
    
    class Cat extends Animal{
        void eat(){ // Override it.
            System.out.println("Cat is eating.");
        }
    }
    
    class Cow extends Animal{
        void eat(){ // Override it.
            System.out.println("Animal is eating.");
        }
    }
    
    class Five{
        public static void main(String[] args){
            Animal referrer = new Cat(); // Create referrer object of Parent abstract class.
            referrer.eat();
            referrer = new Cow();
            referrer.eat();
        }
    }
    
  6. Implement an abstract class named Person and two subclasses named Student and Employee in Java. A person has a name, address, phone number and e-mail address. A student has a class status (freshman, sophomore, junior or senior). Define the status as a constant. An employee has an office, salary and date-hired. Implement the above classes in Java. Provide Constructors for classes to initialize private variables. Override the toString( ) methods in each class to display class name and the person’s name. Write an application to create objects of type Student and Employee and print the person’s name and the class name of the objects.
    abstract class Person 
    {
        String name, address, phoneNumber, email;
        Person(String name, String address, String phoneNumber, String email) 
        {
            this.name = name;
            this.address = address;
            this.phoneNumber = phoneNumber;
            this.email = email;
        }
        abstract public String toString();
    }
    
    
    class Student extends Person
    {
        final String status; // Provide status as (freshman, sophomore, junior or senior.)
        Student(String name, String address, String phoneNumber, String email, String status) 
        {
            super(name, address, phoneNumber, email);
            this.status = status;
        }
        @Override
        public String toString() 
        {
            return "Class Name: " + this.getClass().getName() + "\nName: " + this.name;
        }
    }
    
    class Employee extends Person 
    {
        String office, salary, dateHired;
    
        Employee(String name, String address, String phoneNumber, String email, String office, String salary, String dateHired) 
        {
            super(name, address, phoneNumber, email);
            this.office = office;
            this.salary = salary;
            this.dateHired = dateHired;
        }
        @Override
        public String toString() 
        {
            return "Class Name: " + this.getClass().getName() + "\nName: " + this.name;
        }
    }
    
    public class Six
    {
        public static void main(String[] args)
        {
            Student studentOne = new Student("Arjun Adhikari", "Pokhara", "9800011111", "[email protected]", "Senior");
            Employee employeeOne = new Employee("Anil Adhikari", "Pokhara", "982211111", "[email protected]", "Human Resources", "234454.90", "1 January 2019");
            String display = studentOne.toString();
            System.out.println(display);
            display = employeeOne.toString();
            System.out.println(display);
        }
    }
    
  7. Implement an abstract class named Book and two other subclasses named Novel and Magazine. A Book has a name, author, total page and publisher. Book has an abstract method called getBookType( ). Novel and Magazine have field to determine their type. Implement the above classes in Java. Provide constructors for classes to private variables.
    abstract class Book {
        private String name;
        private String author;
        private int totalPage;
        private String publisher;
    
        Book(String name, String author, int totalPage, String publisher) {
            this.name = name;
            this.author = author;
            this.totalPage = totalPage;
            this.publisher = publisher;
        }
        public String getName() {
            return name;
        }
        public String getAuthor() {
            return author;
        }
        public int getTotalPage() {
            return totalPage;
        }
        public String getPublisher() {
            return publisher;
        }
        abstract void getBookType(); // Abstract Method
    }
    
    class Novel extends Book {
    
        Novel(String name, String author, int totalPage, String publisher) {
            super(name, author, totalPage, publisher);
        }
    
    
    
        void getBookType() {
            System.out.println("Book Type : "+this.getClass());
            System.out.println("Name : " + getName());
            System.out.println("Author : " + getAuthor());
            System.out.println("Total Page : " + getTotalPage());
            System.out.println("Publisher: " + getPublisher());
        }
    }
    
    class Magazine extends Book {
    
        Magazine(String name, String author, int totalPage, String publisher) {
            super(name, author, totalPage, publisher);
        }
    
        void getBookType() {
            System.out.println("Book Type : " + this.getClass().getName()); // This returns the class type
            System.out.println("Name : " + getName());
            System.out.println("Author : " + getAuthor());
            System.out.println("Total Page : " + getTotalPage());
            System.out.println("Publisher: " + getPublisher());
        }
    }
    
    class Seven{
        public static void main(String[] args){
            Magazine magazineOne = new Magazine("TIME", "Time Editorial", 61, "Time Publishers");
            magazineOne.getBookType();
        }
    }
    
  8. Make a class Human with a name and age. Make a class Employee inherit from Human. Add instance variable salary of double. Supply a method showData( ) that prints the Employee’s name, age, and salary. Make a class Manager inherit from Employee. Supply appropriate showData( ) methods for all classes. Provide a test program that tests these classes and methods.
    class Human {
        private String name;
        private int age;
    
        Human(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public void display() {
            System.out.println("Name : " + name);
            System.out.println("Age : " + age);
        }
    }
    
    class Employee extends Human {
        private double salary;
    
        Employee(String name, int age, double salary){
            super(name,age);
            this.salary = salary;
        }
    
        public void display() {
            super.display();
            System.out.println("Salary : " + salary);
        }
    }
    
    class Manager extends Employee {
    
        Manager(String name, int age, double salary){
            super(name, age, salary);
        }
    
        public void display() {
            super.display();
        }
    }
    
    class Eight {
        public static void main(String[] args) {
            Human humanOne = new Human("Arjun",19);
            humanOne.display();
    
            Employee employeeOne = new Employee("Hari", 45, 21312.90);
            employeeOne.display();
    
            Manager managerOne = new Manager("Hari Nath", 45, 21312.90);
            managerOne.display();
    
    
        }
    }
    
  9. Create a class MyClass in a package MyPack. Import newly created class MyClass form IpmClass.

Chapter 3

  1. Write a program to input an integer from keyboard and print it on the console. Fire an exception if the input is other than integer using try and catch.
  2. Write a program to create your own Arithmetic Exception.

Chapter 4

  1. Write a program in Java to read a line of string in console mode and display same line as output. ✅ ✅ ✅ ✅
  2. Write a Java program to access an existing file in to your current directory.
  3. Write a program which stores and appends any String value given from keyword into the C:\store.txt.
  4. Write a program to read a text file and display the content on screen.
  5. Write a program to read two integer numbers from the console using the Input Stream. Calculate their sum display in console.
  6. Write a program to store objects of a class Student into a file “student.dat” also reads the objects from same file and display the file state of objects on the screen. Handle possible exceptions.
  7. Write a program using any stream class for writing text to a file.
  8. Write a program to read content from file “abc.txt” and store it in “xyz.txt”.
    /* Write a program to read content from file abc.txt and store it in xyz.txt. */
    
    import java.io.*;
    
    class DataTransfer
    {
        public static void main(String[] args)
        {
            try
            {
                FileReader filereader = new FileReader("abc.txt");
                FileWriter filewriter = new FileWriter("xyz.txt");
    
                int i = filereader.read();
                while(i != -1)
                {
                    System.out.print((char)i);
                    filewriter.write(i); // Appends every time
                    i = filereader.read();
                }
                filereader.close();
                filewriter.flush();
                filewriter.close();
            }
            catch(IOException err){
                err.printStackTrace();
            }
        }
    }
    
  9. Write a program to write “Hello World” in a file abc.txt.