Sunday 18 May 2014

Java - Datatypes and Variable Types

 Variables

 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables.

1) byte:

    Byte data type is an 8-bit signed two's complement integer.

    Example: byte a = 100 , byte b = -50

2) short:

    Short data type is a 16-bit signed two's complement integer.
     Example: short s = 10000, short r = -20000


3) int:

    Int data type is a 32-bit signed two's complement integer.

    Example: int a = 100000, int b = -200000

4) long:

    Long data type is a 64-bit signed two's complement integer.

    Example: long a = 100000L, int b = -200000L

4) float:

    Float data type is a single-precision 32-bit IEEE 754 floating point.

    Example: float f1 = 234.5f



 

 5) double:

    double data type is a double-precision 64-bit IEEE 754 floating point.

    This data type is generally used as the default data type for decimal values, generally the default choice.


  Example: double d1 = 123.4

   6) boolean:

    boolean data type represents one bit of information.

    There are only two possible values: true and false.

    This data type is used for simple flags that track true/false conditions.

     Example: boolean one = true

   7) char:

    char data type is a single 16-bit Unicode character.

      Example: char letterA ='A'


Variable Types










There are three kinds of variables in Java:

   1)  Local variables



Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.



    2) Instance variables



Instance variables are declared in a class, but outside a method, constructor or any block.

Instance variables are created when an object is created with the use of the keyword 'new' and destroyed when the object is destroyed.    

3) Class/static variables



Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final and static. Constant variables never change from their initial value.

No comments:

Post a Comment