Pages

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Wednesday, 11 September 2013

Exception - tricky interview questions

1) find the o/p of the following


package com.kb.client;

public class Exception1 {

 
 public static void main(String[] args) {
  String value = getValue();
  System.out.println(value);

 }

 private static String getValue() {
  
  try {
   System.out.println("before return from try");
   return "from try";
   
  } catch (Exception e) {
   System.out.println("before return from catch");
   return "from catch";
  }
  finally{
   System.out.println("before return from finally");
   return "from finally";
  }
 }

}
 
here when the control enters the try block it first prints the first line 
before return from trythen it has return statement , but finally should execute before try completes so control goes to finally, it prints finally block's first statement
 and it finds the return statement there so it returns from finally.
so output would be
 
before return from try
before return from finally
from finally
 
 
now i will put exception statement in try block as below
 
package com.kb.client;

public class Exception1 {

 
 public static void main(String[] args) {
  String value = getValue();
  System.out.println(value);

 }

 private static String getValue() {
  
  try {
   int i = 10/0;
   System.out.println("before return from try");
   return "from try";
   
  } catch (Exception e) {
   System.out.println("before return from catch");
   return "from catch";
  }
  finally{
   System.out.println("before return from finally");
   return "from finally";
  }
 }

}
 
in this case find the o/p ?

as explained above but try gets with the exception so catch starts execution and executes finally before catch returns so 
the o/p will be as below 

before return from catch
before return from finally
from finally

now if we comment return from finally for the above program as below

package com.kb.client;

public class Exception1 {

 
 public static void main(String[] args) {
  String value = getValue();
  System.out.println(value);

 }

 private static String getValue() {
  
  try {
   int i = 10/0;
   System.out.println("before return from try");
   return "from try";
   
  } catch (Exception e) {
   System.out.println("before return from catch");
   return "from catch";
  }
  finally{
   System.out.println("before return from finally");
   //return "from finally";
  }
 }

}
 
now in this case try as soon as get exception control goes to catch and catch executes first line and before executing return it goes to finally and executes first line .
since return in finally is commented it goes back to catch and executes return from catch.
so o/p would be as below

before return from catch
before return from finally
from catch


 

Saturday, 1 June 2013

Serialization and externalization in java

Serialization is the process of writing an object state into the file.
state of an object means atrributes and its values and in future if we need that object we can rebuild it from the file and  we call that process as "de serialization"
so to achive serialization in java,  any class must implement one marker interface.
that marker interface is "serializable".
lets understand this process through below example
package com.kb.model;

import java.io.Serializable;

public class Employee implements Serializable{

 private String name;
 private int age;
 private String designation;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getDesignation() {
  return designation;
 }
 public void setDesignation(String designation) {
  this.designation = designation;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

package com.kb.client;

import java.io.File;

public class Serialize {

 public static void main(String[] args) {
  Employee emp = new Employee();
  emp.setAge(25);
  emp.setDesignation("se");
  emp.setName("kb");
  File file = new File("employee.ser");
  FileOutputStream fout = null;
  ObjectOutputStream oout = null;
  try {
   fout = new FileOutputStream(file);
   oout = new ObjectOutputStream(fout);
   oout.writeObject(emp);
  } catch (IOException e) {
  } catch (Exception e) {

  }

  finally {
   if (oout != null) {
    try {
     oout.flush();
     oout.close();
     oout = null;
    } catch (IOException e) {
     e.printStackTrace();
    }
    if (fout != null) {
     try {
      fout.close();
      fout = null;
     } catch (IOException e) {
      e.printStackTrace();
     }

    }
   }
  }
 }

}


when we execute the above program, one file gets created in our project names as "employee.ser". this file contains the information about the employee object which we have written into this file.
this process is called serialization.

Now lets see de-serialization.
its just reading a serialized object from the file into the object back.
means retaining the object state.
lets do it as below
package com.kb.client;

import java.io.File;

public class DeSerialize {

 public static void main(String[] args) {
  File file = new File("employee.ser");

  FileInputStream fin = null;
  ObjectInputStream oin = null;

  try {
   fin = new FileInputStream(file);
   oin = new ObjectInputStream(fin);
   Employee emp = (Employee) oin.readObject();
   System.out.println(emp.getAge());
   System.out.println(emp.getDesignation());
   System.out.println(emp.getName());
  } catch (Exception e) {
   // TODO: handle exception
  }

  finally {
   if (oin != null) {
    try {
     oin.close();
     oin = null;
    } catch (IOException e) {
     e.printStackTrace();
    }
    ;

   }

   if (fin != null) {
    try {
     fin.close();
     fin = null;
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  }

 }

}

now run the above program and see the below output


25
se
kb

Remember in serialization
1)If we dont want to save any of the attribute from the serializable class then we can make such attributes as "transient".
2)all static fields can not be serializable sine its a class attribute not a object attribute.

in the above example if we dont want to save attribute designation then make it as transient as below
transient String designation;
then run both the program, in the output we can see "null " for that designation in the de-serializable program output.

now what if the employee class has address class reference and if address class is not serialized then while serializing employee object we will get an exception

scenario explained above through program is as below
address class - not implemented serializable interface.

package com.kb.model;

public class Address {
 private String street;
 private String location;
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getLocation() {
  return location;
 }
 public void setLocation(String location) {
  this.location = location;
 }

}
now consider below employee class
package com.kb.model;

import java.io.Serializable;

public class Employee implements Serializable{

 private String name;
 private int age;
 private transient String designation;
 private Address address;
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getDesignation() {
  return designation;
 }
 public void setDesignation(String designation) {
  this.designation = designation;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public Address getAddress() {
  return address;
 }
 public void setAddress(Address address) {
  this.address = address;
 }
}
now see the below client program to serialize
package com.kb.client;

import java.io.File;

public class Serialize {

 public static void main(String[] args) {
  
  
  Employee emp = new Employee();
  emp.setAge(25);
  emp.setDesignation("se");
  emp.setName("kb");
  Address address = new Address();
  address.setLocation("bang");
  address.setStreet("rajajinagar");
  emp.setAddress(address);
  File file = new File("employee.ser");
  FileOutputStream fout = null;
  ObjectOutputStream oout = null;
  try {
   fout = new FileOutputStream(file);
   oout = new ObjectOutputStream(fout);
   oout.writeObject(emp);
   System.out.println("done");
  } catch (IOException e) {
  } catch (Exception e) {

  }

  finally {
   if (oout != null) {
    try {
     oout.flush();
     oout.close();
     oout = null;
    } catch (IOException e) {
     e.printStackTrace();
    }
    if (fout != null) {
     try {
      fout.close();
      fout = null;
     } catch (IOException e) {
      e.printStackTrace();
     }

    }
   }
  }
 }

}
run this , we will end up with an exception "not serializable exception"

so to serialize any object , if its clas is having any derived type reference like address then those derived types class must also be serialized first otherwise we will end with the above exception.

we will see about externalization and its flexibility and advantages over serialization in next post.

Thanks for reading

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 ?