JAVA Variables

Like in algebra, variables are where a data is placed e.g. x = 10, this indicates that the variable x will contain a value of 10. Same is through JAVA, variables are containers of data. Let us take a look on how to code JAVA variables.

int testname = 10;
float anothername = 10.5f;
double _testagain = 21.3; //double data can contain larger values than short and float
short forsmallrange = 54; //short data type is used when you store values from -32768 to 32767
String myname = “Hello World”;
char onechar = ‘Z’; //char data type is for a single char only unlike the String data type.
boolean true_or_false = true;

So, the syntax is Data_Type variable_name = some_value; This is called variable declaration and variable initialization;
Variable Declaration is -> Data_Type variable_name; Declaration of a variable will cause the variable to contain a garbage value like #$(*%hsdw0348 etc…
Variable Initialization is -> variable_name = some_value; This will store a value to the variable like x=10;

Just think of a variable as a storage of a value or data.

Operators are used to make some manipulations in the value. For example:
int x = 10;
int y = 20;
int result = x + y;

If you are an absolute beginner, I recommend that you try other things using operators + – / *. Also, remember the order of MDAS.

Let us try a simple program, we will use the HelloWorld program that we have created or you can also create another project.
Java Variables and Scanner

Notice after the line package helloworld;
There is import java.util.Scanner; . From the name implies import, it indicates that we will use methods that are in the package of java.util.Scanner. Some methods here are used for user input in Console Version. There is also user input in GUI version that we will see later.

Please run the application and input something in the Output Tab:
Window Output in Netbeans

Done!

Next: Control Flow

1 comment: