Skip to main content

ProwessApps

Learn · Practice · Excel

Define a class named Test with an instance variable num. Define a Constructor and a method named getReverse(). Create an object of the class pass an integer to the constructor to initialize num. Call getReverse() to get the reverse and print the reverse no.

Java Code Example — OOP Programs

ADVERTISEMENT

Define a class named Test with an instance variable num. Define a Constructor and a method named getReverse(). Create an object of the class pass an integer to the constructor to initialize num. Call getReverse() to get the reverse and print the reverse no.

Objective

Write a Java program to initialize a number via a constructor and reverse it using a class method.

Algorithm / Approach

  1. Create a class Test with an instance variable x.
  2. Define a parameterized constructor that accepts an integer and assigns it to x.
  3. Define a method getReverse() that uses a while loop to extract digits from x, build the reversed number, and return it.
  4. In main, prompt the user for a number.
  5. Pass the number into the constructor when instantiating the Test object.
  6. Call getReverse() and print the result.
Test.java
import java.util.Scanner;
class Test {
 int x;
 Test(int num){
  x = num ;
 }
 int getReverse() {
  int temp, rev =0;
  while(x != 0) {
   temp = x%10;
   rev = rev *10+temp;
   x = x/10;
  }
  return rev;
 }
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Num: ");
  int x = s.nextInt();
  Test t = new Test(x);
  int res = t.getReverse();
  System.out.print("Reverse = "+res);
 }
}

Expected Output

Enter Num: 15465
Reverse = 56451

Explanation of the Program

  • This program demonstrates how constructors are used to set the initial state of an object immediately upon creation.
  • By the time getReverse() is called, the object already "knows" its number because the constructor stored it in the instance variable x.
  • Reversing a number involves repeatedly taking the last digit using modulo 10 (% 10) and adding it to the reversed value multiplied by 10.

Complexity

Time Complexity O(log10(N)) - Where N is the number being reversed.
Space Complexity O(1)
ADVERTISEMENT