Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '0' do in Java?

Tags:

java

I'm trying to find the product of all digits in a number, which I have stored as a string (due to int and long length limits).

So the number looks like this:

final String number = "1234567898765432123......etc"

If I use this code, it works:

product *= number.charAt(i + j) - '0';

It doesn't if I remove the '0'.

I got this code from another online resource. Can someone explain what the '0' does?

like image 580
Thev Avatar asked Dec 22 '15 06:12

Thev


People also ask

What does this 0 mean in Java?

'0' is the char value of zero. When you write a string, you're writing an array of 'char' datatypes which the compiler translates into ASCII values (which have a corresponding decimal number value).

What is the string 0 in Java?

When we talk about Strings in Java, we can imagine them as arrays of characters, and they are, but in Java, they also object. An empty Java String is considered as the not null String that contains zero characters, meaning its length is 0.

What is a 0 string?

In computer programming, a null-terminated string is a character string stored as an array containing the characters and terminated with a null character (a character with a value of zero, called NUL in this article).

Does null 0 in Java?

null means that a variable contains a reference to a space in memory that does not contain an object. 0 is a numeric data type with a value of 0. Nothing doesn't really exist, however I think you may be viewing this as an empty String "" which is simply a String data type that does not contain a value.


1 Answers

Ascii characters are actually numbers. And 0 .. 9 digits are numbers starting from decimal 48 (0x30 hexadecimal).

'0' is 48
'1' is 49
...
'9' is 57

So to get the value of any character digit, you can just remove the '0', ie 48.

'1' - '0' => 1
 49 -  48 => 1

If you don't remove '0' (48) the total sum will be over by 48 * numberOfDigits.

See an ascii table to locate digits in it.

Note that '0' is the character 0, not the string "0" containing the character '0'.

like image 178
Déjà vu Avatar answered Oct 05 '22 23:10

Déjà vu