Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting random verbiage while printing array variable in Java

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?

like image 450
mishsx Avatar asked Mar 27 '26 07:03

mishsx


1 Answers

  1. Don't import arbitrary stuff coming into you mind. You don't use anything from the packages java.io, java.math, java.security, java.text, java.util.concurrent, or java.util.regex. The only thing needing an import in your code so far is java.util.Scanner

  2. You don't need a construct like scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"). If you are going to read another token, which does not happen in you code anyway, the scanner will already skip white-space, including line breaks, by default. There's also scanner.nextLine(), but you don't need it here.

  3. Do not close System.in. While a Scanner created around a resource allocated by yourself should be closed, you are not responsible for System.in.

  4. System.out.println(Object) prints the result of calling toString() on the object. For classes not providing an implementation, like arrays, the method inherited from java.lang.Object produces getClass().getName() + "@" + Integer.toHexString(hashCode()). The int[] array's class name is [I, that's why you see [I@ plus some hex number.

    Use System.out.println(Arrays.toString(binary)); instead. But this will print the entire array, including the unused elements.

  5. Instead of modifying an existing variable in a loop, creating the need for a new variable in the outer scope, you should introduce a new changeable, temporary variable in the loop. Further, you have to become familiar with the standard loop idiom, start at index zero and exclude the end index (use < rather than <=).

    The loop variable will contain the excluded end index after the loop, when the condition evaluated to false. This logic also applies to your first while loop; afterwards, i will contain the first unused the index or the used length, both interpretations are valid. Subsequent uses must exclude it, using <, which is, as said, the usual pattern. For your reversal loop, this also implies that the end index must be decremented before being used.

    Fixing the loop logic will fix your issue with the leading zero.

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String args[]) {
        int n = scanner.nextInt();
        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++;
        }
        /*Reversing the binary[] to get the correct binary value.*/
        for(int j=0, k=i-1; j<k; j++,k--) {
            int temp=binary[j];
            binary[j]=binary[k];
            binary[k]=temp;
        }
        /*Printing out all the bits of binary number. */
        for(int l=0; l<i; l++) {
            System.out.print(binary[l]);
        }
        System.out.println();

        System.out.println(Arrays.toString(binary));
    }
}
25
11001
[1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
like image 59
Holger Avatar answered Mar 29 '26 22:03

Holger