File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes What's wrong with the program? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What Watch "What New topic

What's wrong with the program?

Niyas Ahmed Sheikh
Ranch Hand

Joined: Jun 15, 2005
Posts: 129



In the above pgm, the byte array bb[0] - bb[9] will have a - j.
But I got the above output. I thought the output should be: abcdefghij

What's wrong with the program?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15094

Take out of the loop.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Manuel Moons
Ranch Hand

Joined: Mar 05, 2002
Posts: 229
The read(byte[]) command will try to read 10 bytes at once (because your byte[] is 10 bytes). It will try to read those 10 bytes and when the inputstream is at it's end it will return -1. If less then 10 bytes can be read the read method will return the amount that can be read.

So if you follow these rules you can see why your output can be unpredictable.

You'd better do something like this:

Choon-Chern Lim
Ranch Hand

Joined: Aug 29, 2005
Posts: 74
Instead of reading character by character, consider using bufferedReader to read the whole line.

I agree. Here's the link:
subject: What's wrong with the program?
It's not a secret anymore!