Notes
Java and Apex are similar in a lot of ways. Variable declaration in Java and Apex is also quite the same. We will discuss a few examples to understand how to declare local variables.
You can declare the variables in Apex as follows;
String:
String strName = 'My String';
Integer:
Integer myInt= 64;
Boolean:
Boolean Status= false;
Long:
Long myLong= 16754.9874L;
Decimal:
Decimal myDecimal= 12.87;
Double:
Double myDouble = 5362545252.737373;
To create a variable, you must specify the type and assign it a value:
Integer myInt =12;
String myTxt = 'Apex';
Boolean status = true;
Decimal myDec = 12.48;
Double myDouble = 1453.1453;
Long myLong = 16562836553L;
System.debug(myInt);
System.debug(myTxt);
System.debug(status);
System.debug(myDec);
System.debug(myDouble);
System.debug(myLong);
You can also declare a variable without assigning the value, and assign the value later:
Integer x;
x = 12;
System.debug(x);
If you assign a new value to an existing variable, it will overwrite the previous value:
Apex variables are Case-Insensitive
This means that the code given below will throw an error since the variable 'myint' has been declared two times and both will be treated as the same.
Integer myint =15;
Integer MYINT = 12;
System.debug(MYINT);