M
M
MGNeo2018-11-08 08:37:07
Java
MGNeo, 2018-11-08 08:37:07

Strange behavior with array initialization in Java?

I have come across some very strange behavior in Java .
According to the Java specification, when an array is created, its elements must be initialized with default values. For elements of type byte , the default value is 0 .
Consider the code on which I was able to reproduce the strange behavior:

package javatest;

import java.io.*;

public class JavaTest 
{   
    public static void main(String[] args) throws IOException
    {
        byte[] buf = new byte[5];
        
        System.in.read(buf);
        
        for (int i = 0; i < buf.length; ++i)
        {
            System.out.println((char)buf[i]);
        }
    }
}

Strange behavior begins with the following sequence of actions:
1) Enter 1 , poke Enter , the program correctly displays 1 and ends;
2) Run the program again (I run it from NetBeans IDE ), type 12345 , hit Enter , the program displays 12345 correctly and exits;
3) Run the program again, enter 123456 , poke Enter , the program displays garbage and ends;
4) The next few launches of the program with the input of any data lead to the fact that garbage is displayed - in some cases not everything is displayed, in others - what was not entered.
5be3d3a7568c8610323123.jpeg
Maybe I don't understand something? It seems to me that this should not be.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question