Wednesday 8 April 2020

How to initialize long in Java?

This is one of the good interview questions asked to understand how primitive types work.

Interviewer given below statement and asked whether this code compile or not.
long var1 = 12345678912;

Since long in Java is 8 bytes in size, and in range of -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. You can guess that this program compiles successfully.

But when you try to compile the program, you will end up in error like 'The literal 12345678912 of type int is out of range'. It is because all the numeric literals are integers by default and the number (12345678912) can’t be accommodated in integer (which is 4 bytes in size). To make the program run, You need to add the character L or l at the end of the number to make Java recognise it as a long.

App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {
  
  long var1 = 12345678912L;
  long var2 = 12345678912l;

  System.out.println("var1 : " + var1);
  System.out.println("var2 : " + var2);
 }

}

Output
var1 : 12345678912
var2 : 12345678912



You may like

No comments:

Post a Comment