Unexpected int/Integer behavior when number starts by 0 - java

I can't understand why this is not printing the expected value (400300) when I put extra zeros in front of the number:
System.out.println(new Integer(0400300)); // prints 131264
System.out.println(0400300); // prints 131264
If I put one or more zeros in front of the number, the expected value is not printed.
// JUnit test does not pass:
assertTrue(0400300 == 400300); // returns false!?

Adding 0 to the front made the number an Octal literal. So:
0400300 = 3 * 8 ^ 2 + 4 * 8 ^ 5 = 131264
See JLS for the relevant sections. Quote:
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.

Related

The width of a double variable

I am trying to write some text to a file using PrintWriter and I do not understand what "7" means in the next example:
double d = 12.11211;
out.format(“%7.3f”, d);
The source from where I am inspiring says that 7 means:
The 7.3 before the f denotes the width (7) and precision (3) to output
d in.
The problem is that I cannot understand what that width really means. I mean, even though my variable would have more than 7 digits, it is not going to format anything.
Think of it as the total length of the string produced by the applied format.
If you take in account that there will be exactly 3 chars after the decimal point and 1 char for the decimal point itself, then it leaves 3 chars for the integer part.
Because your number has only 2 digits in the integer part the final result will be padded at the left with a white space:
double d = 12.11211;
out.format("%7.3f", d);
will create:
" 12.112"
with
out.format("%8.3f", d);
you get
" 12.112"
and so on.
The minimum length of the formatted string is in your case:
6 = 2 chars for the integer part + 1 char for the decimal point + 3 chars for the digits after the decimal point
so even if you set:
out.format("%5.3f", d);
this will not truncate the result, it will be:
"12.112"
For simple text arguments, you can think of the width and precision as a minimum and maximum number of characters to be output. For floating-point numeric types, the precision changes meaning slightly and controls the number of digits displayed after the decimal point.
watch this example:
System.out.printf("String is '%5s'\n", "A");
// String is ' A'
System.out.printf("String is '%.5s'\n", "Happy Birthday!");
// String is 'Happy'
for more information look at this link
Your source of inspiration should be the javadoc. It says:
The width is the minimum number of characters to be written to the
output. If the length of the converted value is less than the width
then the output will be padded by ' ' ('\u0020') until the total
number of characters equals the width. The padding is on the left by
default.[...]
For the floating-point conversions 'a', 'A', 'e', 'E', and 'f' the precision is the number of digits after the radix point.
A simple experiment shows it:
System.out.printf("%7.3f%n", 1.3);
System.out.printf("%7.3f%n", 12.3);
System.out.printf("%7.3f%n", 12.34);
System.out.printf("%7.3f%n", 12.345);
System.out.printf("%7.3f%n", 12.3456);
System.out.printf("%7.3f%n", 12.34567);
System.out.printf("%7.3f%n", 12.34567);
System.out.printf("%7.3f%n", 123.34567);
System.out.printf("%7.3f%n", 1234.34567);
System.out.printf("%7.3f%n", 12345.34567);
prints:
1,300
12,300
12,340
12,345
12,346
12,346
12,346
123,346
1234,346
12345,346
By width, it means the string will always fill the rest of the places if the number of digits/characters of the value is less than the given number.
double d = 12.11211;
String.format(“%7.3f”, d);
> 12.112
^^^^^^^
1234567
According to this:
The field width in a formatting operator is a nonnegative integer that
specifies the number of digits or characters in the output when
formatting input values. For example, in the operator %7.3f, the field
width is 7.
By default, the output text is padded with space
characters when the field width is greater than the number of
characters.
The 7 adds padding () in case the output is smaller than 7 characters. This way the output is always at least 7 characters, with 3 floating decimals.
This documentation gives a very detailed explanation for formatting text in general, most of which is applicable cross-language.

"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 to convert large integer number to binary?

Sorry for a possible duplicate post, I saw many similar topics here but none was exactly I needed. Before actually posting a question I want to explicitly state that this question is NOT A HOMEWORK.
So the question is: how to convert a large integer number into binary representation? The integer number is large enough to fit in primitive type (Java long cannot be used). An input might be represented as a string format or as an array of digits. Disclaimer, This is not going to be a solution of production level, so I don't want to use BigInteger class. Instead, I want to implement an algorithm.
So far I ended up with the following approach:
Input and output values represented as strings. If the last digit of input is even, I prepend the output with "0", otherwise - with "1". After that, I replace input with input divided by 2. I use another method - divideByTwo for an arithmetical division. This process runs in a loop until input becomes "0" or "1". Finally, I prepend input to the output. Here's the code:
Helper Method
/**
* #param s input integer value in string representation
* #return the input divided by 2 in string representation
**/
static String divideByTwo(String s)
{
String result = "";
int dividend = 0;
int quotent = 0;
boolean dividendIsZero = false;
while (s.length() > 0)
{
int i = 1;
dividend = Character.getNumericValue(s.charAt(0));
while (dividend < 2 && i < s.length())
{
if (dividendIsZero) {result += "0";}
dividend = Integer.parseInt(s.substring(0, ++i));
}
quotent = dividend / 2;
dividend -= quotent * 2;
dividendIsZero = (dividend == 0);
result += Integer.toString(quotent);
s = s.substring(i);
if (!dividendIsZero && s.length() != 0)
{
s = Integer.toString(dividend) + s;
}
}
return result;
}
Main Method
/**
* #param s the integer in string representation
* #return the binary integer in string representation
**/
static String integerToBinary(String s)
{
if (!s.matches("[0-9]+"))
{
throw new IllegalArgumentException(s + " cannot be converted to integer");
}
String result = "";
while (!s.equals("0") && !s.equals("1"))
{
int lastDigit = Character.getNumericValue(s.charAt(s.length()-1));
result = lastDigit % 2 + result; //if last digit is even prepend 0, otherwise 1
s = divideByTwo(s);
}
return (s + result).replaceAll("^0*", "");
}
As you can see, the runtime is O(n^2). O(n) for integerToBinary method and O(n) for divideByTwo that runs inside the loop. Is there a way to achieve a better runtime? Thanks in advance!
Try this:
new BigDecimal("12345678901234567890123456789012345678901234567890").toString(2);
Edit:
For making a big-number class, you may want to have a look at my post about this a week ago. Ah, the question was by you, never mind.
The conversion between different number systems in principle is a repeated "division, remainder, multiply, add" operation. Let's look at an example:
We want to convert 123 from decimal to a base 3 number. What do we do?
Take the remainder modulo 3 - prepend this digit to the result.
Divide by 3.
If the number is bigger than 0, continue with this number at step 1
So it looks like this:
123 % 3 == 0. ==> The last digit is 0.
123 / 3 == 41.
41 % 3 == 2 ==> The second last digit is 2.
41 / 3 == 13
13 % 3 == 1 ==> The third digit is 1.
13 / 3 == 4
4 % 3 == 1 ==> The fourth digit is 1 again.
4 / 3 == 1
1 % 3 == 1 ==> The fifth digit is 1.
So, we have 11120 as the result.
The problem is that for this you need to have already some kind of division by 3 in decimal format, which is usually not the case if you don't implement your number in a decimal-based format (like I did in the answer to your last question linked above).
But it works for converting from your internal number format to any external format.
So, let's look at how we would do the inverse calculation, from 11120 (base 3) to its decimal equivalent. (Base 3 is here the placeholder for an arbitrary radix, Base 10 the placeholder for your internal radix.) In principle, this number can be written as this:
1 * 3^4 + 1 * 3^3 + 1*3^2 + 2*3^1 + 0*3^0
A better way (faster to calculate) is this:
((((1 * 3) + 1 )*3 + 1 )*3 + 2)*3 + 0
1
3
4
12
13
39
41
123
123
(This is known as Horner scheme, normally used for calculating values of polynomials.)
You can implement this in the number scheme you are implementing, if you know how to represent the input radix (and the digits) in your target system.
(I just added such a calculation to my DecimalBigInt class, but you may want to do the calculations directly in your internal data structure instead of creating a new object (or even two) of your BigNumber class for every decimal digit to be input.)
Among the simple methods there are two possible approaches (all numbers that appear here decimal)
work in decimal and divide by 2 in each step as you outlined in the question
work in binary and multiply by 10 in each step for example 123 = ((1 * 10) + 2) * 10 + 3
If you are working on a binary computer the approach 2 may be easier.
See for example this post for a more in-depth discussion of the topic.
In wikipedia, it is said:
For very large numbers, these simple methods are inefficient because
they perform a large number of multiplications or divisions where one
operand is very large. A simple divide-and-conquer algorithm is more
effective asymptotically: given a binary number, it is divided by
10^k, where k is chosen so that the quotient roughly equals the
remainder; then each of these pieces is converted to decimal and the
two are concatenated. Given a decimal number, it can be split into two
pieces of about the same size, each of which is converted to binary,
whereupon the first converted piece is multiplied by 10^k and added to
the second converted piece, where k is the number of decimal digits in
the second, least-significant piece before conversion.
I have tried, this method is faster than conventional one for numbers larger than 10,000 digits.

Why does 022 - 2 equal 16 in Java? [duplicate]

I am developing an application in Android using Eclipse. I wrote the following code and in tests the first and third "if" block is not reachable. Why?
When I add a leading zero to a number, the equal operator returns false.
int var = 123;
if (var == 0123) {
//not reachable
}
if (var == 123) {
//reachable
}
if (var == (int)0123) {
//not reachable
}
if (var == (int)123) {
//reachable
}
0123 is an octal number (leading 0), while 123 is a decimal number.
so 0123 actually equals to 83.
Any integer Number Leading With Zero is octal Number (base 8).
0123 is octal Number and 123 is Decimal Number
0123 = (3*8^0) +(2*8^1)+(1*8^2)+(0*8^4)
=3+16+64+0
=83
because 0123 in not decimal digit its octal (base 8)
so this is equal to 83
To convert a number k to decimal, use the formula that defines its base-8 representation:
0123 base-8 = 83 decimal
0123 = (3*8^0) +(2*8^1)+(1*8^2)+(0*8^4)
=3+16+64+0
=83
An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 and can represent a positive, zero, or negative integer.
Note: Octal values are denoted in java by leading zero normal decimal number cannot have a leading zero

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

Categories

Resources