Java 101 — Variables and Parameters
Variables are useful to store information that later we can use.In order to use a variable first we must declare them.
We start with the type of variable followed by the variable name and it's value.
public class Variable
{
public static void main (String [] args)
{
byte variable1;
// Can store -128 to 128
short variable2;
// Can store -32768 to 32768
int variable3;
// Can store 2147483684 to 2147483684
long variable4;
//Can store really huge numbers
float variable5;
// Can store large decimal range
double variable6;
// Can store huge decimal range
}
}
Area of a Rectangle
The following class calculates the area of a rectangle using variables.
public class Area
{
public static void main (String [] args)
{
int length = 5;
int width = 10;
int area = length * width;
System.out.println("The area of the rectangle is " + area );
}
}
Casting
If you want to store a double in an integer the JVM will throw an expection because a double wont fit in an integer. The solution is casting.
int myVar = (int) myDouble;
When casting from one type to another, always use the type that you are converting to as the cast.