Monday, July 30, 2012

JAVA REFLECTION

Code:


I have the following class.



package pd.tutorials.practice;

public class Employee {
public String name;
public double salary;
public int age;
public String employeeId;
static{
System.out.println("static block called");
}
public Employee()
{
System.out.println("Employee constructor called");
}
public Employee(String name1, double salary, int age, String employeeId)
{
name = name1;
this.salary = salary;
this.age = age;
this.employeeId = employeeId;
}
//overriden method
public String toString() {
return name + ", " + salary + ", " + age + ", " + employeeId;
}

}



package pd.tutorials.practice;


public class TryCollections {

public static void main(String a[]) {
try {
                        // loads the class. calls static block
Class.forName("pd.tutorials.Employee");
//define type of constructor a class may have
Class[] paramType = {String.class, Double.TYPE, 
Integer.TYPE, String.class};
//asking if the class has the constructor type defined above
Constructor<Employee> con = Employee.class.getConstructor(paramType);
System.out.println("No error means...found the constructor");
//if constructor is found, create values to pass to constructor
Object [] paramValues = {"Pratik Dave",
new Double(10000), 
30,
"539622"
};
// calls the constructor
Employee emp = con.newInstance(paramValues);
System.out.println(emp.age);
} catch (Exception ex) {
ex.printStackTrace();
}

}

}

Sunday, July 22, 2012

JAVA CUSTOM DATA TYPES


Custom data types is data type (which can hold value) but created by you.

Let us say, I have a class Dog.

public class Dog
{
public String breed;
public String name;
public float weight;

public void bark()
{}

public void play()
{}

}

So, looking at the class structure, it can store value of breed, name and weight. 
So this is different than the int datatype which can store single integer value.

So if I want a person class to hold all values associated with dog, I take a variable to type Dog class.

public class Person // [access modifiers] [class - the keyword] [class_name]
{
// [access modifiers] [datatype] [variable_name]
public String name; 
public int age;
public char gender;
public Dog dog; // not a int or char datatype but a Dog type.

[access modifiers] [return type] [method_name]
public void walk()
{}

public void eat()
{}

public void run(int kms)
{}

}

So, every  java class is a custom data type.


JAVA DATATYPES

The datatypes are used to store the values I may want to work on.


byte
short
int
long
float
double
boolean


These are also called primitive datatypes.


I won't discuss the max values each datatype can store and differences among the datatypes. I also won't discuss the Operators here.


Yet, one thing that is important to discuss is Wrappers for the primitive datatypes.


byte - Byte class
short - Short
int - Integer
long - Long
float - Float
double - Double
boolean - Boolean


I will discuss what are Custom datatypes when we discuss Class & Objects.

JAVA CLASS & OBJECTS

Java thinks in terms of objects. Lets take my example...
I am a person. So Person becomes a class.


I have my name, age, gender, address. These are my attributes which become properties/class variables of class.


I walk, eat, sleep, run, work etc., These are my behaviors, which becomes methods/functions of a class.


public class Person // [access modifiers] [class - the keyword] [class_name]
{
// [access modifiers] [datatype] [variable_name]
public String name; 
public int age;
public char gender;


[access modifiers] [return type] [method_name]
public void walk()
{}


public void eat()
{}


public void run(int kms)
{}


}


Now obviously, I AM (not) LEGEND. I communicate with lot other objects. e.g.., Organization (my company), other Persons, my Pet, my Vehicle, my Bank etc... So the objects I communicate with may similar objects (like Person) or objects of other type (like Vehicle, Pet, Bank etc..).


public class Dog
{
public String breed;
public String name;
public float weight;


public void bark()
{}


public void play()
{}


}




public class Bank
{
public String bankName;
public String address;


public void openAccount()
{}


public void transferMoney(float amount)
{}


}





Wednesday, July 18, 2012

EXCEPTIONS

Exception Handling


Any deviation from the current flow is termed as exception.


I have lived my days when my Mom used to give some money and instructions to buy list of items from the market. I happily took the money and paddled my cycle through the roads to the market unaware of exceptional condition that may confront me.


1) My cycle gets punctured
2) I run out of money
3) I don't get item(s) from the market and so on ...


These abnormal conditions which may stop me from completing my responsibilities are called exceptions. They may occur to me naturally or because of my irresponsible behavior. Now, I may be smart to be able to come out of these exceptional conditions.


1) I get the puncture repaired
2) I buy credit from the shop
3) these one, I may not be able to overcome ...


try, catch, throw
The truth that I try going to market and do things is similar to the code in the try block that is tried to run.


public class Myself{


public void doThingsForMom()
{
try{


// buy listed items
// your code goes here


} // end try block


} // end method


} // end class


I say the nature threw these conditions upon me is similar to the exceptions that JVM throws in my class.


The truth that I tried to handle the exceptional situation is similar to the catch block that catches the exception that gets throwed.



public class Myself{

public void doThingsForMom()
{
try
{

// your code goes here

} // end try block
catch(OutOfMoneyException)
{
}

} // end method

} // end class

throw, throws
There is a unique thing that happens here. I become a MAN out of Mama's boy as I take the conditions and handle it myself and my mom does not even know a thing that happened to me. 

But in programming a calling method would like to know the exceptions that occur instead the callee method handling it silently. i.e. there is a need to propagate the exception.

public class Son{

public void doThingsForMom() throws IMayBeLateException


// when Mom asks me toDoThings I let her know first hand that I may be late ... so she prepares herself that I may get late


{
try
{

// your code goes here
// if getting late - throw new IMayBeLateException();

// if running out of money - throw new OutOfMoneyException();

} // end try block
catch(OutOfMoneyException ex)
{
// buy credit
}

} // end method

} // end class



public class Mom
{
public void toDoList()
{
Son dearSon = new Son();

try{


dearSon.doThingsForMom(); 


// so now mom needs to handle the exceptional condition when her son will be late


}catch(IMayBeLateException ex)
{
// she does not get tensed
}
} // end method


} // end class

Custom Exception

You can create your own exception by extending(IS-A) the Exception class.

public class IMayBeLateException extends Exception 
{

public void toString()
{
}

}


ACCESS MODIFIERS


Access Modifiers:
public – accessible within the class, within the same package and outside the package.

protected – accessible within the class, within the same package. It is accessible outside the package, but only to the class that is a subclass. Also it will be accessible only on the object of child, still not accessible on the object of Parent.

default -  accessible within the same class and within the same package. Not accessible outside the package.

private – accessible only within the same class.

Let us review these access modifier by taking and example of ATM.
We will make 2 packages with atleast 1 class in each of them.

package mybank.atm;

public class Atm
{
            public String bankName;
            public String location;
            String policeContactNo;
private cashInAtm;

public float withdrawMoney(String cardNo)
{
            // anybody should be able to withdraw money
}

protected void getDaysTransaction(String cardNo)
{
            // should be available t
}
           
           

private getTotalCashInAtm()
            {
                        // no one needs to know what is the total cash in ATM
            }

            void callPolice()
{
// bank can make an automated call to police if somebody tries to vandalize the ATM
// the security guard can also make a call to police if suspects any robbery at ATM
}

}




package mybank.customer;

public class Customer
{
            public String customerName;

            public static void main(String args[])
            {
                        Atm atm = new Atm();
            atm.withdrawMoney(“”);
                        atm.callPolice(); // will give compilation error
            atm.getTotalCashInAtm(); // will give compilation error
}
}


package mybank.atm;

public class SecurityGuard
{
            public String guardName;

            public static void main(String args[])
            {
                        Atm atm = new Atm();
            atm.withdrawMoney();
                        atm.callPolice();
            atm.getTotalCashInAtm(); // will give compilation error
}
}

PLATFORM INDEPENDENCE


Platform Independent:

All the earlier programming language compiles a piece of code that can be then run to get the desired output.  The problem with the code that is generated after the compilation is that, it can run only on the machine that it was created.

All software (including games) comes with a specification that it needs a specific OS platform to run on. So if you had bought a FIFA 2012 for WINDOWS and then you also got a MAC, you cannot run the same FIFA 2012 on MAC. 

Same thing happens with the code generated from earlier programming language. You cannot take the code that was generated on WINDOWS and run it on MAC or LINUX.

So if you can produce some kind of platform that can run on top of all OS platform and let your platform run the code generated from your programming language. Your platform can understand these codes and no matter what OS platform is beneath, you can generate the same output everytime.

For eg.,  You understand only one language. You may not be able to understand the languages of other countries when you visit them. So you install a person to every country you visit and he knows which language you know and he translates that country’s language your language.

The platform (virtual machine) that SUN creates for every OS platform is called as JVM (Java Virtual Machine). It is virtual because you cannot feel it or see it. It installed and it just there.

JRE and JDK

Not let us understand 2 parts of any application creation. Every time you write a program you use the language compiler to compile the program. The Java compiler (javac) checks the syntax and semantics of your code and makes sure that it can be run later.

The compiler is a part of JDK (Java Development Kit) but helps you to write Java programs.

Java provides some predefined and precompiled collections of code (rt.jar, tools.jar) that you can use. The collection is a part of JRE (Java Runtime Environment). JRE also supports to run your compiled code.  In a nutshell, JRE provides the environment that may be necessary to run any Java program.

Let us now bring JDK, JRE and JVM together.
You will be writing java code in .java files. You will then compile this .java file using java compiler (javac). Java compiler to create a .class file at the end of compilation. The good thing about this .class file it that, it runs of JVM and not directly on OS platform.

This is how all the 3 superheroes come together to give you platform independence.