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
- Create a class
Testwith an instance variablex. - Define a parameterized constructor that accepts an integer and assigns it to
x. - Define a method
getReverse()that uses a while loop to extract digits fromx, build the reversed number, and return it. - In
main, prompt the user for a number. - Pass the number into the constructor when instantiating the
Testobject. - 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 variablex. - 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)