A Guide to Declaring Variables and Performing Operations in Java
2023-11-18 | by reerr.com

Declaring Variables and Assigning Initial Values
When declaring a variable in Java, you need to specify the data type of the variable and then provide the variable name. Let’s take a look at some examples:
Declaring an Integer Variable
To declare an integer variable, use the int
data type:
int num;
You can assign an initial value to the declared variable later on:
num = 100;
Alternatively, you can declare and assign a value to the variable at the same time:
int num = 100;
Declaring a Character Variable
Declaring a character variable is similar to declaring an integer variable. Use single quotes (' '
) to assign an initial character:
char grade = 'A';
Declaring a Decimal Variable
To store a number with a decimal point, use the double
data type:
double pi = 3.14;
Declaring a String Variable
To store a series of characters, use the String
data type. Insert the string within double quotes (" "
):
String greeting = "Hello, World!";
Performing Operations with Variables
In Java, you can perform various operations with variables using a variety of operators designed to work appropriately with different data types. Here are some examples:
int num1 = 10; int num2 = 20; int sum = num1 + num2; // addition int sub = num1 - num2; // subtraction int mult = num1 * num2; // multiplication int div = num1 / num2; // division
Types of Data in Java
Java provides several types of data. Here’s a brief introduction to the main data types:
- Primitive data types: These include
byte
,short
,int
,long
,float
,double
,char
, andboolean
. - Reference/Object data types: These include
Arrays
,Class
,Interface
, andEnum
.
An array is a data structure that holds consecutive data of the same type. It can be a primitive type or an object type. A class is a user-defined data type that consists of fields (variables) and methods. An interface is a collection of methods with prototypes that must be implemented in a class. An enum is a collection of specific values (constants).
By understanding these data types and how to declare variables and perform operations, you’ll be well-equipped to write efficient and effective Java programs.
RELATED POSTS
View all