-3

Here is my problem. In the following code, I have a void type method, but inside this method, I can still find a return.

Also, in the recursion call, I can find this >> operator.

So there are my questions :

  • Why using a return in a void function ?
  • Whats number >> 1 does it mean ?
import java.util.Scanner;
class Code {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your Decimal value here : ");
        int num = sc.nextInt();
        printBinaryform(num);
        System.out.println();
    }
    private static void printBinaryform(int number) {
        int remainder;
        if (number <= 1) {
            System.out.print(number);
            return; // KICK OUT OF THE RECURSION
        }
        remainder = number % 2;
        printBinaryform(number >> 1);
        System.out.print(remainder);
    }
}
Maxime
  • 838
  • 6
  • 18
Lidan Suidan
  • 31
  • 1
  • 5
  • It doesn't return a value, or expect anything to be returned from the recursive call, so what's the problem? – jonrsharpe Apr 13 '19 at 07:48
  • @jonrsharpe i don't get if (number <= 1) { System.out.print(number); return; but not returning any value ? and here printBinaryform(number >> 1); what does ">>" do? – Lidan Suidan Apr 13 '19 at 07:57
  • Of course it's not returning any value, *it's a void function*. And see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html. SO isn't a tutorial service, I'd recommend finding a structured tutorial to run you through the basics of the language. – jonrsharpe Apr 13 '19 at 07:59
  • @jonrsharpe ohh, ok Thanks Bro :) – Lidan Suidan Apr 13 '19 at 08:05
  • As usual in these questions, there is no decimal here at all, apart from what the user enters. `Scanner.nextInt()` already does the decimal to binary conversion. What you're doing after that is anybody's guess. Unclear what you're asking, – user207421 Apr 13 '19 at 08:46

1 Answers1

0

In your code, the return; is used to leave the function. In an String function, we would have had the return keyword, follow by a String value, but in a void function return is just follow by nothing.

The >>operator is called a right shift. It is used for the bit shift. But this question already have an answer here :

What does “>>” mean in java

12 is 1100 in binary. A right shift (>> is the bitwise right shift operator) by one bit produces

1100 -> 0110

which comes out to be 6.

Thus we have that,

6 - 1 = 5

Community
  • 1
  • 1
Maxime
  • 838
  • 6
  • 18