Site icon TestingDocs.com

Declare Java variables

Overview

In this tutorial, we will learn to declare Java variables in Eclipse IDE. Two important points to remember are:

What is statically-typed Language?

Statically typed language expects the variables to be declared before using them. In Java, we need to declare the variables before using them in the Java programs. Any undeclared variables would result in a compilation error

<Undeclared_Variable> cannot be resolved to a variable

Declare Java Variables

Java variables are the names of the memory locations that are used to store the values. We can declare a single variable or multiple variables using a declaration statement.

Syntax

The general syntax for declaring a single Java variable is as follows:

DataType variable_name;   //declaring variable

In the preceding syntax, DataType specifies a Jave type, such as int, char, double, etc. Variable can have any name that follows some specified naming conventions. For example to declare a String variable we can use the following line of code.

String name;

Example to declare an integer variable i.

int i;

Declare a double variable called price.

double price;

We can also declare multiple variables at once using a single statement. For example, to declare the length and width of type float:

float length, width ;

Initialize Variable

We need to initialize the variable and assign a value. The most common way is to initialize the variable along with the declaration statement.

Examples

String name=”Learn java”;

int i=0;

double price=12.5;

 

Common mistakes

We get this error when we try to run the program without initializing the variable.

The local variable name may not have been initialized

Java is case sensitive language.  So, String and string are not equal. We get an error if we try to declare

string name=”Learn Java”;

 

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version