I need help, I have an int num = 0000;
but on System.out.print(num);
it only shows like this: 0
.
I would like to know what can I do if I have num = 0111;
or num = 0011;
or num = 0001
and I want to show the 0 before the number, so the final result can be 0001
and not 1
.
Thanks!
Asked
Active
Viewed 763 times
-3

GGarriga
- 25
- 1
- 2
- 7
-
You need to use a `String` instead. – marstran Feb 24 '17 at 10:03
-
but how can I do that? – GGarriga Feb 24 '17 at 10:03
-
You can do research ... – Tom Feb 24 '17 at 10:04
-
`String num = "0000";` – marstran Feb 24 '17 at 10:04
-
`System.out.println(String.format("%04d", 1));` – Suresh Atta Feb 24 '17 at 10:04
-
3Beware, a leading `0` will make your value an octal one . http://stackoverflow.com/questions/7218760/why-is-08-not-a-valid-integer-literal-in-java – Arnaud Feb 24 '17 at 10:05
3 Answers
0
If you want to print an int formated like this 0000, you have to do this:
int num = 23;
System.out.print(String.format("%04d", num));
// result -> "0023"
Best regards

thibsc
- 3,747
- 2
- 18
- 38
0
Kindly use String datatype instead of int. Because in Java int automatically removes extra leading zeros.
Example: String num="0000";
As you know in integers Leading zeros have no impact. From you input I think you are storing binary integers. If you want to store binary input to Integer kindly take a look on this answer.
Use Binary in Int variable in Java
Thanks

Community
- 1
- 1

Hammad Sajid
- 312
- 1
- 3
- 14