Create a class having one 3-digit number and display the reverse of that number

In this program, we have created a class Reverse having data member num and one method called calReverse( ). In main( ) method we then created the object of Reverse class and call the method calReverse( ). Remember we have passed the value 786 in Reverse's constructor call. In below program Resverse(int n) { } is called a parameterized constructorConstructor is a special type of method which enables to initialize an object when it is first created. It has the same name as the class name in which it is declared. It does not specify a return type not even void. 

It has following syntax:
// Default constructor
constuctor-name( ) {
    //Initialize statements


// Parameterized constructor
constuctor-name(parameter list) {
    //Initialize statements

class Reverse {

 int num;
 Reverse(int n) {
  num = n;
 void calReverse() {
  int rev=0;
  System.out.print("Reverse of number " + num + " is = ");
  while(num > 0) {
   rev = rev * 10 + (num % 10);
 public static void main(String[] args) {
  Reverse r1 = new Reverse(786);
C:\>java Reverse
Reverse of number 786 is = 687

No comments:

Post a comment