IOStream writing data to console - java

I have read that only lower order 8 bits are used while Output of byte output stream, then why I am getting 5?
Also, why I am not getting the binary or hex format of 65?
If I delete the leading 2 zeros and make the value of b as 65 then I get 'A' as the answer but why by placing leading 2 zeros I am not getting the answer but '5'?
Also why I am getting the answer as a character and not in binary format as 'out' is a Byte OutputStream object and should write in bytes?
public static void main(String[] args) {
int b = 0065;
System.out.write(b);
System.out.flush();
}
desired 'A', actual 5?
Also, desired 0100 0001.

Static field out in class java.lang.System has type java.io.PrintStream.
Class PrintStream has several write() methods. In your code, the argument you are passing to method write() is an int, hence the method invokde is write(int). You are assigning a number literal to your local variable b. In java, a number literal that begins with a zero (0) indicates an octal number and 65 in octal is 53 (fifty-three) in decimal and 53 is the ASCII code for the digit 5 (five). For your information, class java.lang.Integer has static method toBinaryString(). I suggest you look at the javadoc for that method.

public class StackOverFlow{
public static void main(String []args){
int x = 0065;// in java when you append zero like 011 or 0023 its take as octal number,when you print it will convert to decimal
System.out.println(x); // 0065 is octal value when you convert to decimal it will be 53 and in hexa 35
int y = 056;//octal value
System.out.println(y); // Output:46 decimal value
}
}

Because 0065 is octal for decimal 53 for hexadecimal 0x35 for the ASCII character 5.

Related

"The literal 0008 of type int is out of range" [duplicate]

I am trying to write following code.but it gives me error kindly help me.
int six=06;
int seven=07;
int abc=018;
int nine=011;
System.out.println("Octal 011 ="+nine);
System.out.println("octal O18 =" + abc);
why i cant give 018 and 019 to variable.i can give value 020 and 021 to variable.
Why this happen? what's the reason behind this Kindly tell me.
I got Following error
integer number too large: 018
int eight=018;
Octal is base-8 number system, so it means digit can be from 0 to 7, you can't use digit 8 (and 9 too) in octal number system.
// Decimal declaration and possible chars are [0-9]
int decimal = 495;
// HexaDecimal declaration starts with 0X or 0x and possible chars are [0-9A-Fa-f]
int hexa = 0X1EF;
// Octal declaration starts with 0 and possible chars are [0-7]
int octal = 0757;
// Binary representation starts with 0B or 0b and possible chars are [0-1]
int binary = 0b111101111;
If the number is string format then you can convert it into int using the below
String text = "0b111101111";
int value = text.toLowerCase().startsWith("0b") ? Integer.parseInt(text.substring(2), 2)
: Integer.decode(text);
why i cant give 018 and 019 to variable.
Because an integer literal prefixed with 0 is treated as octal, and '8' and '9' aren't valid octal digits.
From section 3.10.1 of the JLS:
An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.
Trying to use '8' in an octal number is like trying to use 'G' in hex... it's simple not part of the set of symbols used in that base.
Octal numbers (base 8) can only use the following figures: 01234567. The same way that decimal numbers (base 10) can only use 0123456789.
So in octal representation, 17 + 1 is 20.
The prefix 0 indicates octal(8 base)(digits 0-7).
public class MainClass{
public static void main(String[] argv){
int intValue = 034; // 28 in decimal
int six = 06; // Equal to decimal 6
int seven = 07; // Equal to decimal 7
int eight = 010; // Equal to decimal 8
int nine = 011; // Equal to decimal 9
System.out.println("Octal 010 = " + eight);
}
}
why i cant give 018 and 019 to variable.i can give value 020 and 021 to variable.
The leading zero signifies an octal literal. However, 8 and 9 are not valid octal digits. This makes 018 and 019 invalid.
When an integer literal starts with 0 in Java, it's assumed to be in octal notation. The digits 8 and 9 are illegal in octal—the digits can range only between 0 and 7.
Because it's octal, an octal number has 8 digits which spans from 0 to 7 inclusive. For the same reason 12 would be an invalid binary number.
You need at least base 9 to have 18 and a normal decimal base for 19.
For your query.....you assign an invalid value to the variable....your assigned value is started with 0(zero) ..which means that you are assigning an octal value to the variable and when you assign a value higher then 7 such as 018 in your case...the value excedes the range of octal variables and hence show an error...so try entering simply 18 so it would take it as an integer rather than an octal variable data type...

How many bytes does a string contains?

public class ClassToTestSnippets {
private static ClassToTestSnippets ctts;
public static void main(String[] args) {
ctts = new ClassToTestSnippets();
ctts.testThisMethod();
}
public void testThisMethod() {
System.out.println("\u2014".length()); //answer is 1
}
}
Above code prints 1. But \u2014 is E2 80 94 i.e. 3 bytes. How do I know how many bytes does a string contains?
Depends. What encoding do you want to use?
System.out.println("äö".getBytes("UTF-8").length);
Prints 4, but if I change UTF-8 to ISO-8859-1 (for example), it'll print 2. Other encodings may print other values (try UTF-32).
Internally - it contains (number of chars) * 2 bytes, as each char in Java takes up two bytes (a normal character in Java is 16 bits unicode). The actual bytes are 0x20 and 0x14.
However, the length function returns the number of characters, not the number of bytes.

Compiler error "Incompatible types" on byte literal

I have seen many cases where a byte is declared but where the value from a method like
intToByte or StringToByte is casted to a byte because the programmer is provideing i.e. a hexadecimal- value, an Integer- or a String-value.
I am trying to assign an actual byte value to the variable without any casting or methods to parse, like so:
public class ByteTest {
/**
* This array will be used to hold three characters, together forming a string.
*/
private static byte[] string;
/**
* The main method of the program, where the byte-array is coming to use.
*/
public static void main(String args[]) {
//Construct the array with a limit to three bytes.
string = new byte[3];
/*
* Fill the three bytes with the binary values to create "O", "l" and "e".
*/
string[0] = 01001111;
string[1] = 01101100;
string[2] = 01100101;
//Print out "Ole".
System.out.println(string[0] + string[1] + string[2]);
}
}
But I get the following error in the compiler:
java\ByteTest.java:8: error: incompatible types: possible lossy conversion from int to byte
string[0] = 01001111;
^
java\ByteTest.java:9: error: incompatible types: possible lossy conversion from int to byte
string[1] = 01101100;
^
java\ByteTest.java:10: error: incompatible types: possible lossy conversion from int to byte
string[2] = 01100101;
^
Appearently, what I think of as eight bits, the compiler thinks of as eight integers.
Is there any other solution to this, where I can provide actually bits directly to the variables/array?
Indicate binary
string[0] = 0b01001111;
string[1] = 0b01101100;
string[2] = 0b01100101;
This reminds me of the joke: there are 10 kinds of programmers: those that understand binary and those that do not.
As bytes are signed there still is a problem with 0b1xxxxxxx which would need to be a negative number. In that case use the following trick:
string[2] = 0b11100101 - 256;
string[2] = (byte) 0b11100101; // Or simply cast the int range value.
Also binary is ideal for an underscore usage:
string[2] = 0b0110_0101; // 0x65
And is commented by #BackSlash: bytes are binary data. To interprete them as text they have to be associated with some Charset/encoding.
String s = new String(string, StandardCharsets.US_ASCII);
System.out.println(s);
This converts the bytes, interpreting them as ASCII to the Unicode that String uses (to combine all scripts of the world).
Adding 0 in front of constant number ( like 01101100 ) is interpreted as octal value
What do you need to do to fix this?
The simplest solution which will use the least memory (code and data) is also the simplest.
private static final String string = "Ole";
System.out.println(string);
otherwise you can do this
private static final char[] chars = {
(char) 0b01001111,
(char) 0b01101100,
(char) 0b01100101 };
String s = new String(chars);
System.out.println(s);
Note: characters in Java are 16-bit unsigned char, not 8 bit byte
To get an idea of why the class file is bigger you can dump the class file with
java -c -v -cp target/classes mypackage.MyClass
To start with 01001111 is in octal, not binary. To write a binary number, you need 0b01001111
Numbers don't "remember" how many leading zeros you gave it, and generally speaking, leading zeros are dropped when printed.
The default format for a number is decimal, not binary.
When you add two, or three numbers, you get another number. Assuming you got this to compile it would print something like
288
or whatever the sum of the values are.
BTW it is really confusing to name an int called "string" because this could be assumed to be a String
Assign Actual value :-
String a ="100101";
System.out.println(""+a);
Output :- 100101
Binary to integer conversion and then assign value to string variable :-
String a=""+0b100101
System.out.println(""+a);
Output: 37

Printing binary values in Java

Why the output of this java program is 8 and 9 while we try to print 010 and 011 respectively:
public class Test{
public static void main(String str[]){
System.out.println(011);
}
}
What is the reason?
In Java, the default conversion from integer to string is base 10. If you want a different radix, you have to specify it explicitly. For instance, you can convert an integer value to a binary string using:
Integer.toString(value, 2);
Similarly, you can convert it to an octal value with:
Integer.toString(value, 8);
Unless the value is 0, the string will not have a leading zero. If you want a leading 0, you'll have to prepend it. Alternatively, you can format it with String.format() and specify zero fill and a minimum width for the converted string:
String.format("%1$03o", value); // the "1$ in the format string is optional here
P.S. It's not clear from your question what the exact problem is. It sounds like it's that you are converting from an integer value to a string. However, if the problem is that you're trying to read the string "011" and it is being read as the integer value 9, this is because a leading 0 forces interpretation as an octal value. You'll have to read it as a String value and then explicitly specify the conversion from string to integer to be base 10:
int val = Integer.valueOf(stringValue, 10);
010 is interpretetion of 10 in octal base which is 8. And similarly 011 is interpretetion of 11 in octal base which is 9.
Prepending an integer with 0 makes it interpreted in octal base.
Similarly, you can try printing 0x10, which is a hexadecimal representation, and will give you 16 as output.
- If you want to convert the integer to binary data, use toBinaryString() method.
Eg:
int i = 8;
Integer.toBinaryString(i);
bec. when you start your number with 0 JVM convert the number from decimal to octal that's all ;)
"11 in decimal = 9 in octal"
decimal 0 1 2 3 4 5 6 7 8 9
octal 0 1 2 3 4 5 6 7 10 11

integer assigning in java

public class Example {
public static void main(String args[]) {
int a = 0153;
int b=a;
System.out.println(""+b);
}
}
Can someone explain why it prints 107 and not 153?
Octal of 107 is 0153
In Java you can create octal literals simply by adding a leading zero like this: int a = 0755; Be careful! It is very common to specify an octal literal
Because a number starting by 0 is considered as an octal value in Java. 0153 in octal is 107 in decimal.
You write as octal and print defaults to decimal.
Input Prints (decimal)
Decimal 153 153
^
No leading zero (digits 0-9)
Octal 0153 107
^
leading zero (digits 0-7)
Hex 0x153 339
^^
leading 0x (digits 0-F)

Categories

Resources