Java Program to find square and cube of a number using class and object


In this program, You will learn how to find square and cube of a number using class and object in Java.


9 = 3 * 3

27 = 3 * 3 * 3


Example: How to find square and cube of a number using class and object in Java

Run it Now
import java.util.Scanner;

class Test {

    int num, sq, cube;
    Scanner sc = new Scanner(System.in);

    void input() {
        System.out.print("Enter a number: ");
        num = sc.nextInt();
    }

    void findSquare() {
        sq = num * num;
        System.out.println("\nSquare is: " + sq);
    }

    void findCube() {
        cube = num * num * num;
        System.out.println("Cube is: " + cube);
    }
}

class Main {

    public static void main(String args[]) {

        Test obj = new Test();
        obj.input();
        obj.findSquare();
        obj.findCube();
    }
}

Output:

Enter a number: 3
Square is: 9
Cube is: 27