Variable

A unit of storage in java programming.

syntax:

type identifier= value;

type- predefined data type, class name or interface name.

identifier- name of the variable.

value- corresponding to the type of variable.

ex:

int a,b; //declaring the variables.

int x=5,y,z=10; // initializing the variables.

Dynamic Initialization of variables

During the execution of expression variable will initialized.

ex:

int a=2,b=3; // direct initialization

int c= add(a,b); //dynamic initialization

Scope of variable

scope means block of code surrounded by curly braces.

in java 2 types- class scope, method scope.

nested scope- the variables in outside scope can be accessed by inside scope but not vice versa.

ex:

//example of nested scope
class NestedScopeExample
{
public static void main(String args[])
{
int a=5;
System.out.println("value of a is::"+a); //displays 5
if(a>3)
{
int b=10;
System.out.println("value of b is::"+b); // displays 10
System.out.println("value of a is::"+a); // displays 5
}
System.out.println("value of b in outside scope"+b);//error as we can't access b variable
}
}

output:: cannot found a symbol b

as we can access the out scope variable in inside scope but we can't declare the same variable again.

ex:

if(a>3)

int a=10; //error as a already exists.

Type Conversation

if both value and identifier are of same type.

if the data type is higher than value type.

automatic conversation done by byte, long, short, char

char to boolean or boolean to char is not possible

ex 1:

int a;

byte b=50;

a=b*2; // possible as int is more limit than byte.

ex 2:

byte b=50;

b=50*2//not possible as more than byte limit

b=(byte) 50*2;

Casting incompatible types

_Narrowing conversation:_making value to narrow to fit into a target variable.

ex: int a=100;

byte b;

b= a;//it is not possible as byte is smaller than int

b= (byte) a;// (target type) value.

Truncation:initializing float or double values to int type variable means different values.

ex: int a;

float f=1.43;

a=f; // not possible as different types

a = (int) f;// truncation of f to a

Type Promotion Rules

byte, char, short can promote to int.

long to long.

double to double.

float to float.

results matching ""

    No results matching ""