Maison >Java >javaDidacticiel >Programmation Java : variables et types de données

Programmation Java : variables et types de données

Mary-Kate Olsen
Mary-Kate Olsenoriginal
2024-10-03 06:16:021002parcourir

Java Programming: Variables and Data Types

Variables and data types, an important concepts in every programming language. In this article, we will explore variables and data types in Java.

Variable

A variable is a container used to store data in memory. In the real world, we use different types of containers to store various things. The data we store can be of various types. It can be a number, a character, a word, or a boolean value, either true or false. Here are the data types in the picture.

Data Types

Data types are the types of data. In Java, there are numerous types of data. Some of them are:

  • int: Whole numbers from -2,147,483,648 to 2,147,483,647
  • float: Floating point numbers eg: 3.14
  • long: Whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
  • double: A double is a 64-bit (8-byte) floating-point number that can store up to 15-16 decimal digits.
  • boolean: A boolean type, true or false
  • char: A single character or letter

Declaring variables

In Java, we can declare variables by using the following method:

dataType variableName = value;

So, if we want to store a variable called age. So the code will be :

int age = 21;

Let’s create some more variables.

class MyClass {
    public static void main(String[] args) {
        int age = 21;
        String name = "Mahmud";
        float pi = 3.146;
        char letter = 'm';
        boolean isMarried = false;
    }
}

Here we have created a few variables of different types. We have created a variable called name of the String data type to store a word. Note that the String keyword starts with a capital S. We’ve also created a variable of float type to store the value of pi which is a floating point number.

Boolean is a data type where there are only two values, true or false. We’ve declared a boolean variable called isMarried and assigned its value to false.

Constant

We can create a constant using the final keyword. Here is an example:

final int constantNumber = 16;

Now, we cannot change the value of constantNumber because it’s a constant. If we try to assign a new value it will generate an error.

Conclusion

In this article, I discussed different data types and how to create variables using those types in Java.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn