This is the second lecture of the Learn Java lecture series. In this you’ll learn about variables in Java.
Variable is like a box in which you can put a value and we got different sizes of boxes. There is a convention in java that the name of the variable should be first word should start with small letter and rest of the word will start with capital words. For Example:
This is how you can declare a variable in java and see the convention I was talking about, this is how you’ll use it. So myNumber is a type int meaning it is an integer variable and can hold an integer value. Int has the following types too:
int is 32 bit value.
short is a 16 bit value
long is used to store numbers more that int and short, it is 64 bit.
To store floating point number you need to we used double for it.
double myDouble = 7.4332;
There is no long version of double, but there is a short one called float.
In java when you declare a float like float myFloat = 342.4 will give you an error. Because this is how double number is written so you need to add ‘f’ at the end of it in order to make it a float.
float myFloat = 342.4f;
char is a type which can hold a unicode character and you can specify a character by putting a single quote around it as:
char myChar = 'e';
boolean is very useful variable type in java to hold true or false.
boolean myBool = true;
Lastly, we have byte which can hold 8-bits of data.
byte myByte = 112;
So in helloWorld.java file add this code:
int myNumber; //declaring variable
myNumber = 88; //Initializing variable
//We can do this in one line too as
int anotherNumber = 34;
//printing a value in a variable
//other types of int
short myShort = 847;
long myLong = 9445;
//for floating number
double myDouble = 7.3243;
float myFloat = 324.3f;
char myChar = 'y';
boolean myBool = false;
byte myByte = 122;
//print all of them
Run the code and you’ll see the following as output.