Java is the future !: October 2010

Sunday, October 31, 2010

Quiz of the Day | Oct 31, 2010



How many objects will be eligible for garbage collection after the execution of line 9 in the following code?
a.) 8
b.) 14
c.) 15
d.) 16


Solution : This code creates 16 objects of type Double. Out of which, 15 Double objects are created by the iterations of the nested for loops at lines 6 and 7, and one more Double object is created at line 5. The very first iteration of the loop makes the object created at line 5 eligible for garbage collection. With each iteration of the loop, a new object is created and assigned to 'x', and the old (or previously created) object becomes eligible for garbage collection. Only the most recently created object (for i=4 and j=2) is not eligible for garbage collection.

Thus, out of the created 16 objects (including the one created at line 5), a total of 15 objects have become eligible for garbage collection after the execution of line 9.

Actually, as explained in the earlier paragraph, each iteration of the loop (line 8) makes the previously created object eligible for garbage collection. Thus, by the time both nested loops finish their execution (before execution of line 9), a total of 15 objects have become eligible for garbage collection. The execution of line 9 itself does not affect garbage collection in any way. Want to know more?

You can read more about garbage collection at -
http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html
http://www.developer.com/tech/article.php/628881


Source : "Facebook community"

Saturday, October 30, 2010

Quiz of the Day | Oct 30, 2010

Which of the following statements are true about the relationships between the following classes?
a.) A Bar is a Baz
b.) A Foo has a Bar
c.) A Baz is a Foo 
d.) A Foo is a Baz
e.) A Baz has a Bar


Solution : Choices B, C, and E are the correct answers. An instance of the Baz class is also an instance of the class Foo since the Baz class extends the Foo class. So choice C is correct. 

A Baz has a Bar, since instances of the Baz class contain an instance of the Bar class by reference. So choice E is correct. 

A Foo has a Baz, since instances of the Foo class contain an instance of the Baz class by reference. Since a Foo has a Baz, which in turn has a Bar, a Foo has a Bar. So choice B is also correct. 

Choice A is incorrect because Bar does not extend Baz. Choice D is also incorrect because Foo does not extend Baz either. Refer http://cnx.rice.edu/content/m11709/latest/ for more details.


Source : "Facebook community"

Friday, October 29, 2010

Quiz of the Day | Oct 29, 2010

Which of the following statements are true?

a. As soon as the reference count for an object reaches zero, it will be immediately garbage collected.
b. The finalize() method will not be invoked more than once by the JVM on the same object.
c. The finalize() method cannot be overloaded.
d. The garbage collection implementation is JVM-dependent.
e. If the finalize() method is overridden, a call to the super class's finalize() method is inserted automatically by the compiler.


Solution : Choices B and D are the correct answers.

As specified by the Java API documentation, the finalize() method is never invoked more than once by a Java virtual machine for any given object. Also, the garbage collection indeed is implementation-dependent. This is what the Java Virtual Machine Specification (JVMS) has to say about memory management -

"The heap is created on virtual machine start-up. Heap storage for objects is reclaimed by an automatic storage management system (known as a garbage collector); objects are never explicitly deallocated. The Java virtual machine assumes no particular type of automatic storage management system, and the storage management technique may be chosen according to the implementor's system requirements."

Choice A is incorrect because when the reference count for an object reaches zero, it becomes eligible for garbage collection but that *does not* necessarily mean that it will be immediately garbage collected.

It is perfectly legal to overload the finalize() method like any other method. However, the JVM will always invoke the default, no arguments finalize() method. Hence choice C is incorrect.

Choice E is incorrect because if you override the finalize() method, you must explicitly call the superclass' finalize() method. The compiler *does not* automatically insert this call. Want to know more?

You can read more about garbage collection at -http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html
Also, the API documentation of the Object class contains the necessary information about the finalize() method -
http://java.sun.com/j2se/1.4/docs/api/java/lang/Object.html


Source : "Facebook community"

Thursday, October 28, 2010

Quiz of the Day | Oct 28, 2010

Given the following two classes, which statement is true?

Choose one answer. 
a. The code will compile and run only if line 5 is removed. 
b. The code will compile and run only if line 6 is removed 
c. The code compiles and runs, printing "Test" twice. 
d. The code compiles but throws an exception at runtime.


Solution : Choice B is the correct answer.

The code will compile and run only if line 6 is removed. 

Subclasses that are in a package different from that of the superclass can access protected members of the superclass only through inheritance. Such a subclass cannot use a superclass reference to access a protected member.

Line 5 is legal since we are invoking the test() method using the subclass reference itself, it is the inherited method which we are accessing.

However, line 6 will not compile because the subclass is using the superclass reference to call the test() method.

Since the code does not compile, choices C and D are incorrect.

Reference:
http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html


Source : "Facebook community"

Monday, October 25, 2010

Line separator in Java

 Different operating systems use different conventions to mark the ends of lines in text files. 
  • Windows/DOS uses [CrLf] [\r\n] [0x0d 0x0a] to terminate each line.
  • The web, Unix, Linux and Mac OS uses [Lf] [\n] [0x0a] to terminate each line.
  • The older Mac OS 1-9 uses [Cr] [\r] [0x0d] to terminate each line.
If you use the readLine and println methods, Java automatically deals with the platform differences for you.

Monday, October 18, 2010

Java Interview questions: Multiple Inheritance


Recruiting and interviewing is a never ending task for development managers. Sometimes you get help from HR, but you’re still on your own when deciding to hire or not to hire. Or as I’ve written last time in “Java Interview questions: Write a String Reverser”:
Interviewing developers for a programming job is hard and tedious. There are some excellent Guides, like the Joel Guerilla Guide to interviewing, but in the end you need to decide yourself to hire or not to hire. To get a quick idea about their programming abilities I have considered asking the String reverse question.
Beside the String reverse question I have another favorite.

Does Java support multiple inheritance?

Well, obviously Java does not have multiple inheritance in the classical sense of the word. So the right answer should be “no”, or “no, but” or “yes, but”. From there one can explore several ways. Mostly I start by asking if the Java language designers were too stupid to implement multiple inheritance? Why did the C++ guys implement it then? We mostly land at the Diamond Anti-Pattern then:
In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?
The other way to explore is how Java “emulates” multiple inheritance? The answer, which might already have surfaced, ist Interfaces. We then usually discuss interfaces in Java, if, when and how the candidate has used them in the past. What are interfaces good for, does he like them? I can explore how good he is at modelling and sometimes make him draw a diagram with interfaces. We go on with problems of interfaces in Java, and what happens when two interfaces have the same static fields and a class implements both – some kind of “multiple inheritance” in Java:
public interface I1 {
   String NAME = "codemonkeyism";
}

public interface I2 {
   String NAME = "stephan";
}

public class C implements I1, I2 {
   public static void main(String[] args) {
      System.out.println(NAME);
   }
}
Staying true, the language designer decided that this does not work in Java:
C.java:3: reference to NAME is ambiguous, both variable NAME
              in I1 and variable NAME in I2 match
      System.out.println(NAME);
                         ^
1 error
There are many more ways to explore with the candidate, e.g. what are the modifiers of interface methods. Are mixins or traits a better solution to the diamand problem than interfaces? Or are they just as bad as multiple inheritance? As I’m no longer very fond of inheritance and think most uses are a code smell, one can also discuss the down side of inheritance – thight coupling for example – with the candidate.

Why?

Why do I ask this question and what do I learn from it? Inheritance is a very basic concept in OO and should be understood by every Java developer. Reflection on his work and going beyond knowing the syntax is an essential trait also, therefor the multiple inheritance question. I prefer questions that spawn many opportunities to explore. The inheritance question is one of them: Mutliple inheritance, language design, code smells, solutions, interfaces, role based development.
If you interview with me, you should know the answers, or tell me you’ve read my blog.
Source: codemonkeyism

    Java Programming Tutorial - 58 - Abstract and Concrete Classes

    What's the difference between “.equals and ==” ?

    In Java, == always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.

    However, the equals method can be overridden - so two distinct objects can still be equal.

    For example:

    Tuesday, October 12, 2010

    Equality, Immutable Objects / Wrapper class caching

    Equality

    Object equality is tested using the == operator, while value equality is tested using the .equals(Object) method.

    For example:



    The output is:

    The two objects are not the same.
    But they do contain the same value
    These two are the same, because they use the same reference.


    Also, be aware that:

    String abc = "abc"; and String abc = new String("abc"); are different. For example, consider the following:



    The output is: true

    This is due to the compiler and runtime efficiency. In the compiled class file only one set of data "abc" is stored, not two. In this situation only one object is created, therefore the equality is true between these object. However, consider this:



    The output is: false

    Even though one set of data "123" is stored in the class, this is still treated differently at runtime. An explicit instantiation is used to create the String objects. Therefore, in this case, two objects have been created, so the equality is false. It is important to note that "==" is always used for object equality and does not ever refer to the values in an object. Always use .equals when checking looking for a "meaningful" comparison.


    Immutable Objects / Wrapper Class Caching

    Since Java 5, wrapper class caching was introduced. The following is an examination of the cache created by an inner class, IntegerCache, located in the Integer cache. For example, the following code will create a cache:


    Integer myNumber = 10; or Integer myNumber = Integer.valueOf(10);

    256 Integer objects are created in the range of -128 to 127 which are all stored in an Integer array. This caching functionality can be seen by looking at the inner class, IntegerCache, which is found in Integer:




    So when creating an object using Integer.valueOf or directly assigning a value to an Integer within the range of -128 to 127 the same object will be returned. Therefore, consider the following example:



    The output is:
    i and p are the same.
    i and p contain the same value.

    It is important to note that object i and p only equate to true because they are the same object, the comparison is not based on the value, it is based on object equality. If Integer i and p are outside the range of -128 or 127 the cache is not used, therefore new objects are created. When doing a comparison for value always use the “.equals” method. It is also important to note that instantiating an Integer does not create this caching. So consider the following example:



    In this circumstance, the output is only: i and p contain the same value


    Remember that “==” is always used for object equality, it has not been overloaded for comparing unboxed values.
    This behavior is documented in the Java Language Specification section 5.1.7. Quoting from there:
    If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions ofp. It is always the case that r1 == r2.
    The other wrapper classes (Byte, Short, Long, Character) also contain this caching mechanism. The Byte, Short and Long all contain the same caching principle to the Integer object. The Character class caches from 0 to 127. The negative cache is not created for the Character wrapper as these values do not represent a corresponding character. There is no caching for the Float object.
    BigDecimal also uses caching but uses a different mechanism. While the other objects contain a inner class to deal with caching this is not true for BigDecimal, the caching is pre-defined in a static array and only covers 11 numbers, 0 to 10:



    As per Java Language Specification(JLS) the values discussed above are stored as immutable wrapper objects. This caching has been created because it is assumed these values / objects are used more frequently.

    Source : http://www.owasp.org

    Converting Integer String and int into one another

    Here are all the different versions:

    a) Convert an Integer to a String

    Integer one = Integer.valueOf(1);
    String oneAsString = one.toString();

    b) Convert an int to a String

    int one = 1;
    String oneAsString = String.valueOf(one);

    c) Convert a String to an Integer

    String oneAsString = "1";
    Integer one = Integer.valueOf(oneAsString);

    d) Convert a String to an int

    String oneAsString = "1";
    int one = Integer.parseInt(oneAsString);

    in1020

    You've given 2 values, return true if either of them is in the range 10..20 inclusive.

    in1020(12, 95) → true
    in1020(22, 12) → true
    in1020(7, 95) → false

    Solution :

    Monday, October 11, 2010

    icyHot

    Given two temperatures, return true if one is less than 0 and the other is greater than 100.

    icyHot(100, -1) → true
    icyHot(-1, 120) → true
    icyHot(2, 120) → false

    Solution :

    startHi

    You've given a string, return true if the string starts with "hi" and false otherwise.

    startHi("hi chankey") → true
    startHi("hi") → true
    startHi("heya hi") → false

    Solution :

    front22

    You've given a string, take the first 2 chars and return the string with the 2 chars added at both the front and back, so "blogger" yields"blbloggerbl". If the string length is less than 2, use whatever chars are there.

    front22("chankey") → "chchankeych"
    front22("Na") → "NaNaNa"
    front22("xyz") → "xyxyzxy"

    Solution :

    Sunday, October 10, 2010

    backAround

    You've given a string, take the last char and return a new string with the last char added at the front and back, so "rat" yields "tratt". The original string will be length 1 or more.

    backAround("rat") → "tratt"
    backAround("cake") → "ecakee"
    backAround("x") → "xxx"

    Solution :

    front3

    You've given a string, the chankey is the first 3 chars of the string. If the string length is less than 3, the chankey is whatever is there. Return a new string which is 3 copies of the chankey.

    front3("Metallica") → "MetMetMet"
    front3("Coldplay") → "ColColCol"
    front3("No") → "NoNoNo"

    Solution :

    frontBack

    You've given a string, you've to return a new string where the first and last characters have been exchanged. For example

    frontBack("doct") → "todd"
    frontBack("x") → "x"
    frontBack("pq") → "qp"

    Solution :

    Saturday, October 9, 2010

    String class in Java

    String class in Java is final so no class can extend the String class hence method overriding is also not possible. Two strings can be concate by + opertor. That's the only overloaded operator in Java.

    String str = "xyz";

    is equivalent to :

    char info[] = { 'x', 'y', 'z' };
    String str = new String (info);

    Here are some more examples of how strings can be used:

    System.out.println("xyz");
    String cde = "pqr";
    System.out.println("xyz" + pqr);
    String c = "xyz".substring(2,3);
    String d = pqr.substring(1, 2);



    Note : Passing a null arguement to the constructor or method in String class will throw a NullPointerException.

    Most commonly used methods in String class.

    1. charAt(int index)
    Returns the character at the specified index.
    2. compareTo(String anotherString)
    Compares two strings lexicographically.
    3. compareToIgnoreCase(String str)
    Compares two strings lexicographically, ignoring case differences.
    4. compareTo(Object o)
    Compares this String to another Object.
    5. concat(String str)
    Concatenates the specified string to the end of this string.
    6. equals(Object anObject)
    Compares this string to the specified object.
    7. indexOf(int ch)
    Returns the index within this string of the first occurrence of the specified character.
    8. indexOf(String str)
    Returns the index within this string of the first occurrence of the specified substring.
    9. length()
    Returns the length of this string.
    10. replace(char oldChar, char newChar)
    Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
    11. split(String regex)
    Splits this string around matches of the given regular expression.
    12. substring(int beginIndex)
    Returns a new string that is a substring of this string.
    13. substring(int beginIndex, int endIndex)
    Returns a new string that is a substring of this string.
    14. toCharArray()
    Converts this string to a new character array.

    missingChar

    You've given a non-empty string and an integer, return a new string where the char at index "n" has been removed. The value of "n" will be a valid index of a char in the original string (i.e. n will be in the range 0..str.length()-1 inclusive).

    missingChar("kitten", 1) → "ktten"
    missingChar("kitten", 0) → "itten"
    missingChar("kitten", 4) → "kittn"

    Solution :

    notString

    Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. Note: use .equals() to compare 2 strings.

    notString("candy") → "not candy"
    notString("x") → "not x"
    notString("not bad") → "not bad"

    Solution :

    posNeg

    Given 2 int values, return true if one is negative and one is positive. Unless the parameter "negative" is true, then they both must be negative.

    posNeg(1, -1, false) → true
    posNeg(-1, 1, false) → true
    posNeg(1, 1, false) → false

    Solution :

    nearHundred

    Given an int n, return true if it is within 10 of 100 or 200. Note: Math.abs(num) computes the absolute value of a number.

    nearHundred(93) → true
    nearHundred(90) → true
    nearHundred(89) → false

    Solution :

    Friday, October 8, 2010

    Date class in Java

    Date is a Java class that can represent a timestamp.

    The example shown below will give you a good idea of how it works :



    %tc = Complete date and time
    %tr = just the time
    %tA = Day of the week
    %tB = Month
    %td = day

    < is just another flag in the format specifier that tells the formatter to "use the previous argument again." It saves you from retyping the arguments.

    Check out the API for Date class. Click here to see.

    Tuesday, October 5, 2010

    Address of a Java Object

    Source : http://javapapers.com

    In conventional java programming, you will never need address or location of a java object from memory. When you discuss about this in forums, the first question raised is why do you need to know the address of a java object? Its a valid question. But always, we reserve the right to experiment. Nothing is wrong in exploring uncharted areas.

    I thought of experimenting using a little known class from sun package. Unsafe is a class that belongs to sun.misc package. For some of you the package might be new. You need not worry about it. If you have sun’s JDK then you have this class already.
    When a class name is “Unsafe” in java, it calls for your attention immediately. Then I decided to dig deep into it and find what is unsafe about that class. Voila, it really opens up the pandora’s box. Its difficult to find the source of Unsafe. Get the source and look at the methods you will know what I am referring to.
    Java’s security manager provides sufficient cover and ensures you don’t fiddle with memory that easily. As a first step, I thought of getting the memory location of a java object. Until the exploration, I too was 100% confident that it was not possible to find the location / address of an object in java.
    Sun’s Unsafe.java api documentation shows us an opportunity to get the address using the method objectFieldOffset. That method says, “Report the location of a given field in the storage allocation of its class“. It also says, “it is just a cookie which is passed to the unsafe heap memory accessors“. Whatsoever, I am able to get the storage memory location of an object from the storage allocation of its class.
    You can argue that, what we have got is not the absolute physical memory address of an object. But we have got the logical memory address. The following program will be quite interesting for you!
    As a first step, I have to get an object of Unsafe class. It is quite difficult as the constructor is private. There is a method named getUnsafe which returns the unsafe object. Java’s security manager asks you to make your java source code privileged. I used little bit of reflection and got an instance out. I know there are better ways to get the instance. But to bypass the security easily I chose the following.
    Using Unsafe’s object just invoke objectFieldOffset and staticFieldOffset. The result is address / location of object in the storage allocation of its class.
    Following example program runs well on JDK 1.6


    import sun.misc.Unsafe;
    import java.lang.reflect.Field;
    public class ObjectLocation {
     private static int apple = 10;
     private int orange = 10;
     public static void main(String[] args) throwsException {
      Unsafe unsafe = getUnsafeInstance();
      Field appleField = ObjectLocation.class.getDeclaredField("apple");
      System.out.println("Location of Apple: "
        + unsafe.staticFieldOffset(appleField));
      Field orangeField = ObjectLocation.class.getDeclaredField("orange");
      System.out.println("Location of Orange: "
        + unsafe.objectFieldOffset(orangeField));
     }
     private static Unsafe getUnsafeInstance() throwsSecurityException,
       NoSuchFieldException, IllegalArgumentException,
       IllegalAccessException {
      Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
      theUnsafeInstance.setAccessible(true);
      return (Unsafe) theUnsafeInstance.get(Unsafe.class);
     }
    }