Search code examples
javagarbage

Java outputs garbage?


import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;


public class Main {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub

        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter output = new PrintWriter(System.out);

        String st="";
        String st1; 
        String st2;

        while((st1 = input.readLine()) != null)
        {
            char[] x1 = st1.toCharArray();
            st2 = input.readLine();
            char[] x2 = st2.toCharArray();
            Arrays.sort(x1);
            Arrays.sort(x2);
            st1 = x1.toString();
            st2 = x2.toString();
            output.print(st1.charAt(0));
            output.flush();
        }

        }
    }

input can be any two strings. the problem is that this code outputs garbage value, so, what is the wrong with this ? NOTE: this is a partial code debugging, the rest of the code is not attached.


Solution

  • x1.toString() calls the toString() method on the x1 array.

    Which returns something like [C@33909752. Which is the value returned by the Object.toString() method.

    [ - it's an array
    C - of type `char`
    33909752 - on memory address `33909752`
    

    If you want to build a String based on the characters in array x1 you must use new String(x1).