Automation QA Testing Course Content

Showing posts with label Variable. Show all posts
Showing posts with label Variable. Show all posts

What is a Variable in Java? variable Types in Java

Variable:

In Java, a variable is a storage location for a value. A variable has a name, a type, and a value. The type of a variable determines the kind of value it can hold, such as an integer, a floating-point number, or a string.
  • We use a name, so we can distinguish one variable from another.
  • A variable's type determines the kinds of values/data that can be stored in it.
  • The value is the specific object, data, or information stored in the variable.

How to Work with Variables in Java

To work with different kinds of data in Java, you can create variables of different types. For example, if you want to store your age in a new variable, you can do so like this:

public class Main {

	public static void main(String[] args) {
		// <type> <name>
		int age;

	}

}

You start by writing out the type of data or variable. Since age is a whole number, its type will be integer or int for short, followed by the name of the variable age and a semicolon.

At the moment, you've declared the variable but you haven't initialized it. In other words, the variable doesn't have any value. You can initialize the variable as follows:

public class Main {

	public static void main(String[] args) {
		// <type> <name>
		int age;
		
		// <name> = <value>
		age = 27;
        
		// prints the age on the terminal
		System.out.println("I am " + age + " years old.");

	}

}

When assigning a value, you start by writing the name of the variable you want to initialize, followed by an equal sign (it's called the assignment operator) then the value you want to assign to the variable. And don't forget the semicolon at the end.

The System.out.println(); function call will print the line I am 27 years old. to the console. In case you're wondering, using a plus sign is one of the many ways to dynamically print out variables in the middle of a sentence.

One thing that you have to keep in mind is you can not use an uninitialized variable in Java. So if you comment out the line age = 27 by putting two forward slashes in front of it and try to compile the code, the compiler will throw the following error message at you:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The local variable age may not have been initialized

	at variables.Main.main(Main.java:13)

The line The local variable age may not have been initialized indicates that the variable has not been initialized.

Instead of declaring and initializing the variable in different lines, you can do that in one go as follows:

public class Main {

	public static void main(String[] args) {
		// <type> <name> = <value>
		int age = 27;
        
		// prints the age on the terminal
		System.out.println("I am " + age + " years old.");

	}

}

The code should be back to normal again. Also, you can change the value of a variable as many times as you want in your code.

public class Main {

	public static void main(String[] args) {
		int age = 27;
        
		// updates the value to be 28 instead of 27
		age = 28;
        
		System.out.println("I am " + age + " years old.");

	}

}

In this code, the value of age will change from 27 to 28 because you're overwriting it just before printing.

Keep in mind, while you can assign values to a variables as many times as you want, you can not declare the same variable twice.

public class Main {

	public static void main(String[] args) {
		// <type> <name> = <value>
		int age = 27;
        
		int age = 28;
        
		// prints the age on the terminal
		System.out.println("I am " + age + " years old.");

	}

}

If you try to compile this code, the compiler will throw the following error message at you:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Duplicate local variable age

	at variables.Main.main(Main.java:9)

The line Duplicate local variable age indicates that the variable has already been declared.

Apart from variables, you may find the term "literal" on the internet. Literals are variables with hardcoded values.

For example, here, age = 27 and it's not dynamically calculated. You've written the value directly in the source code. So age is an integer literal.

What Are the Rules for Declaring Variables?

There are some rules when it comes to naming your variables in Java. You can name it anything as long as it doesn't start with a number and it can't contain any spaces in the name.

Although, you can start a variable name with an underscore (_) or a dollar sign ($), not being mindful of their usage can make your code hard to read. Variable names are also case sensitive. So age and AGE are two different variables.

Another important thing to remember is you can not use any of the keywords reserved by Java. There are around 50 of them at present. You can learn about these keywords from the official documentation but don't worry about memorizing them.

As you keep practicing, the important ones will slip into your neurons automatically. And if you still manage to mess up a variable declaration, the compiler will be there to remind you that something's wrong.

Apart from the rules, there are some conventions that you should follow:

  • Start your variable name with small letter and not any special character (like an underscore or dollar sign).
  • If the variable name has multiple words, use camel case: firstNamelastName
  • Don't use single letter names: fl

As long as you follow these rules and conventions, you're good to go. If you'd like to learn more about naming conventions in general, checkout my article on the topic.

What Are final Variables?

final variable in Java can be initialized only once. So if you declare a variable as final, you can not reassign it.

public class Main {

	public static void main(String[] args) {
		// final <type> <name> = <value>
		final int age = 27;
		
		age = 28;
        
		System.out.println("I am " + age + " years old.");

	}

}

Since the age variable has been declared as final, the code will throw the following error message at you:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	The final local variable age cannot be assigned. It must be blank and not using a compound assignment

	at variables.Main.main(Main.java:9)

However, if you leave the variable uninitialized while declaring, the code will work:

public class Main {

	public static void main(String[] args) {
		// final <type> <name>
		final int age;
		
		age = 28;
        
		// prints the age on the terminal
		System.out.println("I am " + age + " years old.");

	}

}

So, declaring a variable as final will limit your ability to reassign its value. If you leave it uninitialized, you'll be able to initialize it as usual.

 
naming conventions of variable:


 variablename should start with alphabet lowercase, it contains alphanumerics. 
 variable name shouldnot start with number. Variable names cannot contain spaces, +, -, etc
 Here are some examples of declaring variables in Java:
int age; // Declare a variable of type int double salary; // Declare a variable of type double boolean isMarried; // Declare a variable of type boolean String name; // Declare a variable of type String (a reference type) int[] numbers; // Declare an array of type int (a reference type)
You can also initialize a variable when you declare it by assigning it a value:
int age = 35; // Declare and initialize a variable of type int double salary = 75000.0; // Declare and initialize a variable of type double boolean isMarried = true; // Declare and initialize a variable of type boolean String name = "John Smith"; // Declare and initialize a variable of type String int[] numbers = {1, 2, 3, 4, 5}; // Declare and initialize an array of type int

 String collegeName="JNTU";
 byte b4=25; //this is valid
 public static int 9x=35; -->this is not valid, because variable name starts with number


To perform the assignment operation, we use the equal sign (=)."
I'll say it again: This isn't making a comparison. We are copying the value on the right of the equal sign to the variable on the left. To perform a comparison, Java uses a double equal sign (==)."