4 How to Assign Literal to Variable

Literal means a Value. Means our topic is how to assign value to a variable.

Mainly in Java we have 5 types of  assignment:

1) With the help of value directly.
2) With the help of another variable.
3) With the help of method return type.
4) With the help of Expressions.
5) Passing argument to a method parameters.

Variable: A variable is a named memory location.

(1) With the help of value directly : In this we directly give the value to a variable as follow:

    int a=10;

(2) With the help of another variable : In this we first store the value in another variable and initialize that value to our current variable.

byte b=10;
int a=b;

Note: In this a new memory location is created for variable a and then the value of b is copied into that memory location. 

(3) With the help of method return type : I n this type the value return by the method after the call complete is stored in the variable.

int a=m1();

Here the green part is Destination Place. The blue part is Source place/ Initialization place/Calling Place.

Whenever we are calling method we call with 1) Method Name.
                                                                          2) Parameter.

int m1()
{
    .......
    .......
    .......
    return 123; // return type
}

In this  definition int is return type.
m1 is the method name.

Note: The destination place and return type and return value should be of same type.

Types of Method:
1) Carrying the information -> non-void
2) Not Carrying -> void


(4) With the help of Expressions : 

char a='a';
char b='b';
int c = a+b;

Whenever we are adding two char value we are getting integer value.

Ascii value of  'a' = 97 
                        'b' = 98
So in c we get 97+98 i.e 195.

(5) Passing argument to a method parameters

In this we are passing the value to method as a parameter and then initializing the parameter.

public void m1(int x)
{

}

Here public : Access Specifier 
void is return type.
m1 is method name.
int x is parameter place / argument place.

When we are calling m1(123) then x will store 123.


Previous
Next Post »