Posts

Showing posts from October, 2011

SCJP 6 Questions: Pass by reference with example

Image
See the code:


class GFC304 { static void m1(int[] i1, int[] i2) { int[] i3 = i1; i1 = i2; i2 = i3; } public static void main (String[] args) { int[] i1 = {1}, i2 = {3}; m1(i1, i2); System.out.print(i1[0] + "," + i2[0]); }}What will be the output?Answer: 1,3Explanation: Here we are passing the copy of reference variables i1 and i2 from main() method to method m1(). Now m1 has it's own local reference variables i1 and i2 referring to same array as main()method's i1 and i2. So you can see that we are only passing the reference variables not exactly the value they are refering.See this figure... Now see the second code.......
class GFC305 { static void m1(int[] i1, int[] i2) { int i = i1[0]; i1[0] = i2[0]; i2[0] = i; } public static void main (String[] args) { int[] i1 = {1}, i2 = {3}; m1(i1, i2); System.out.print(i1[0] + "," + i2[0]); }}What will be the output?Answer: 3,1 Explanation: Here in the m1() method we are pass…

SCJP 6 Questions: Widening, autoboxing and varargs in overloading

The code is given:

3.  public class Bertha {
4.    static String s = "";
5.    public static void main(String[] args) {
6.        int x = 4; Boolean y = true; short[] sa = {1,2,3};
7.        doStuff(x, y);
8.        doStuff(x);
9.        doStuff(sa, sa);
10.       System.out.println(s);
11.   }
12.   static void doStuff(Object o) { s += "1"; }
13.   static void doStuff(Object... o) { s += "2"; }
14.   static void doStuff(Integer... i) { s += "3"; }
15.   static void doStuff(Long L) { s += "4"; }
16. }

What is the result?
A. 212
B. 232
C. 234
D. 312
E. 332
F. 334
G. Compilation fails

Answer:  A is correct. 

Explanation: It's legal to autobox and then widen. The first call to doStuff(), x is boxed from int to an Integer then passes these two objects (Integer,Boolean) to varargs (Object.... 0).

The second call cannot widen and then box (making the Long method unusable), so it boxes the int to an Integer. And then it goes to doStuff(Object o) because Intege…

Overloading with widening, boxing and Varargs

Overloading with Boxing and Var-args

class AddBoxing {
  static void go(Integer x) { System.out.println("Integer"); }  
  public static void main(String [] args) {
     int i = 5;
     go(i); 
  }
}

Answer: Integer


class AddBoxing { 
  static void go(long x) { System.out.println("long"); }
  public static void main(String [] args) {
     int i = 5;
     go(i); 
  }
}

Answer: long

Now see...

class AddBoxing {
  static void go(Integer x) { System.out.println("Integer"); }
  static void go(long x) { System.out.println("long"); }
  public static void main(String [] args) {
     int i = 5;
     go(i); // which go() will be invoked?
  }
}

If it is given that both methods exist, which one will be used? In other words, does the compiler think that widening a primitive
parameter is more desirable than performing an autoboxing operation?
The answer is that the compiler will choose widening over boxing, so the output will be

long


The compiler will choose the older style before i…

SCJP 6 Questions: Garbage collection

Image
Qu1. See the code ...

3.   class Dozens { 4.      int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12}; 5.   } 6.   public class Eggs { 7.         public static void main(String[] args) { 8.               Dozens [] da = new Dozens[3]; 9.               da[0] = new Dozens(); 10.             Dozens d = new Dozens(); 11.             da[1] = d; 12.             d = null; 13.             da[1] = null; 14.            // more code 15.       } 16.  }
Which two are true about the objects created within main(), and eligible for garbage collection when line 14 is reached?
A. Three objects were created B. Four objects were created C. Five objects were created D. Zero objects are eligible for GC E. One object is eligible for GC F. Two objects are eligible for GC G. Three objects are eligible for GC
Answer: C and F are correct.
Explanation: When you compile and run,  main method from Eggs runs and object creation starts from line 8. It is first object which is a 1 D array object created.
Now at line 9, Dozens() class no-arg constructor c…

Interview Question @ IBM: Write your own generic class

Qu1: Can you write a small generic class by yourself ?

Answer: This could be like this......


public class GenericClassDemo<X, Y> {
   X name;
   Y age;


   GenericClassDemo(X name, Y age) {
      this.name = name;
      this.age = age;
   }


   X getX() { return name; }


   Y getY() { return age; }


   // test it by creating it with <String, Integer>


  public static void main (String[] args) {


       GenericClassDemo<String, Integer> obj= 
                     new GenericClassDemo<String, Integer>("Rajesh Kumar", 15);


       String empName = obj.getX();    // returns a String


       int empAge = obj.getY();    // returns Integer, unboxes to int


       System.out.println("Generic use::: EmpName  :"+empName +" and EmpAge :"+empAge);
}
}
----------------------------------------------------------------------------
Qu2.Create your own custom generic class using wildcard ?

Answer: Let's take an example..
---------------------------------------

abstract class …

Ploymorphism with Generics in Java 5 or later

Ploymorphism with Generics

Generic collections give us sane advantages of type safety that we have always had with arrays, but there are some crucial differences

Most of these have to do with polymorphism.
You've already seen that polymorphism applies to the "base" type of the collection:

List<Integer> myList = new ArrayList<Integer>();

In other words, we were able to assign an ArrayList to a List reference, because
List is a supertype of ArrayList.

But what about this?

class Parent { }


class Child extends Parent { }


List<Parent> myList = new ArrayList<Child>();

No, it will not work.

Rule : The type of the variable declaration must match the type you pass to the actual object type. If you declare List<Parent> parentList then whatever you assign to the foo reference MUST be of the generic type <Parent>. Not a subtype of <Parent>. Not a supertype of <Parent>. Just <Parent>.


Wrong:
List<Object> myList = new ArrayList&l…

Android 4 ice cream

Image
See latest from Android...


Undestanding hashCode() and equals() on using Map

Understand hashCode() and equals() in HashMap

Always remember that when you are using a class that implements Map or any classes that you
are using as a part of the keys for that map must override the hashCode() and equals()
methods.

Let's see the following example....


-----------------------------------
import java.util.*;


class MapEQ2 {
  public static void main(String[] args) {
       Map<ToDos, String> m = new HashMap<ToDos, String>();

       ToDos t1 = new ToDos("Monday");
       ToDos t2 = new ToDos("Monday");
       ToDos t3 = new ToDos("Tuesday");
       System.out.println("Putting first object::");
       m.put(t1, "doLaundry");
       System.out.println("\n Putting second object::");
       m.put(t2, "payBills");
       System.out.println("\n Putting third object::");
       m.put(t3, "cleanAttic");
       System.out.println("\n Map size ::"+m.size());
       System.out.print…

Split cell if data exceeds in itext pdf API

When we insert a big data into a cell then it inserts a page break and goes to next page automatically....

To solve this we can use  setSplitLate(false) method on table to be created in itext pdf doc.

See the complete code here......


package com.example;


import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;


import java.io.FileOutputStream;


public class PdfTableExample {
  public static void main(String[] args) {
 System.out.println("Going to create pdf...");
    Document document = new Document();


    try {
      PdfWriter.getInstance(document, 
    new FileOutputStream("C://Test.pdf"));


      document.open();


      PdfPTable table = new PdfPTable(1); //1 column.


      String text="Test summary::: bciovjbozxcmbzxmb xcvboixzcjbocvb zxcvbizxjvbiozx]cblozxjiboz cbxscvxukcunbx zxizucvhix czuivh xcvzxblzxckbnx bx…

Create Nested table inside a table on a pdf document using iText

Nested table in iText to cerate pdf using Java Suppose you are using iText to create pdf document using java, then this program will help you to create a table inside a table.

------------------------------------------------------------------

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;


import java.io.FileOutputStream;


public class NestedTableExample {
  public static void main(String[] args) {
    Document document = new Document();


    try {
      PdfWriter.getInstance(document, 
    new FileOutputStream("NestedTableDemo.pdf"));


      document.open();


      PdfPTable table = new PdfPTable(2); // 2 columns.


      PdfPCell outerTableCell1 = new PdfPCell(new Paragraph("Outer Table :Cell 1"));
      PdfPCell outerTableCell2 = new PdfPCell(new Paragraph("Outer Table :Cell 2"));



      PdfPTable nestedTable = new PdfPTable(3);
      n…

How to add custom marker on Static Map

Please see the folowing URL:


http://maps.googleapis.com/maps/api/staticmap?size=512x512&maptype=roadmap\&
markers=size:mid|color:blue|icon:http://knowledgeserve.in/images/logo.png|San+Francisco,CA|Oakland,CA|San+Jose,CA&sensor=false

See icon: http://knowledgeserve.in/images/logo.png , here you can give the image path, wherever it is..
So change your image link and then copy and paste this URL.

Session timeout interceptor in struts 2

Interceptor continue.....
If you want to use an interceptor which will check whether the session has been expired or not, if it is expired then it will forward to global view( like any jsp that you want to display after session timeout).

You need to do the following coding...
1) Make an interceptor file SessionCheckInterceptor .java

----------------------------------------------------

package com.example.web.interceptor;


import java.util.Map;


import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.vicwalks.web.util.LogManager;
import com.vicwalks.web.util.VicWalkConstants;


public class SessionCheckInterceptor implements Interceptor {

private static final long serialVersionUID = 1L;


public void destroy() {
LogManager.info(this," SessionCheckInterceptor destroy() is called...");
}


public void init() {
LogManager.info(this," SessionCheckInterceptor init() is called...");
}


public…