Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java check if first digit of int is 0 [duplicate]

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.

like image 948
Freddy19 Avatar asked Jan 03 '23 11:01

Freddy19


2 Answers

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)

like image 135
Valentin Michalak Avatar answered Jan 13 '23 19:01

Valentin Michalak


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.

like image 43
Shanu Gupta Avatar answered Jan 13 '23 17:01

Shanu Gupta