Java: Numeric Types - byte, short, int, long, float and double




We already know how to show messages through the 'print'.
Now let's do some stuff with numbers.

We will show you how to work with integers and real numbers (decimal), in addition to an explanation about data types (int, float and double, in this case).



- Declaring

Java is a strongly typed language, ie, to use the types of data, we have to declare them.
Let us declare an integer:
int age;

The declarations follow this syntax: [type] variable_name;

This is necessary because the Java selects a part in memory (allocate) for this variable, but different variable types occupy different memory sizes.

The type "int", for example, stores 32 bits, or any integer between -2,147,483,648 and 2147483647

The type 'float', which stores decimal numbers (broken or with a comma) also store 32 bits.
As for the 'long' store 64 bits, as well as 'double' (which is a 'float' high), or any integer from 9.223.372.036.854.775.808L 9.223.372.036.854.775.807L up.

Let's declare a type 'long':
idade_do_universo long;

We can do:
long age;

to store a person's age? Yes we can, but obviously a waste of memory because it will not use a large number to represent our age.

- Initializing a variable

We could assign a value to a variable in two ways, in a statement:int age = 21;

Another way is after the declaration:int age;age = 21;

We will show how to print the value of a variable in the 'print', noting that Java only allows this after you declare and initialize your variable:System.out.println (age);

Try the following code:
public class Soft {

    public static void main(String[] args) {
        int age=21;
        System.out.println("age");
        System.out.println(age);
        
    }
}



Realize the difference? When placed between quotation marks, the text is printed.
If we don't use quotation, the value stored is saw.

We will use both "age" text and the age value:

public class Soft {

    public static void main(String[] args) {
        int age=21;
        System.out.println("My age is: " + age);
       
    }
}


A quoted text is called string. So we printando the string "age" and an integer.

Replace and test, now with decimal values​​:


        float money=1.99f;
        System.out.println("I have " + money + " in my wallet");


One important details:
.By default, Java assumes double as decimal values​​. To specify that it is a 'float', put that 'f' at the end. Or 'F'.
At the end of type 'long' place 'l' or 'L'.

To store integers, there are also types byte, which stores 8 bits and 'short', which stores 16 bits.
But let's ignore these, because its limitations (very small).

Java: Numeric Types - byte, short, int, long, float and double

No comments: