4. Working with variables and data types
Data types & Variables
In Java, a variable is a named location in memory that is used to store a value. Before you can use a variable, you must declare it by specifying its data type and name.
Here is an example of a variable declaration in Java:
int myVariable;
In this example, "int" is the data type of the variable, and "myVariable" is the name of the variable. The data type specifies the kind of value that the variable can hold, such as an integer, a floating-point number, or a string.
Java has a rich set of data types, including primitive types (such as int and double) and reference types (such as String and Object). It is important to choose the appropriate data type for your variables to ensure that they can store the values you need.
Here are some examples of data types in Java:
- int: used for storing integers (whole numbers)
- double: used for storing floating-point numbers (decimal numbers)
- char: used for storing single characters
- boolean: used for storing logical values (true or false)
- String: used for storing text strings
- After declaring a variable, you can assign a value using the assignment operator (=).