I'm learning basics of Java and there seems to be an observation I'm not able to get my head around.
Below is the code that is supposed to print the binary implementation of a base10 number. There are no errors or warnings but logical anomalies I'm looking for answers.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Main
{
private static final Scanner scanner = new Scanner(System.in);
public static void main(String args[]) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int remainder, quotient, i=0;
int[] binary=new int[n];
/* Binary division -Extracting the 1's and 0's out of the base10 number and storing it in binary[] */
while(n!=0){
remainder=n%2;
quotient=n/2;
binary[i]=remainder;
n=quotient;
i++;
}
int k=i; // For storing the length of array till I want my bits to be reversed since all other bits are initialized to 0.
/*Reversing the binary[] to get the coreect binary value.*/
for(int j=0; j<=i; j++){
int temp=binary[j];
binary[j]=binary[i];
binary[i]=temp;
i--;
}
/*Printing out all the bits of binary number. */
for(int l=1;l<=k;l++){
System.out.print(binary[l]);
}
System.out.println(binary); /*Prints a garbage looking value: For ex- for 25 i get: [I@33909752 */
scanner.close();
}
}
Concerns for my code:
1. I am not able to comprehend possible reasoning as to why I am getting random garbage looking verbiage when I try to print the array variable - binary. Is this something expected? If so what is this?
For example:
In my code when I provide an input of 25 I get [I@33909752 while printing the binary variable. I expected something like an [1,1,0,0,1,0,....,0]
2. I get an extra 0 in front of my binary value if I start my for-loop to print the binary from 0 instead of 1
For example:
for(int l=1;l<=k;l++)
{
System.out.print(binary[l]);
}
Prints 11001 for 25 but if I start the loop from 0, I get 011001. I checked all other places of the code by putting SOPLn statements and nowhere the 0 index of array is getting 0. I wonder why?