Showing posts with label local variables. Show all posts
Showing posts with label local variables. Show all posts

Friday, 7 February 2014

How to define a method

A method is a programmed procedure that is defined as part of a class. A class (and thus an object) can have more than one method.

Syntax of method definition
    modifier returnType methodName(parameters) Exception List{
        Method Body
    }

Method definition composed of six components :

modifiers : like private, public, protected or default. We have already seen private, public and default. Will discuss more about these in the packages section.

ReturnType : The type of the value written by the method. If you don't want to return any value make the return type as void. Return type will be any primitive type or reference type.

MethodName : The name given to the method

parameters: Method is defined with parameters or with out parameters. A method can be defined with any number of parameters.

Exception List: A Method can throw any number of exceptions, will discuss about this on ExceptionHandling section

Method Body: The actual implementation of the method goes here

Example
    1. public int sum(int a, int b){
        return (a+b);
        }

        modifier : public
        returnType : int
        methodName : sum
        parameters : a,b
        Exception List : none
        Method body : calculates the sum of the two parameters and return the sum.

2. void sayHello(){
        System.out.println(“Hello”);
    }

    modifier : default
    returnType : void
    methodName : sayHello
    parameters :none
    Exception List : none
    Method body : simply prints the message “Hello” to the console.

If no access specifier (modifier) specified to a variable or method, it assumes default access specifier(modifier).

Naming a Method
By convention method names starts with a small character and starting character of subsequent words is capitalized.

    Example:
    walk()
    sleep()
    setColor(String s)
    getHeight()

Local Variables
Variables declared inside a method are called local variables. These are not accessible out side of the method. You must initialize local variables before using.

Some Points to remember
Trying to use local variables before initializing causes compile time error

Example
class LocalVariable{
 int sum(int a, int b){
  int c;
  System.out.println(c);
  return (a+b);
 }
} 

Since “c” is a local variable, when your program tries to access local variable, before initialization, compiler will throw the error.
 
For the above program, you will get below error
LocalVariable.java:5: error: variable c might not have been initialized
            System.out.println(c);
                                          ^
1 error





Instance methods                                                 More about methods                                                 Home

Friday, 31 January 2014

More About primitive types

1. sizes Of primitive data types

Data Type Size (in bytes)
byte 1
short 2
int 4
long 8
float 4
double 8
char 2

boolean: The boolean data type has only two possible values: true and false. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

2. If you are using primitive data types as local variables, then you must initialize the variable before using. Other wise compiler will throw error.

Example
class PrimitiveDeclaration{
 public static void main(String args[]){
  int var1;
  System.out.println(var1);
 }
}

When you tries to compile the above program below error thrown

PrimitiveDeclaration.java:5: error: variable var1 might not have been initialized
 System.out.println(var1);
 ^
1 error

3. Assigning data to compatibility types
Java permits to assign a value of one data type to the value of other if types are compatible. I.e, we can assign a data of float to double, byte to int, char to int etc.,

When you assign a character variable to int variable, then int variables store the Uni code of the variable.

Example
class Compatible{
 public static void main(String args[]){
  char charVar = 'a';
  int intCharVar = charVar;
  byte byteVar = 100;
  short shortVar = byteVar;
  int intVar = shortVar;
  long longVar = intVar;
  float floatVar = longVar;
  double doubleVar = floatVar;
  
  System.out.println(charVar);
  System.out.println(intCharVar);
  System.out.println(byteVar);
  System.out.println(shortVar);
  System.out.println(intVar);
  System.out.println(longVar);
  System.out.println(floatVar);
  System.out.println(doubleVar);
 }
}

Output
a
97
100
100
100
100
100.0
100.0

4. If you are trying to assign data of one type to the other incompatible type compiler will throw error.

Example
class Compatible{
 public static void main(String args[]){
  int intVar = 10;
  boolean a = intVar;
 }
}
While compiling you will get the below error

Compatible.java:6: error: incompatible types
 boolean a = floatVar;
 ^
 required: boolean
 found: float
1 error

5. If you want to assign a higher data type value to compatible lower data type, then you should externally cast it, otherwise compiler will throw an error by saying “possible loss of precision”.

Syntax:  
   dataType value1 = (dataType) value2;

class Compatible{
 public static void main(String args[]){
  double doubleVar = 109.05;
  char ch = doubleVar;
  
  System.out.println(doubleVar);
  System.out.println(ch);
 }
}

while compiling you will get the below error.

Compatible.java:5: error: possible loss of precision
 char ch = doubleVar;
 ^
 required: char 
 found: double
1 error

To solve the above error, we need to cast explicitly like below

class Compatible{ 
 public static void main(String args[]){
  double doubleVar = 109.05;
  char ch = (char)doubleVar;
  
  System.out.println(doubleVar);
  System.out.println(ch);
 } 
}

6. Always assign a value to a float variable by appending “f” to it like below
float floatVar = 10.09f

other wise compiler will throw error.

class Compatible{
 public static void main(String args[]){
  float floatVar = 10.09;
  System.out.println(floatVar);
 }
}

While compiling you will get the below error

Compatible.java:3: error: possible loss of precision
 float floatVar = 10.09;
 ^
 required: float
 found: double
1 error

To solve the above error define the float variable like below
    float floatVar = 10.09f;

Data Types in Java                                                 Operators in Java                                                 Home