ITSourceCode.com

We Exist to Provide 100% Free Source Code and Tutorials

Custom Search

Variable Types

Variable Types

Based on the data type associated with them they are basically of two types:

Numeric types:
Integer type:The variables with which int data type is used belong to this type.
int x;

Here int is the data type and x is the variable.

Float type: Similarly the variables which store all real numbers belong to this type.
Eg.

float x;

Non numeric type:
1.character type:It holds any character(an alphabet,a digit or a special character).

Eg. char c;

2.String type:It holds many characters at a time;

Eg. String fan;

We have three kinds of variables in java:

Local variables:The variables whose scope is limited to the methods ,constructor or block where it is declared.They don’t have any initial value so the must be initialized after declaration.
Example:

  1. class Fan
  2.  
  3. {
  4.  
  5. public void fanspeed()
  6.  
  7. {
  8.  
  9. int speed=0;
  10.  
  11. speed=speed+2;
  12.  
  13. System.out.println(“The speed of the fan is:+ speed);
  14.  
  15. }
  16.  
  17. public static void main(String args[])
  18.  
  19. {
  20.  
  21. Fan f=new Fan();
  22.  
  23. f.fanspeed();
  24.  
  25. }
  26.  
  27. }

Output:

The speed of the fan is:2

In the above example speed is the local variable.Its scope is limited to fanspeed() method.

Instance variables:The variables declared inside the class but outside the method or block.
Example:

  1. class Fan
  2.  
  3. {
  4.  
  5. public String color;
  6.  
  7. public Fan(String c)
  8.  
  9. {
  10.  
  11. color=c;
  12.  
  13. }
  14.  
  15. public void printfan()
  16.  
  17. {
  18.  
  19. System.out.println(“The color of the fan is:+ color);
  20.  
  21. }
  22.  
  23. public static void main(String args[])
  24.  
  25. {
  26.  
  27. Fan f=new Fan(“Black”);
  28.  
  29. f.printfan();
  30.  
  31. }
  32.  
  33. }

Output:

The color of the fan is: black

In the above example color is the instance variable.

Static variables:Like instance variables they are declared inside the class but outside the method or block but they use the static keyword with them. There will only be one copy of these variables.
Example:

  1. class Fan
  2.  
  3. {
  4.  
  5. static int speed;
  6.  
  7. public static void main(String args[])
  8.  
  9. {
  10.  
  11. speed=4;
  12.  
  13. System.out.println(“The speed of the fan is:+4);
  14.  
  15. }

Output:

The speed of the fan is:4

Here speed is the static variable.

Facebook Comments

Check Your Domain Ranking

Leave a Reply

Your email address will not be published. Required fields are marked *

ITSourceCode.com © 2016 Frontier Theme

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!