What does System.in.read actually return? - java

What does :
System.in.read()
return ? The documentation says :
Returns:
the next byte of data, or -1 if the end of the stream is reached.
But for example if I enter : 10 I get back 49 . Why is that ?

49 is the ASCII value of the char 1. It is the value of the first byte.
The stream of bytes that is produced when you enter 10Enter on your console or terminal contains the three bytes {49,48,10} (on my Mac, may end with 10,12 or 12 instead of 10, depending on your System).
So the output of the simple snippet
int b = System.in.read();
while (b != -1) {
System.out.println(b);
b = System.in.read();
}
after entering a 10 and hitting enter, is (on my machine)
49
48
10

System.in.read() reads just one byte.
49 is the Unicode point value for 1.
Try to print:
System.out.println((char)49);
This will help you to understand it more.

When you enter 10, it is not read as an integer but as a String or, more precisely here, an array of bytes.
49 is the ASCII code for the character 1.

Related

Java unable to read signed negative bytes written to standard out

I have 2 classes, the first is fed a binary string of 1s and 0s to standard in, and splits the string into sub strings of length 8 to convert to bytes, to write to standard out like so:
byte b = (byte)Integer.parseInt(byteString, 2);
System.out.write(b);
System.out.flush();
The second is piped the output of the first, and ultimately will turn the bytes back into the long binary string, but currently I have it just doing this:
int next;
while((next = System.in.read())!=-1){
System.out.print(next); System.out.print(" ");
System.out.flush();
}
If I replace System.out.write(b); with System.out.print(b); System.out.print(" "); in the first class with some small sample input, the output is -80 -84 83 11 98 -116 53 -119 49 27 10 -80 -72 104 -123 0
If I pipe this output to the second class it outputs 63 63 83 11 98 63 53 63 49 27 13 10 63 63 104 63 0 13 10
Two things seem to be happening that I can't figure out why, System.in.read() is returning 63, which is ASCII for ? when reading bytes that would be signed negative, and a carriage return + new line has been added to the end. I am stumped for solutions, insight is greatly appreciated.
Note: I was running this in Windows 10 powershell, but on normal command line and in a linux terminal the behaviour was as expected, so problem is only in powershell!
I do not use powershell, but a small test shows that pipes do change the output, like adding a newline and carriage return at the end, or converting the byte 0xA2 to 0x3f ('?').
Searching the net I found Understanding the Windows PowerShell Pipeline. I did not read more than the first paragraph, but that contains a hint:
Piping works virtually everywhere in Windows PowerShell. Although you see text on the screen, Windows PowerShell does not pipe text between commands. Instead, it pipes objects.
Maybe this helps: What exactly does the pipe | mean in PowerShell?
int next;
while((next = System.in.read())!=-1){
System.out.print(next); System.out.print(" ");
System.out.flush();
}
Bytes are signed in Java, and so is the result of InputStream.read(). Try this:
int next;
DataInputStream in = new DataInputStream(System.in);
for (;;)
{
try
{
next = in.readUnsignedByte();
System.out.print(next); System.out.print(" ");
System.out.flush();
}
catch (EOFException exc)
{
break;
}
}

System.in.read using my char value as an int? [duplicate]

What does :
System.in.read()
return ? The documentation says :
Returns:
the next byte of data, or -1 if the end of the stream is reached.
But for example if I enter : 10 I get back 49 . Why is that ?
49 is the ASCII value of the char 1. It is the value of the first byte.
The stream of bytes that is produced when you enter 10Enter on your console or terminal contains the three bytes {49,48,10} (on my Mac, may end with 10,12 or 12 instead of 10, depending on your System).
So the output of the simple snippet
int b = System.in.read();
while (b != -1) {
System.out.println(b);
b = System.in.read();
}
after entering a 10 and hitting enter, is (on my machine)
49
48
10
System.in.read() reads just one byte.
49 is the Unicode point value for 1.
Try to print:
System.out.println((char)49);
This will help you to understand it more.
When you enter 10, it is not read as an integer but as a String or, more precisely here, an array of bytes.
49 is the ASCII code for the character 1.

Why is '0' + 1 or '1' + 1 result in a different number? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm studying for an exam and was wondering why the follow ' number ' code statements result in a number that completely different.
public class HelloWorld{
public static void main(String []args){
System.out.println('1' + 1); // prints 50
System.out.println('2' + 1); // prints 51
System.out.println('2'); // prints 2
}
}
When you say '1' and you add 1, the values are promoted to int before adding (binary numeric promotion). 1 has the ASCII value 49, so 49 + 1 = 50, and 2 has the ASCII value 50, so 50 + 1 = 51.
However, if you don't add, then the println method that takes a char is called, and '2' is printed.
http://www.asciitable.com/
The ASCII value for 1 is 49, so when doing System.out.println('1' + 1);, the char '1' is first converted to its ASCII value (49) and then 1 is added, resulting in 50.
In the last example, there is no addition, so the character is not converted to its integer representation.
Likewise, you could add 'f' and 1:
System.out.println('f' + 1); // prints: 103
System.out.println('1' + 1);
Java will see an arithmetic operation and try to print the result of that operation. Therefore, Java will convert the char '1' into the ASCII code value which is 49. 49 + 1 = 50 so it prints "50"
System.out.println('2');
There is no arithmetic here so it just prints the char
First '2'+1 equals to 51 ,not 50.
The number inside the singlequates is represents as an ascii value and its not the real number. The ascii of 1 is 49 , 49 and 1 equals 50.Check the ascii code here
In addition to all above answers.
When you type System.out.println('2'); //It just prints the string 2.
Refer http://www.newebgroup.com/academy/tables/ascii.htm for detailed ascii values.
When you use single quotes, '1', Java parses this as a char type. When you perform an operation on a char type with an int, Java will take the decimal value of that char and use it for the operation. Using an ASCII Table you can see the ascii value for '1' is 49 (and '2' is 50), so adding 1 you get 50 and 51 respectively. System.out.println will then print out the int result.
When you use System.out.println('2'), it will print out the char ascii value, which is why you get 2.
'1' indicates a character and it ASCII value is 49.
It is added to 1 so you got 50.
In the last case you dont add anything to char , so println prints 2
System.out.println('1' + 1); // prints 50
System.out.println('2' + 1); // prints 51
System.out.println('2'); // prints 2
When your parameter is being parsed, it will assume the entire expression should of type int. Therefore, it will convert the char '1' to its ASCHII value (int value), which is 49. Therefore 49 + 1 = 50.
Similarly, '2' == 50 so 50 + 1 = 51.
However, when you pass just the '2' as a parameter, it will simply print the char as is, because it has no reason to be parsed into an int, like in the other cases.

ASCII value related query

I read that "When an integer is cast into a char, only its lower 16 bits of data are used; the other part is ignored". Based on this shouldn't i get the char value for '0041' as output.Instead i get 'A' as output ,which has an ASCII value of 65. Why does this happen??
public class practice {
public static void main(String[] args) {
char ch = (char)0XAB0041;
System.out.println(ch);
char ch1= (char)65.25;
System.out.println(ch1);
}
}
Will i get the same output if i myself consider only the lower 16 bits for casting.As below:
char ch = (char)0041;
System.out.println(ch);
Guys could anyone clear this problem that i am facing in comprehending the relation between unicode,ASCII and hexadecimal values...
Thanks..
0x0041 is decimal 65 which is ASCII 'A'.
65.25 would be truncated to 65, so it's still 'A'.
What were you expecting?
0XAB0041 in decimal is:
11206721
in binary, it becomes:
101010110000000001000001
So taking last 16 bits,
we have: 0000000001000001=65 in decimal
If you see the ASCII table in this link, it is for 'A'
Hence, 0XAB0041 on casting to char, becomes 'A'
If you consider
char ch = (char)0041;
System.out.println(ch);
0041 is taken by java as octal literal with decimal value 4*8+1=33.So ASCII code for 33 decimal is !.
Hence the output will be:
!
Hence if you ask "Will i get the same output if i myself consider only the lower 16 bits for casting.", your answer is !(not) :)
You are dealing with 0x41 which is 65(16 * 4 + 1) in decimal system. 'A' corresponds to ascii 0x41.

Java - InputStream .read() function

If I use int oneByte = dis.read(byteArray, 0, 1) does this mean I am reading only 1 byte and I am assigning its decimal value to integer oneByte?
If I want to check for | (pipe) character to break out of a loop can I do something like this:
while((oneByte = dis.read(byteArray, 0, 1)) != 124)
If I use int oneByte = dis.read(byteArray, 0, 1) does this mean I am
reading only 1 byte and I am assigning its decimal value to integer
oneByte?
Nope. You're reading up to 1 bytes into byteArray and receiving the number of bytes read in oneByte. Perhaps you'd prefer:
int oneByte = dis.read();
Also be careful because you'll get the integer value...not a decimal. Keep in mind that it will return -1 when you reach the end of the stream.
If I want to check for | (pipe) character to break out of a loop can I
do something like this: while((oneByte = dis.read(byteArray, 0, 1)) !=
124)
You'll need to also check for the end of stream (-1). Try something more like this:
while(true) {
int oneByte = dis.read();
if(oneByte == -1 || oneByte == '|') {
break;
}
}
No, it means you are trying to read 1 byte and you are assigning the number of bytes actually read to oneByte. So oneByte cannot be greater than 1 in this case. If you want to check for the "|" char you have to do:
dis.read(byteArray, 0, 1);
while(byteArray[0] != 124) {
dis.read(byteArray, 0, 1);
}
As Matthew says in a comment, you should read the API.
The read() method is overloaded. Without arguments, it does what you want. With the arguments you're passing, it returns the number of characters read.
Make sure you check for EOF (-1) too.
No. oneByte = dis.read(byteArray,0,1); The 0 means you're reading from an offset of 0 (so if you haven't read anything from the stream yet this will be the beginning of the stream), the 1 means you want to read up to 1 byte, the byteArray is the array into which you're reading and the return value assigned to oneByte is the number of bytes read (since if your stream contains fewer bytes than you tried to read this number would be less than the len parameter).
You can break on pipe by using the read() method:
while(dis.read() !- 124)
dis.read(buffer) will return as result the numbers of bytes read.
dis.read() will read ONE single byte and return it's value as integer (0 to 255)
The while loop should be like this to do what you want:
while ((oneByte = dis.read()) != 124)
If you check the Java API for InputStream, you'll see that the 'return' value for InputStream.read(byte[], int, int) is described as:
the total number of bytes read into the buffer, or -1 if there is
no more data because the end of the stream has been reached.
So, no. You're reading one byte and storing into byteArray[0]. OneByte will be -1, 0 or 1. Breaking your loop will not work in this scenario. But, for the record, if you really only need one byte at a time, the InputStream.read() method will do the trick.
You also, for readability's sake, may want to check against the exact character you're looking for. So:
while (stream.read()!='|'){
//stuff
}
This way, anyone who reads your code (future coders, graders, etc.) will immediately know "Oh, it breaks on a Pipe Character".

Categories