# JAVA Tutorial II – Data Types (Part III – Floats)

Floats can do what Ints cannot because Ints are stupid…Just kidding. People prefer Ints because “they use less memory.” Most computers nowadays can handle all of the floats so it wouldn’t be much of a problem to outsource the Ints’ job to the floats.

What’s a Float?

A Float is a number than can hold a limited amount of decimal places. They are commonly declared as a Float x; or Float potatoes;. Since Java is heavily inspired by C++, Floats are declared the same way in both.

What’s in Store?

For this section, we are going to rebuild the Division problem. We are also going to cover the other 2 types of simple mathematics logic (subtraction and multiplication). Many of the terms learned in the Ints section will spill over into this section, such as the Scanner. We’ll learn how to implement floats and what happens when you replace ints with a float on a division problem.

Part I of Part III of Java Tutorial II

Create a new program and new class. You should have this down by now. After creating the new class, (we’ll name it Float), create the code as if you were making the Division Program but replace all of the Ints with Floats. Here is the code you will need for the actual program.

 import java.util.Scanner;public class Float {

public static void main(String[] args) {   System.out.print(“Enter Your Dividend”); Scanner scan = new Scanner(System.in); float x = scan.nextFloat();   System.out.print(“Enter Your Divisor”); Scanner scan2 = new Scanner(System.in); float y = scan.nextFloat();   float total=x/y; System.out.print(“Your Quotient is ” + total); }   } And here is the color coded copy: Float Result Once you compile the program, enter numbers. If you place non-Integral numbers, notice that it gives a response including a decimal. But this decimal is limited to a certain amount of digits. If we wanted to increase the amount of digits, you’d need a data type that has a larger memory capacity. Division Logic To divide numbers, you just use the “/” forward slash symbol. Part II of Part III of Java Tutorial II We aren’t going to change the code so the result would have multiplied numbers. But when using Multiplication logic, you have to just change the forward slash (“/”) symbol into an asterisk. When creating a program that subtracts numbers, you’d change the forward slash, asterisk, or addition sign into a dash. Pretty simple huh? We covered Floats and Ints, but we also covered simple mathematics and Input/Output! You ready for Double? Next Page >> <

Tags:

Categories:

Updated: