Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java List Interface

Java Queue Interface

Java Map Interface

Java Set Interface

Java Data Structures

Java Collections Algorithms

Advanced Java

Java Miscellaneous

Java APIs & Frameworks

Java Useful Resources

Java - long datatype



long datatype is one of the eight primitive datatype supported by Java. It provides means to create long type variables which can accept a long value. Following are the characteristics of a long data type.

  • Long data type is a 64-bit signed two's complement integer
  • Minimum value is -9,223,372,036,854,775,808(-2^63)
  • Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
  • This type is used when a wider range than int is needed
  • Default value is 0L
  • Example: long a = 100000L, long b = -200000L

A long variables represents a reserved memory locations to store long values. This means that when you create a variable you reserve some space in the memory.

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store long values in long variables.

Example 1

Following example shows the usage of long primitive data type we've discussed above. We've created a long variable as longValue and assigned it a long value. Then this variable is printed.

package com.tutorialspoint;

public class JavaTester {
   public static void main(String args[]) {
      long longValue = 2;
      System.out.println("long: " + longValue);	  
   }
}

Output

long: 2

Example 2

Following example shows the usage of long primitive data type in an expression. We've created two long variables and assigned them long values. Then we're creating a new long variable longResult to assign it the sum of long variables. Finally result is printed.

package com.tutorialspoint;

public class JavaTester {
   public static void main(String args[]) {
      long longValue1 = 2;
      long longValue2 = 4;
      long longResult = longValue1 + longValue2;

      System.out.println("long: " + longResult);
   }
}

Output

long: 6

Example 3

Following example shows the usage of long variable with an invalid value. We've created a long variable as longValue and assigned it an out of range value.

package com.tutorialspoint;

public class JavaTester {
   public static void main(String args[]) {
      long longValue = 9223372036854775808;
      System.out.println("long: " + longValue);
   }
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The literal 9223372036854775808 of type int is out of range 

	at com.tutorialspoint.JavaTester.main(JavaTester.java:5)
Advertisements