Java


26
Mar 11

How to get cookie value in Java

Cookies come as part of the HttpServletRequest object.  The below code should help you retrieve cookie values that you have set on a client’s browser.

 

Cookie[] cookies = servletRequest.getCookies();

if (cookies != null) {
 for (Cookie cookie : cookies) {
   if (cookie.getName().equals("cookieName")) {
     //do something
     //value can be retrieved using #cookie.getValue()
    }
  }
}

28
Apr 09

javac bug – no unique maximal instance

While trying to compile my java class files with the 1.6 java compiler, I came across an error message that read :

no unique maximal instance exists for type variable U with upper bounds U

The weird thing was that the file compiled just fine in eclipse!

On further probing I realized it’s a javac bug (check the bug here)

Here’s the workaround -

Bug Scenario :

public class SomeObject {

<U extends SomeObject> U foo1() throws Exception {

SomeObject obj = new SomeObject();
return obj.foo1();
}

}

Solve this way :

public class SomeObject {

<U extends SomeObject> U foo1() throws Exception {

SomeObject obj = new SomeObject();
return obj.<U>foo1();
}
}


4
Jul 08

Method overriding and overloading in Java

I know this may be trivial for many people but then it can be pretty confusing for new bees (pssst.. in the beginning me too used to be confused between overloading and overriding)

OVERRIDING – when you extend a class and write a method in the derived class which is exactly similar to the one present in the base class, it is termed as overriding.

Example:

public class BaseClass{

public void methodToOverride()

{

//Some code here

}

}

public class DerivedClass extends BaseClass{

public void methodToOverride()

{

//Some new code here

}

}

As you can see, in the class DerivedClass, we have overridden the method present in the BaseClass with a completely new piece of code in the DerivedClass.

What that effectively means is that if you create an object of DerivedClass and call the methodToOverride() method, the code in the derivedClass will be executed. If you hadn’t overridden the method in the DerivedClass then the method in the BaseClass would have been called.

OVERLOADING -  when you have more than one method with the same name but different arguments, the methods are said to be overloaded.

Example:

public class OverLoadingExample{

public void add(int i, int j)

{

int k = i + j;

}

public void add(String s, String t)

{

int k = Integer.parseInt(s) + Integer.parseInt(t);

}

}

As you can see in the example above, we have the same method add() taking two parameters but with different data types. Due to overloading we can now call the add method by either passing it a String or int :)