Java variables

 

JAVA VARIABLES

A variable is a container which holds the value while the java program is executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and static.

There are two types of data types in java: primitive and non-primitive.

Variable is name of reserved area allocated in memory. In other words, it is a name of memory location.

Syntax : Variable declaration

int a=10; 



in above figure variable a allocated memory to store it's value i.e 10.


Types of variable in java

There are three types of variable in java.

1.local variable

2.instance variable

3.Static variable






1) Local Variable: A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.


2) Instance Variable: A variable declared inside the class but outside the body of the method, is called instance variable. It is not declared as static.

It is called instance variable because its value is instance specific and is not shared among instances.

3)Static variable: A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of static variable and share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory. 

for example

Class Test
{
 int a=10; // instance variable 
 static b=9;  // static variable
 
void display()
{
 int c=12; // local variable
}
} 

Java Variable Example Widening

Class Test
{
public static void main()
{
 int a=10; 
 float b=a;  // float can store int type data
 System.out.println(a);// output 10
 System.out.println(b); //output:10.0
}
}
Java Variable Example Narrowing
Class Test
{
public static void main()
{
 float a=10.0f; 
 int b=(int)a;  //typecasting
 System.out.println(a); // output 10.0
 System.out.println(b);  //output:10
}
}

Comments

Popular posts from this blog

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: com.mysql.jdbc.Driver