📢 Join My WhatsApp Channel JavaWithSumit

Get Daily ICSE Java Notes, Programs & Exam Tips 🚀

👉 Join Now

User Defined Methods in Java Class 10 | All Programs with Output

Chapter 3: User Defined Methods



Question 1: WAP in Java to create a method to accept any two values from the user and multiply them. Store and display the result.

Solution: 


import java.util.Scanner; class MultiplyValues { // Method to multiply two numbers void multiply(int a, int b) { int result = a * b; System.out.println("Multiplication = " + result); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); // Creating object MultiplyValues obj = new MultiplyValues(); // Accepting values from user System.out.print("Enter first value: "); int x = sc.nextInt(); System.out.print("Enter second value: "); int y = sc.nextInt(); // Calling method obj.multiply(x, y); } }

Input:
Enter first value: 10
Enter second value: 2
Output: Multiplication =20

Question 2: WAP for method overloading by creating a method called vol() of calculate volume of a cube, cylinder and rectangular prism.
    Formulae:    Volume of cube = side3
                         Volume of Cylinder=Ï€×radius2×height
                        Volume of rectangular prism=length×breadth×height 
Solution: 


import java.util.Scanner; class Volume { // Volume of cube void vol(int side) { int volume = side * side * side; System.out.println("Volume of Cube = " + volume); } // Volume of cylinder void vol(double radius, double height) { double volume = 3.14 * radius * radius * height; System.out.println("Volume of Cylinder = " + volume); } // Volume of rectangular prism void vol(int length, int breadth, int height) { int volume = length * breadth * height; System.out.println("Volume of Rectangular Prism = " + volume); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); Volume obj = new Volume(); // Cube System.out.print("Enter side of cube: "); int s = sc.nextInt(); obj.vol(s); // Cylinder System.out.print("Enter radius of cylinder: "); double r = sc.nextDouble(); System.out.print("Enter height of cylinder: "); double h = sc.nextDouble(); obj.vol(r, h); // Rectangular Prism System.out.print("Enter length: "); int l = sc.nextInt(); System.out.print("Enter breadth: "); int b = sc.nextInt(); System.out.print("Enter height: "); int ht = sc.nextInt(); obj.vol(l, b, ht); } }

Input:
Enter side of cube: 3
Enter radius of cylinder: 2
Enter height of cylinder: 5
Enter length: 4
Enter breadth: 3
Enter height: 2
Output: Volume of Cube = 27 Volume of Cylinder = 62.800000000000004 Volume of Rectangular Prism = 24

Question 3: WAP to add two different time variables and display the output using following details in class Time.
Member Member's Name Description
Member Variables int hr, min To store hour and minute value
Member Methods input(int h,int m) To accept hours and minutes
addTime(Time t1,Time t2) To add two different time variables
display() To display time
Solution: 

import java.util.Scanner;

class Time
{
    int hr, min;

    // Method to accept time
    void input(int h, int m)
    {
        hr = h;
        min = m;
    }

    // Method to add two time objects
    void addTime(Time t1, Time t2)
    {
        min = t1.min + t2.min;
        hr = t1.hr + t2.hr;

        // Convert extra minutes into hours
        if(min >= 60)
        {
            hr = hr + (min / 60);
            min = min % 60;
        }
    }

    // Method to display time
    void display()
    {
        System.out.println("Total Time = " + hr + " Hours " + min + " Minutes");
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        Time t1 = new Time();
        Time t2 = new Time();
        Time t3 = new Time();

        // Input first time
        System.out.print("Enter first time (hours minutes): ");
        int h1 = sc.nextInt();
        int m1 = sc.nextInt();
        t1.input(h1, m1);

        // Input second time
        System.out.print("Enter second time (hours minutes): ");
        int h2 = sc.nextInt();
        int m2 = sc.nextInt();
        t2.input(h2, m2);

        // Add times
        t3.addTime(t1, t2);

        // Display result
        t3.display();
    }
}
Input:
Enter first time (hours minutes): 2 45 Enter second time (hours minutes): 3 30
Output: Total Time = 6 Hours 15 Minutes

Question 4: WAP to find sum of volumes of box and cylinder using following details:
In class Box
Member Member's Name Description
Member Variables double len, breadth, height, vol To store length, breadth, height and volume
Member Methods input(double l, bouble b, double h) To accept length, breadth and height
vol() To compute volume and store in variable vol

In class Cylinder
Member Member's Name Description
Member Variables double radius, height, vol To store radius, height and volume
Member Methods input(double r, double h) To accept radius, height
vol() To compute volume and store in variable vol

In class Computevol
Member Member's Name Description
Member Methods Addvol( Box v1,Cylinder v2) To add volume of two different object and display it
main() To call Addvol() method.

Solution: 


import java.util.Scanner;

class Time
{
    int hr, min;

    // Method to accept time
    void input(int h, int m)
    {
        hr = h;
        min = m;
    }

    // Method to add two time objects
    void addTime(Time t1, Time t2)
    {
        min = t1.min + t2.min;
        hr = t1.hr + t2.hr;

        // Convert extra minutes into hours
        if(min >= 60)
        {
            hr = hr + (min/60);
            min = min % 60;
        }
    }

    // Method to display time
    void display()
    {
        System.out.println("Total Time = " + hr + " Hours " + min + " Minutes");
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        Time t1 = new Time();
        Time t2 = new Time();
        Time t3 = new Time();

        // Input first time
        System.out.print("Enter first time (hours minutes): ");
        int h1 = sc.nextInt();
        int m1 = sc.nextInt();
        t1.input(h1, m1);

        // Input second time
        System.out.print("Enter second time (hours minutes): ");
        int h2 = sc.nextInt();
        int m2 = sc.nextInt();
        t2.input(h2, m2);

        // Add times
        t3.addTime(t1, t2);

        // Display result
        t3.display();
    }
}import java.util.Scanner;

class Box
{
    double len, breadth, height, vol;

    void input(double l, double b, double h)
    {
        len = l;
        breadth = b;
        height = h;
    }

    void vol()
    {
        vol = len * breadth * height;
    }
}

class Cylinder
{
    double radius, height, vol;

    void input(double r, double h)
    {
        radius = r;
        height = h;
    }

    void vol()
    {
        vol = 3.14 * radius * radius * height;
    }
}

class Computevol
{
    void Addvol(Box v1, Cylinder v2)
    {
        double sum = v1.vol + v2.vol;

        System.out.println("Volume of Box = " + v1.vol);
        System.out.println("Volume of Cylinder = " + v2.vol);
        System.out.println("Sum of Volumes = " + sum);
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        Box b = new Box();
        Cylinder c = new Cylinder();
        Computevol obj = new Computevol();

        // Input for Box
        System.out.println("Enter length, breadth and height of box:");
        double l = sc.nextDouble();
        double br = sc.nextDouble();
        double h1 = sc.nextDouble();

        b.input(l, br, h1);
        b.vol();

        // Input for Cylinder
        System.out.println("Enter radius and height of cylinder:");
        double r = sc.nextDouble();
        double h2 = sc.nextDouble();

        c.input(r, h2);
        c.vol();

        // Add volumes
        obj.Addvol(b, c);
    }
}
Input:
Enter length, breadth and height of box:5 4 3 Enter radius and height of cylinder: 2 7
Output: Volume of Box = 60.0 Volume of Cylinder = 87.92 Sum of Volumes = 147.92

Question 5: Write a Ticket class as given in chapter 2. Create an object of Ticket class. Call its setMoney() method. Check the balance with a call to getBalance(). Now call setMoney() and getBalance() again to ensure that the new balance is the sum of the two amounts passed to the two calls to setMoney().

Solution: 


class Ticket { private double balance; // Method to add money void setMoney(double amount) { balance = balance + amount; } // Method to display balance double getBalance() { return balance; } } class Demo { public static void main(String args[]) { Ticket t = new Ticket(); // First deposit t.setMoney(100); System.out.println("Balance after first deposit = " + t.getBalance()); // Second deposit t.setMoney(50); System.out.println("Balance after second deposit = " + t.getBalance()); } }

Input:
100 200
Output: Balance after first deposit = 100 Balance after second deposit = 300

Question 7: Write a class named Display, which call a method Convert of another class named Temperature. The method take a Celsius temperature value as an argument and then returns the equivalent Fahrenheit value. For reference, the formula is given below.
Fahrenheit= 18×Celcius +32.0

Solution: 
import java.util.Scanner;
class Temperature
{
    double Convert(double celsius)
    {
        double fahrenheit;
        fahrenheit = 1.8 * celsius + 32.0;
        return fahrenheit;
    }
}

class Display
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        Temperature t = new Temperature();

        System.out.println("Enter temperature in Celsius:");
        double c = sc.nextDouble();

        double f = t.Convert(c);

        System.out.println("Temperature in Fahrenheit = " + f);
    }
}
Input:
Enter temperature in Celsius: 25
Output: Temperature in Fahrenheit = 77.0

Question 8: Create a class Distance. The class should have method to accept distance as parameter in inches and feet. Another method in the class should convert the total distance into centimeters and display it.

Solution: 
import java.util.Scanner;

class Distance
{
    int feet, inches;
    double cm;

    // Method to accept distance
    void input(int f, int i)
    {
        feet = f;
        inches = i;
    }

    // Method to convert and display distance in centimeters
    void convert()
    {
        int totalInches = (feet * 12) + inches;
        cm = totalInches * 2.54;

        System.out.println("Distance in centimeters = " + cm);
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        Distance d = new Distance();

        System.out.println("Enter feet:");
        int f = sc.nextInt();

        System.out.println("Enter inches:");
        int i = sc.nextInt();

        d.input(f, i);
        d.convert();
    }
}
Input:
Enter feet: 5 Enter inches: 8
Output: Distance in centimeters = 172.72

Question 9: Create a class Distance. The user input distance in meters and centimeters as parameter to a method, which should covert the total distance into centimeters as well as feet and display the result.

Solution: 
import java.util.Scanner;

class Distance
{
    int meter, centimeter;
    double totalCm, feet;

    // Method to accept distance
    void input(int m, int cm)
    {
        meter = m;
        centimeter = cm;
    }

    // Method to convert and display
    void convert()
    {
        totalCm = (meter * 100) + centimeter;
        feet = totalCm / 30.48;

        System.out.println("Total distance in centimeters = " + totalCm);
        System.out.println("Total distance in feet = " + feet);
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        Distance d = new Distance();

        System.out.println("Enter distance in meters:");
        int m = sc.nextInt();

        System.out.println("Enter distance in centimeters:");
        int cm = sc.nextInt();

        d.input(m, cm);
        d.convert();
    }
}
Input:
Enter distance in meters:5 Enter distance in centimeters:50
Output: Total distance in centimeters = 550.0 Total distance in feet = 18.04461942257218

Question 10: Write a class Multiply, which has method to accept an object of class Test, and a number. The method should multiply the data members of Test by that number. Display the values of data members of Test before and after call to the method.

public class Test{
    private int test1;
    private int test2;
    public Test(int t1, int t2){
        test1=t1;
        test2=t2;
    }
}

Solution: 
class Test
{
    private int test1;
    private int test2;

    public Test(int t1, int t2)
    {
        test1 = t1;
        test2 = t2;
    }

    // Method to display values
    void display()
    {
        System.out.println("Test1 = " + test1);
        System.out.println("Test2 = " + test2);
    }

    // Method to multiply values
    void multiplyValues(int n)
    {
        test1 = test1 * n;
        test2 = test2 * n;
    }
}

class Multiply
{
    // Method to accept object and number
    void multiply(Test t, int n)
    {
        t.multiplyValues(n);
    }

    public static void main(String args[])
    {
        Test obj = new Test(10, 20);

        Multiply m = new Multiply();

        System.out.println("Before Multiplication:");
        obj.display();

        m.multiply(obj, 5);

        System.out.println("After Multiplication:");
        obj.display();
    }
}
Input:
10 20 5
Output: Before Multiplication: Test1 = 10 Test2 = 20 After Multiplication: Test1 = 50 Test2 = 100

Question 11: Define class Demo with integer type data marks. Write the following methods: 
  1. Method to accept an object of the Demo type and compare the values in argument with current object. Display the larger of the two.
  2. Method to accept an object of the Demo type and calculate and return average marks.

Solution: 
import java.util.Scanner;
class Demo
{
    int marks;

    // Constructor
    Demo(int m)
    {
        marks = m;
    }

    // Method to compare marks
    void compare(Demo d)
    {
        if(marks > d.marks)
            System.out.println("Larger Marks = " + marks);
        else
            System.out.println("Larger Marks = " + d.marks);
    }

    // Method to calculate average
    double average(Demo d)
    {
        return (marks + d.marks) / 2.0;
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter first marks:");
        int m1 = sc.nextInt();

        System.out.println("Enter second marks:");
        int m2 = sc.nextInt();

        Demo d1 = new Demo(m1);
        Demo d2 = new Demo(m2);

        d1.compare(d2);

        double avg = d1.average(d2);

        System.out.println("Average Marks = " + avg);
    }
}
Input:
Enter first marks: 80 Enter second marks: 60
Output: Larger Marks = 80 Average Marks = 70.0 Test2 = 20 After Multiplication: Test1 = 50 Test2 = 100

Question 12: Define class Student with the following specifications: 
Private Member Description
rollno 2 digit roll number
rollno 2 digit roll number
name 20 characters
marks1 total marks in test1
marks2 total marks in test2
average average marks obtained
public members Description
set() method to accept values for data members and to invoke getavg()
getavg() method to compute average marks obtained in 2 tests
display() method to display all data members


Solution: 
import java.util.Scanner;

class Student {
    // Private data members
    private int rollno;
    private String name;
    private int marks1;
    private int marks2;
    private double average;

    // Method to accept values and call getavg()
    public void set() {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter Roll Number (2 digits): ");
        rollno = sc.nextInt();

        sc.nextLine(); // consume newline

        System.out.print("Enter Name: ");
        name = sc.nextLine();

        System.out.print("Enter Marks in Test 1: ");
        marks1 = sc.nextInt();

        System.out.print("Enter Marks in Test 2: ");
        marks2 = sc.nextInt();

        // Calculate average
        getavg();
    }

    // Method to compute average marks
    public void getavg() {
        average = (marks1 + marks2) / 2.0;
    }

    // Method to display all data members
    public void display() {
        System.out.println("\nStudent Details");
        System.out.println("-------------------");
        System.out.println("Roll Number : " + rollno);
        System.out.println("Name        : " + name);
        System.out.println("Marks Test1 : " + marks1);
        System.out.println("Marks Test2 : " + marks2);
        System.out.println("Average     : " + average);
    }

    // Main method
    public static void main(String[] args) {
        Student s = new Student();

        s.set();
        s.display();
    }
}
Input:
Enter Roll Number (2 digits): 12 Enter Name: Rahul Enter Marks in Test 1: 78 Enter Marks in Test 2: 86
Output: Student Details ------------------- Roll Number : 12 Name : Rahul Marks Test1 : 78 Marks Test2 : 86 Average : 82.0

Question 13: Write a pure method in Java thatr takes an English word as parameter and returns the sum of number value of alphabet. With A starts from 1 and Z ends on 26.

Solution: 
class AlphabetSum {

// Pure method to calculate alphabet value sum
public static int getAlphabetSum(String word) {
int sum = 0;

word = word.toUpperCase();

for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);

if (ch >= 'A' && ch <= 'Z') {
sum += (ch - 'A' + 1);
}
}

return sum;
}

// Main method
public static void main(String[] args) {
String word = "JAVA";

int result = getAlphabetSum(word);

System.out.println("Word : " + word);
System.out.println("Alphabet Sum : " + result);
}
}

Input:
JAVA
Output: Word : JAVA
Alphabet Sum : 34

Question 14: WAP to generate 20 unique random numbers within range of 1 to 100.

Solution: 
class UniqueRandomNumbers {
    public static void main(String[] args) {

        int count = 0;

        System.out.println("20 Random Numbers:");

        while (count < 20) {

            int num = (int)(Math.random() * 100) + 1;

            System.out.print(num + " ");

            count++;
        }
    }
}
Output:
20 Random Numbers: 45 12 78 3 91 56 24 67 89 14 39 72 8 50 99 31 63 5 81 27

Read also:
👉Chapter- 1: Revision of Class IX Syllabus
👉Chapter- 2:Class as the Basis of all Computation

Comments

Popular posts from this blog

Introduction to Object Oriented Programming in Java

Important Java Programs for Beginners | Grade, Fibonacci, Armstrong, Pattern & More

Object Modelling – Entities and Their Behaviour in Java