programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# string + int preceded by zeros

Greenhorn
Posts: 29

the above code outputs :
hello8

how is 8 calculated ?

if my w value is 0011 its 9. How is this ??

author
Sheriff
Posts: 23295
125

Numbers literals, that start with zero, are considered Octal numbers. Hence, 0011 is a base 8 number, that is, of course, equals 9 when converted to decimal (base 10).

Henry

shambhavi sivan
Greenhorn
Posts: 29
oh yeah right !!!

ok fine , so then , if i want to append  a binary value 0010 to  a String , how do i do it ?

if i try the following :

int w=0b0010;
String s="message";
s=s+w;
System.out.println(s);

again it takes the decimal value and prints message2

Sheriff
Posts: 4294
127
I wouldn't take and decimal to binary (I don't think it's possible), but Integer to binary will work.

shambhavi sivan
Greenhorn
Posts: 29

int w=0b0010;
String s="message";
s=s+w;
System.out.println(s);

the above outputs message2

any way to get output as message0010 ?

Henry Wong
author
Sheriff
Posts: 23295
125
shambhavi sivan wrote:
any way to get output as message0010 ?

What's wrong with using the toBinaryString() method that Knute mentioned?

Also, pointing out something that you probably already figured out, an int variable holds an integer. Period. It is a number only. It doesn't have a concept of the base, of number of digits, of formatting of any kind. The fact that it is binary, due to "0b", and 4 digits in length, is simply the compiler processing the literal. That information is *not* available to the program.... So, you are responsible for formatting the number to a string (as binary and as four digits). There is no way that it can be done automagically.

Henry

shambhavi sivan
Greenhorn
Posts: 29
okay thanks everybody for the replies !