Automation QA Testing Course Content

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 (==)."

Variable types:



1)local variable/field/data member
2)instance/non-static variable/field/data member
3)static variable
Localvariable: if you declare any variable inside the method body/block body then those variables are called local variables;
local variables are accessible within that method only not outside the method.
Local variables are allocated memory in stack memory, hence these are also called as stack variables. 
These will be destroyed from the stack when completion of method execution.
for local variables, a default value is never assigned
local variable syntax:
datatype varaiblename=value;
you can apply the final keyword for the local variable.
Which modifier keyword can be used on the local variable?
Ans)final keyword
//what is the final local variable syntax?
final datatype variablename=value;
Ex:
public class LocalVariableDemo{
public static void m1(){
datatype varaiblename=value;
int x=10; //x is local variable
System.out.println("x value is:"+x);
long l=20; //l is a local variable
boolean b=l>x;
}//m1 method ending
private void m2(){
datatype varaiblename=value;
float f=5.6F; //f is local variable
boolean b1=false; //b1 is local variable
double d=f+35.5;  //d is local variable
System.out.println("the value of d is :"+d);
} //m2 method ending
}
Instance variable/non static variable: if you declare any variable outside the method  and inside a class without a static keyword then that variable is called an instance variable
  • non-static variables are accessible within any non-static method
  • non static variables are not accessible within any static method
For instance variables, it is not required to perform initialization explicitly. The JVM will provide default values to it.
In the case of primitives, the default value is zero (0).
In the case of object, the default value is ‘null‘
In the case of String, the default value is ‘null‘
In the case of boolean, the default value is ‘false‘.
Instance variables are allocated memory on the heap. Since the instance variables are allocated memory
 heap, for every object a separate copy of the instance variable will be created in the memory.
Instance variables are allocated memory at the time of creating the objects only (Runtime), hence these variables are also called object-level variables.
nonstatic/instance varaible syntax:
accessmodifier datatype varaiblename=value;
nonstatic final variable syntax:
access modifier final datatype variablename=value;
protected final String S4="java";
example:
public class InstanceVariableDemo{
//access modifier datatype variablename=value;
public int a=20,b=30;  //instance varaible/non static variable
float x=4.5F;
String str="java";
//access modifier void method name(){methodbody}
public void m3(){
//datatype variablename=value/expression;
int sum=a+b;
System.out.println("the sum of a,b, is:"+sum);
}
protected void m4(){
float f1=3.5F+a+b;
System.out.println("the flaot value is :"+f1);
}
static void multiply(){
int m=5*a; //this is wrong a is a nonstatic variable, should not be called inside the static method
}
}
Static variableIf you declare any variable as static, it is known static variable..if you declare any variable inside the class and outside the method with the static keyword is called a static variable.
The static variable can be used to refer to the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students, etc.
Static variables have to be declared at the class level and cannot be declared at the method level
The static variable gets memory only once in the class area at the time of class loading.
static variables are accessible within any method(static and non static)
Static variable syntax:
accessmodifier static datatype varaiblename=value;
static final variable Syntax:
 accessmodifier final static datatype variablename=value;
Example:  MAX_COUNT, MIN_COUNT.
1)public final static int MIN_WORDS=300;
MIN_WORDS=MIN_WORDS+25; -->this will throw compile time error
example:
public class StaticVariableDemo{
//accessmodifier static datatype variablename=value;
float f2=5.5F; //
static int x=10, y=20,z=30;
static int add;
public static void sum(){
//datatype variablename=value/expression;
int a=60;//a is a local variable
add=a+x+y+z;
System.out.println("the sum of numbers is:"+add);
}
private void subtract(){
//datatype variablename=value;
double d=x+y-f2;
System.out.println("the subtraction of x,y,f2 is:"+d);
}
}

Static Variables

Non-Static Variables

They can access them using class names.

They can be accessed only using objects.

They can access them with static methods as well as non-static methods.

They can be accessed only using non-static methods.

They are allocated memory only once while loading the class. 

A memory per object is allocated.

These variables are shared by all the objects or instances of the class.

Each object has its own copy of the non-static variables.

Static variables have global scope.

They have local scope.

=============================================================
More Information on Static keyword:

The static keyword in Java is used to indicate that a member (field or method) belongs to a class, rather than an instance of the class. This means that the member can be accessed without creating an instance of the class.

Here are some examples of how the static keyword is used in real-time applications:

  1. Class constants: The static keyword is often used to define constants that are associated with a class, rather than with a specific instance of the class. For example:
public class MathUtils {
    public static final double PI = 3.141592653589793;
    public static final double E = 2.718281828459045;
}
  1. Factory methods: The static keyword can be used to define factory methods that create and return instances of a class. For example:
public class Employee {
    private static int nextId = 1;
    private int id;
    private String name;

    private Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public static Employee create(String name) {
        return new Employee(nextId++, name);
    }
}
  1. Utility methods: The static keyword is often used to define utility methods that perform a specific task, such as generating a random number or calculating the distance between two points. For example:
public class MathUtils {
    public static double distance(double x1, double y1, double x2, double y2) {
        double dx = x2 - x1;
        double dy = y2 - y1;
        return Math.sqrt(dx * dx + dy * dy);
    }
}
  1. Singleton classes: The static keyword can be used to create singleton classes, which are classes that have only one instance. For example:
public class Database {
    private static Database instance = new Database();

    private Database() {
        // Private constructor to prevent external instantiation
    }

    public static Database getInstance() {
        return instance;
    }
}

final Variable:
final is a non-access modifier keyword. final keyword can be applied on class, method and variable
 final variable value cannot be changed
 For final variable name, all its letters should be capital and words must be connected with "_".


============================================
can you access static variables under non-static methods?
================================================================
Note: can you access nonstatic variables under the static method?
============================================================
  • Can Static variables be used with Static methods - YES
  • Can Static variables be used with non-static methods - YES
  • Can non-static variables be used with static methods - NO
  • Can non-static variables be used with non-static methods - YES
======================================================
Q1)How can you execute the static method under the main method in the same class?
directly call the static method name
staticmethodname();
Q2)How can you access one class static variable in another class?
Ans)classname.staticvariable;
Q3)How can you access one class static method in another class?
Ans)classname.staticmethod();
Q4)How can you call the static variable under main method in the same class?
Ans)directly call the static variable.

Variable Concept Interview Questions?

1)what is a variable?

2)what are the naming conventions of a variable?

3)what is a local variable and explain in detail?

4)What is the Instance variable and explain in detail?

5)what is a static variable and explain in detail?

6)can we access nonstatic data in static methods?

7)can we access static data in nonstatic methods?

8)What is the Final variable?
9)What are final variable naming conventions?
10) can we do the below statement? why?
final int MAX_COUNT=10;
MAX_COUNT=MAX_COUNT+5;
11)local variables stored in which memory?
12)Static variables stored in which memory?
13)nonstatic variables stored in which memory?
14)below code is correct or not about local variables?
public class A{
private static void method1(){
int x=25;
float f=3.5F;
x=x82;
System.out.println(x);
f=f-1.5;
System.outprintln(f);
}
protected static void method2(){
long l=200;
final byte bt=5;
bt=bt*5;
System.out.println(bt);
long sum=x+l+bt;
System.out.println(sum);
}
}
15)Which is a correct naming convention for a variable
a)int_Speed
b)int speed
c)int_speed
d)int Speed

Questions

  1. The term "instance variable" is another name for ___.
  2. The term "class variable" is another name for ___.
  3. A local variable stores a temporary state; it is declared inside a ___.
  4. A variable declared within the opening and closing parenthesis of a method signature is called a ____.

Exercises

  1. Create a small program that defines some fields. Try creating some illegal field names and see what kind of error the compiler produces. Use the naming rules and conventions as a guide.
  2. In the program you created in Exercise 1, try leaving the fields uninitialized and print out their values. Try the same with a local variable and see what kind of compiler errors you can produce. Becoming familiar with common compiler errors will make it easier to recognize bugs in your code.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.