Friday, 22 June 2012

Can we override static method in Java?

Many people have heard that you can't override a static method. This is true - you can't. However it is possible to write code like this:

class Foo {
    public static void method() {
        System.out.println("in Foo");
    }
}

class Bar extends Foo {
    public static void method() {
        System.out.println("in Bar");
    }
}
This compiles and runs just fine. Isn't it an example of a static method overriding another static method? The answer is no - it's an example of a static method hiding another static method. If you try to override a static method, the compiler doesn't actually stop you - it just doesn't do what you think it does.

So what's the difference?

Briefly, when you override a method, you still get the benefits of run-time polymorphism, and when you hide, you don't. So what does that mean? Take a look at this code:
class Foo {
    public static void classMethod() {
        System.out.println("classMethod() in Foo");
    }

    public void instanceMethod() {
        System.out.println("instanceMethod() in Foo");
    }
}

class Bar extends Foo {
    public static void classMethod() {
        System.out.println("classMethod() in Bar");
    }

    public void instanceMethod() {
        System.out.println("instanceMethod() in Bar");
    }
}
 
class Test {
    public static void main(String[] args) {
        Foo foo = new Bar();
        foo.instanceMethod();
        foo.classMethod();
    }
}
If you run the above program, the output is









Why do we get instanceMethod from Bar, but classMethod() from Foo?

Aren't we using the same instance foo to access both of these? Yes we are - but since one is overriding and the other is hiding, we see different behavior.

Since instanceMethod() is an instance method, in which Bar overrides the method from Foo, at run time the JVM uses the actual class of the instance foo to determine which method to run. Although foo was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that foo is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That's how Java normally works for instance methods.

With classMethod() though. since it's a class method, the compiler and JVM don't expect to need an actual instance to invoke the method. And even if you provide one (which we did: the instance referred to by foo) the JVM will never look at it. The compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. Since foo is declared as type Foo, the compiler looks at foo.classMethod() and decides it means Foo.classMethod. It doesn't matter that the instance reffered to by foo is actually a Bar - for static methods, the compiler only uses the declared type of the reference. That's what we mean when we say a static method does not have run-time polymorphism.

Because instance methods and class methods have this important difference in behavior, we use different terms - "overriding" for instance methods and "hiding" for class methods - to distinguish between the two cases. And when we say you can't override a static method, what that means is that even if you write code that looks like it's overriding a static method (like the first Foo and Bar at the top of this page) - it won't behave like an overridden method.

So what about accessing a static method using an instance?

It's possible in Java to write something like:

foo.classMethod();

where foo is an instance of some class, and classMethod() is a class method (i.e. a static method) of that class. This is legal, but it's a bad idea because it creates confusion. The actual instance foo is not really important here. Only the declared type of foo matters. That is, what class is foo declared to be? Since classMethod() is static, the class of foo (as determined by the compiler at compile time) is all we need.

Rather than writing:

foo.classMethod();

It would be better coding style to write either:

Foo.classMethod();

(or)

Bar.classMethod();

That way, it is crystal clear which class method you would like to call. It is also clear that the method you are calling is indeed a class method.

Barring that, you could always come up with this monstrosity:

foo.getClass().getMethod("classMethod", new Class[]).invoke(null, new Object[]);

But all this could be avoided by simply not trying to override your static (class) methods. :-)

Why does the compiler sometimes talk about overriding static methods?

Sometimes you will see error messages from the compiler that talk about overriding static methods. Apparently, whoever writes these particular messages has not read the Java Language Specification and does not know the difference between overriding and hiding. So they use incorrect and misleading terminology. Just ignore it. The Java Language Specification is very clear about the difference between overriding and hiding, even if the compiler messages are not. Just pretend that the compiler said "hide" rather than "override"..


Wednesday, 20 June 2012

Java program to check the given number is prime or not.

package com.dev.test;

import java.util.Scanner;

public class PrimeNumber {

    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter number : ");
        while (in.hasNext()){
            int num = in.nextInt();
            if (isPrime(num)) {
                System.out.println(num + " is prime number");
            } else {
                System.out.println(num + " is not a prime number");
            }
            System.out.print("Enter number : ");
        }
    }

     public static boolean isPrime(int num) {
        //check if n is 2
        if (num == 2){
            return true;
        }
        //check if n is a multiple of 2
        if (num % 2 == 0){
            return false;
        }
        //if not, then just check the odds
        for (int i = 3; i * i <= num; i += 2) {
            if (num % i == 0)
                return false;
        }
        return true;
    }
}

What is metadata?

Metadata is simply data about data. It defines the structure and meaning of data objects. Examples of metadata include database schema, the meaning of object attributes and methods in a Java class, annotations in a Java class, XML DTDs and Schemas, and UML models.

What does volatile do?

Java volatile keyword cannot be used with method or class and it can only be used with variables.

This is probably best explained by comparing the effects that volatile and synchronized have on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:
int i1;              
volatile int i2;              
int i3; 

int geti1() {return i1;}
int geti2() {return i2;}
synchronized int geti3() {return i3;}
geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it's thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a "main" memory, and this is the memory that holds the current "correct" value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the "main" memory. So in fact, it is possible for the "main" memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to "main" memory or other threads.

On the other hand, geti2() effectively accesses the value of i2 from "main" memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in "main" memory. Effectively, a variable declared volatile must have it's data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than "plain" variables, since the reason threads can have their own copy of data is for better efficiency.

Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That's the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with "main" memory. So executing geti3() does the following:

1) The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).

2) The thread memory flushes all its variables, i.e. it has all of its variables effectively read from "main" memory (JVMs can use dirty sets to optimize this so that only "dirty" variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).

3) The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from "main" memory).

4) (Any changes to variables would normally now be written out to "main" memory, but for geti3() we have no changes.)

5) The thread releases the lock on the monitor for object this.

So where volatile only synchronizes the value of one variable between thread memory and "main" memory, synchronized synchronizes the value of all variables between thread memory and "main" memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.

Monday, 18 June 2012

Program for printing numbers from 1 to 100, which contains digit 5?

public class PrintNumbers
{
    public static void main(String[] args) {
        for (int i = 0; i <= 100; i++) {
            if (isContainGivenNo(i, 5)) {
                System.out.println(i);
            }
        }
    }

    private static boolean isContainGivenNo(int no, int containNo) {
        while (no > 9) {
            int remainder = no % 10;
            if (remainder == containNo) {
                return true;
            }
            no /= 10;
        }
        return no == containNo;
    }
}
(or)
public class PrintNumbers
{
    public static void main(String[] args){
        for(int i = 1; i < 100; i++){
            String s = ""+i;
            if (s.contains("5")){
                System.out.println(i);
            }
        }
    }
}
Output : 5 15 25 35 45 51 52 53 54 55 56 57 58 59 65 75 85 95

Sunday, 17 June 2012

What is the difference between thread and threadlocal?

Thread represents the flow of control, i.e. the code that is running as a thread. It can be started, interrupted, waited for, assigned a priority, etc.

ThreadLocal represents a piece of memory attached to the thread. It's a single object that maintains a different value for each thread that uses it. When a thread calls Set on a ThreadLocal, it will get back the same value later, even if other threads have also called set on the same ThreadLocal in the intervening time. Each will get back its own value.

You could achieve the same result with a Map<Thread, ?>, where the current thread is always the key, but this is neater and already checked to be thread-safe.