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 - float Keyword



Java float keyword is used to define one of the eight primitive datatypes supported by Java. It provides means to create float type variables which can accept a float value. Following are the characteristics of a float data type.

  • Float data type is a single-precision 32-bit IEEE 754 floating point

  • Float is mainly used to save memory in large arrays of floating point numbers

  • Default value is 0.0f

  • Float data type is never used for precise values such as currency

  • Example: float f1 = 234.5f

A float variables represents a reserved memory locations to store float 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 float values in float variables.

Example 1

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

package com.tutorialspoint;

public class JavaTester {
   public static void main(String args[]) {
      float floatValue = 2.0f;
      System.out.println("float: " + floatValue);	  
   }
}

Output

float: 2.0

Example 2

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

package com.tutorialspoint;

public class JavaTester {
   public static void main(String args[]) {
      float floatValue1 = 2.0f;
      float floatValue2 = 4.0f;
      float floatResult = floatValue1 + floatValue2;

      System.out.println("float: " + floatResult);
   }
}

Output

float: 6.0

Example 3

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

package com.tutorialspoint;

public class JavaTester {
   public static void main(String args[]) {
      float floatValue = 2 * Float.MAX_VALUE;
      System.out.println("float: " + floatValue);
   }
}

Output

float: Infinity
Advertisements