Web Tutor

Other Entries

The Variables In Java

A variable is a name that is associated with a value that can be changed. For example, when I write
int i = 10;

here variable name is i which is associated with the value 10, int is a data type that represents that this variable can hold integer values.

To declare variables, follow the syntax below.

data_type variable_name = value;

The value is optional because, in Java, you can declare a variable and then assign it to a value later. 

If you take a look at the example below, num is a variable and int is a data type. The int data type allows this num variable to hold integer values.

int num;

Similarly, we can assign the values to the variables while declaring them like this:

char ch = 'A';
int number = 100;

The code above can also be written in this way.

char ch;
int number;

ch = 'A';
number = 100;

Variables Naming convention in Java

1. Variable naming cannot contain white spaces For example:

int num ber = 100;

is not valid because the variable name has a space in it.

2. A variable name can begin with a special character such as a dollar sign($) and underscore(_).

3. As per the java coding standards, the variable name should begin with a lower case letter, for example

int number;

For a lengthy variable that has more than one word. use the camel case technique to declare a variable. For example

package HelloWorld;

/*This program uses camel case in naming variables
 * It prints two names

public class HelloWorld {
	public static void main(String[] args) {
		String firstName = "Norah";
        String secondName = "Winda";
        System.out.println("First Name: "+firstName);
        System.out.println("First Name: "+secondName);




4. Variable names are case sensitive in java

Types of Variables in Java

The three types of variables in java are local variables, static variables, and instance variables.

The local variables are declared inside a method. Their scope is limited to the method, which means that you can't change their values and access them outside of a method.

The static variables are also known as the class variables because they are associated with the class and common for all the instances of a class.

Instance variables have their separate copy of instance variables

Posted in Java on September 10 2022 at 05:55 PM

Comments (0)

No login

Popular Blogs