Pages

Saturday 3 November 2012

Wrapper class - Introduced in JDK 1.5

The classes specifically meant for Primitive Datatypes.

boolean -> Boolean
char-> Character
byte->Byte
short->Short
int->Integer
long->Long
float->Float
double->Double

sometimes it is required to treat a primitive types into an Object type.
so to achieve this wrapper classes are included in Java which are available in java.lang package.

How to Wrap primitive into Object
int x =9; x is a primitive.
Integer y = new Integer(x); y is an Object

How to Unwrap Object into Primitive
int x = y.intValue();
now x is again a primitive.
similarly we have repective methods in each wrapper class to get primitive for it.

before 1.5 -
ArrayList l = new ArrayList();
l.add(new Integer(3));

1.5 onwards
ArrayList l = new ArrayList();
l.add(3);

The above concept is autoboxing...will see in next post...

Tuesday 16 October 2012

Static method and Static variable

Static method -

1)Static methods can be called by its class name instead of calling by reference.
2)A class containing only Static methods not required to be instantiated hence such class can be used for reusablity.
3)Inside a Static method - non static members cant be accessed but can declare non static references.
4)Static members will load at the time of loading a class and only once in the entire application.

public class Staticexample
{
private int i;

public static void main(String args[])
  {
System.out.println(i);// Error - "i" is a non static
  }

}



Static variable
1)it is one value per Class instead of one value per instance.
2)A class gets a single copy of a variable and all the instances of that class share the same copy.
3)All the static variables of a class are getting initialized before its object is getting created.
4)Default value will be assigned to static variable automatically based on the type if its not initialized explicitely.
5)Static variable should be accessed by a class name for the best usage of static rule.

public class StaticVariable
{

static int x=0;
}

public class StaticVariableUsage
{

public static void main(String args[])
  {
System.out.println(StaticVariable.x);
  }
}

Quiz

is it static variables are loaded first or static methods are getting loaded first ?


whtas the o/p
1)public class A{
static int i;
public void print(){
System.out.println(i);
}
}


2)public class B{
int i;
public static void go(){
System.out.println(i);
}
}

Sunday 23 September 2012

Memory Management in Java

Instance variables vs Local variables

Instance variables represents the attributes for each instance(Object) of the class.

for every instance , same instance variables with different state(values).

Local variables are those variables which are local to method.
they are declared inside a method and also declared as a parameter to method.

Stack - is a place where all the local variables and method invocations live.

Heap - is a place where all the objects live.

observe the program below

package pack1;

public class Memory_Mgmt {
String s1;
int a;

public static void main(String[] args) {
new Memory_Mgmt();
show(10);

}
static void show(int j){
System.out.println(j);
}

}



check out the solution of memory allocation to the above program in the diagram given below.

Question

Where the reference variables will get stored stack or heap ?
( Memory_Mgmt m = new  Memory_Mgmt () , here m is the reference variable)

Friday 21 September 2012

Interface in java ?

The one which is having all the methods abstract in it .

 Any subclass which is implementing the interface
should implement all of its methods to become concrete class otherwise it should become abstract class.

interface = 100% pure abstract class.

about members of an interface

1) All the members are public by default. and it should be public only(means we cant make private or protected).

2)The variables are static and final by default.

3)The methods are abstract by default.(method implementation inside the interface is not not not possible).


Rules to remember -

1)Interface variables are public static and final

2)Interface methods are public abstract .

3)We cant modify the above 2 rules so it is good to remember those rules.

Why interface ?
To achieve multiple inheritance.

observe the below  problem




1) To include MTECH and MBA common behaviors we have a parent class PG
but to include MTECH specific behaviors we dont have any other parent  other
than PG. So if you include them in PG they will be inherited automatically to MBA which is irrelevant to MBA.

       So how do we include MTECH specific behaviors in any super class other than PG and also MTECH should be sub class to PG and the parent which holds MTECH specific behaviors (which results in MTECH should have two parents) which is called multiple inheritance .

But  it is not supported in java. so the solution is as below

        Make one interface which is parent to MTECH class and let it have only MTECH specific behaviors
and MTECH class should implement this interface and extends  PG class.
Now MBA class extends only PG class and doesn't implement MTECH specific interface. So in that way it will not have MTECH specific behaviors inside MBA class (which are not required to MBA)
   


See the below diagram for the solution to the first diagram by making use of great concept in java
   i.e;  " INTERFACE "













Friday 14 September 2012


Topic   Abstract class – very important topic in Java.

Pre-requisite : Abstract method
Any method that does not have a body(open and closing curly brace) instead ends with a semicolon  is called Abstract method.
Ex: public void display();
But how do you tell this to the compiler , very simple
Public  abstract void display();

Abstract  class – any class in java which has at least one  abstract method must be declared as Abstract class.

public abstract class Employee {

Public  abstract void display();

}
What happens if I don’t declare as Abstract in that case ?
Simple – compile time error.

Whenever we  declare any class as an abstract it means we cant instantiate that class.

Instantiate –creating an object for the class.

So Employee emp = new Employee(); - is wrong. Compile time error.

So what is the use of abstract class if we are not able to instantiate it ?
Answer is Polymorphism.

Polymorphism – methods which behaves differently in different situations.
Any class which extends abstract class and implements all the unimplemented  methods of abstract class becomes concrete class.

We can  now store the object of concrete class inside a reference variable of Abstract class.
Yes …got confused  how  its polymorphism?  Analyze  the simple  below program carefully.

package pack1;

import sun.security.action.GetLongAction;

abstract class Employee {
     
public abstract int getLeaves();
}

class PermanentEmployee extends Employee{
static int leaves = 20;

      public int getLeaves() {
           
            return leaves;
      }
     
}

class ContractorEmployee extends Employee{
      static int leaves = 10;
     
      public int getLeaves() {
           
            return leaves;
      }


}

public class EmployeeMain{

      public static void main(String[] args) {
            Employee pEmp = new PermanentEmployee();
            Employee cEmp = new ContractorEmployee();
            System.out.println("permanent employee leaves");
            System.out.println(pEmp.getLeaves());
           
            System.out.println("Contractor employee leaves");
            System.out.println(cEmp.getLeaves());
           
           
      }
     
     
}

so same method  getLeaves() behaves differently in different situations in the above program.


Both pEmp and cEmp are of type Employee and we are calling getLeaves() method, but they are printing different values. How ?

Compiler looks at the type of a variable at the compile time but at run time it looks for the variable content(ie where it is pointing).
Since here both pEmp and cEmp are both of type Employee at compile time but at run time both are pointing to different objects.
This behavior is called polymorphism.


Quiz  ??

1)can we declare class as an abstract if it does not contain even a single abstract method ?
2)in the above program can we write like this
PermanentEmployee pEmp = new Employee ();








Sunday 9 September 2012

Topic - Reading input from keyboard

In C we have scanf() function to read the data from the keyboard.
In C++ we have cin>> operator for the same.

what about the same in java ?

answer is  Scanner class with single parameter to Scanner() constructor ie System.in.

the code goes like this

Scanner sc = new Scanner(System.in);
 System.out.println("enter name");
String name = sc.next();
System.out.println("enter age");
int age = sc.nextInt();
System.out.println("name is "+name+" age is "+age);


amazing output is
enter name
kb
enter age
24
name is kb age is 24.

in the above code we passed System.in to Scanner() constructor which points to input stream.
so using scanner object we can read data from keyboard.
next() method always reads String.
nextInt() reads integer value
for byte value use nextByte() and so on for the respective type of data.

Scanner() constructor takes an argument which decides from where the data has to read, whether from file or from input stream or from some variable.

Based on above understanding predict the output of the following piece of code

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
System.out.println(s.next());
s.close();

Friday 7 September 2012


when we write our class in java, it is not full pledged one.
in fact more than 95% of developers wont write full pledged program
so compiler will convert our program into full pledged program.

1)our program
SoftwareEngineer.java

public class SoftwareEngineer {
      String name;
     static double salary;

      public SoftwareEngineer() {
            name = "kb";
             salary=20000;
      }
      void print(){
            System.out.println(name);
            System.out.println(salary);
      }
      void change(String new_name,double new_salary){
            name=new_name;
            salary=new_salary;
      }
     

}

The same  program after compiling becomes like this

2) full pledged program created by compiler
SoftwareEngineer.class

public class SoftwareEngineer extends Object {
      String name;
    static double salary;

      public SoftwareEngineer(SoftwareEngineer this) {
            super(this);
            this.name = "kb";
            SoftwareEngineer.salary=20000;
      }
      void print(SoftwareEngineer this){
            System.out.println(this.name);
            System.out.println(SoftwareEngineer.salary);
      }
      void change(SoftwareEngineer this,String name,double salary){
            this.name=name;
            SoftwareEngineer.salary=salary;
      }
     

}

What all the things compiler added to make our program into full pledged one
1)making Object class as a super class to our class.
Every class in JAVA has Object class as the super class.

2)constructor and other methods got one extra argument 
Yes every method will get one extra argument of type current class which is named as "this".

3)constructor got one extra statement
Yes Every constructor must have the first statement as either super() or this() with or without the arguments.
if we dont write any one of those as the first statement inside constructor , compiler will automatically add super(this) as the first statement inside the constructor.

so try to explain what is "this" and where and all its added. and what is its significance in the program.

also try to figure out why there is no this.salary  in place of SoftwareEngineer.salary   inside a constructor ?

System class - Basic Concept  in  java, Java programmers must know it


explain System.out.println();

System is a final  class in java , we are using class name to access out (which is a reference variable of PrintStream class) that means out is a static member of System class.
so System.out returns us the PrintStream object so following line of code looks different but it is valid is valid
PrintStream p1 = System.out;

println(char[] a) is a non static method inside PrintStream class whose job is to print the passed data.

by default PrintStream object points to console , so System.out.println("data");  prints data on the console.

 System.out.println("data");  is same as p1.println("data");  


Check your knowledge now

main(){
PrintStream p1 = new PrintStream("stdout.log");
p1.println("hello");
System.out.println("world");
}

Based on the above knowledge what will be the output ?