Click here to Skip to main content
15,881,898 members
Articles / Web Development
Technical Blog

Numeric Literals in Java 7 and in C#

Rate me:
Please Sign up or sign in to vote.
4.71/5 (4 votes)
28 Nov 2013CPOL1 min read 13.1K   2   1
Numeric literals in Java 7 and C#

In both Java and C#, it’s quite easy to express integer numerical literals. You can use both decimal and hexadecimal base to represent the value. Only for the hexadecimal base, you need to prefix the value with 0x. For decimal base values that exceed 2^31-1, you need to provide a suffix (typically L) specifying this fact so the compiler will treat it like a long integer value. C# also provides unsigned long values (U prefix). In both languages, the casing of the suffix does not matter.

Java (notice, there are no unsigned primitives in Java)

Java
int i1 = 23; // integer, decimal
int h1 = 0x17; // integer, hexadecimal
long i2 = 12345678900L; // long integer (64 bit signed integer)

C#

C#
int i1 = 23;
int h1 = 0x17;
ulong u1 = 12345678900U;
long i2 = 12345678900L;

As you might have read in Beginning Java for .NET developers in slide 14, beginning in Java 7 you can also use two more features that are not present in C# (at least at the time of this writing).

Binary base
Java
int b1 = 0b11001010;
Underscores in literals (no matter which base)
Java
int b1 = 0b1100_1010;
long myCardNumber = 2315_2432_2111_1110;
int thousandsSeparated = 123_456_000;

The restrictions on the underscore placing is that you may not place it at the beginning of the value (prefix) or at the end (suffix). Also, for non-integer literals, you may not place it adjacent to the decimal separator.

For floating-point literals, you must use the dot as decimal separator (if you need to specify a fraction, if not, you’re not required). You must use F for float-single-precision (32 bit) and D for float-double-precision (64 bit). Moreover in C#, you also have the M suffix corresponding to the decimal (128 bit) value type.

C#

C#
float x1 = 0.001F;
double x2 = 12.33D;
decimal x3 = 111.2M;
float x4 = 33F;

Java

Java
float f1 = 0.001F;
double f2 = 12.31D;
float f3 = 123F;

This article was originally posted at http://blog.andrei.rinea.ro?p=453

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) IBM, Business Analytics
Romania Romania
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionI want training to code programming at online Pin
Member 104421753-Dec-13 21:54
professionalMember 104421753-Dec-13 21:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.