So the question is very simple.
How to check in java if first digit of an int
is 0
;
Say I have:
int y = 0123;
int n = 123;
Now I need an if statement that would return true for y
and false for n
.
Your question is pretty strange for one reason: An int value cannot start by 0. But if you store your value in a String, you could check it easily like this:
public static void main(String[] args) {
String y = "0123";
String n = "123";
System.out.println(startByZero(y));
System.out.println(startByZero(n));
}
public static boolean startByZero(String value) {
return value.startsWith("0");
}
Output:
true
false
EDIT: Like Oleksandr suggest, you can use also:
public static boolean startByZero(String value) {
return value.charAt(0) == '0';
}
This solution is more efficient than the first. (but at my own opinion it's also less readable)
Your
y = 0123
will be considered as octal base but
n = 123
is an decimal base.
Now when you do
if (y == n )
the numbers will be compared based on decimal base always.
You'll have to do conversions from octal to decimal or vice-versa based on your requirements.
You could also use Strings
as @Valentin recommeneded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With