Saturday, October 27, 2007

Interesting Java puzzles

I came across a set of interesting java puzzles... Do share your views/results on these.

  1. public class StringTest
    {
    public static void main(String[] args){
    foo();
    bar();
    }
    public static void foo(){
    String s = "str4";
    String s1 = "str" + s.length();
    System.out.println("(s==s1) = " + (s1==s));
    }
    public static void bar(){
    String s = "str4";
    String s1 = "str" + "4";
    System.out.println("(s==s1) = " + (s1==s));
    }
    }

  2. public class Assignment {
    public static void main(String[] a){
    int count = 0;
    for (int i = 0; i < 3; i++)
    count += count++;
    System.out.println(count);
    }
    }

  3. class StaticTest {
    static { initIfNecessary(); }

    private static int sum;

    public static int getSum() {
    initIfNecessary();
    return sum;
    }

    private static boolean initialized = false;

    private static synchronized void initIfNecessary() {
    if (!initialized) {
    for (int i = 0; i < 100; i++)
    sum += i;
    initialized = true;
    }
    }
    public static void main(String[] args) {
    System.out.println(getSum());
    }
    }

  4. package click;
    public class CodeTalk {
    public void doIt() { printMessage(); }
    void printMessage() { System.out.println("Click"); }
    }
    ------------------
    package hack;
    import click.CodeTalk;
    public class TypeIt {
    private static class ClickIt extends CodeTalk {
    void printMessage() { System.out.println("Hack"); }
    }
    public static void main(String[] args) {
    new ClickIt().doIt();
    }
    }


  5. public class Lazy {
    private static boolean initialized = false;
    static {
    Thread t = new Thread(new Runnable() {
    public void run() {
    initialized = true;
    }
    });
    t. start();
    try {
    t.join();
    } catch (InterruptedException e) {
    throw e.printStackTrace();
    }
    }

    public static void main(String[] args) {
    System.out.println(initialized);
    }
    }
 

2 comments:

chuck said...

Checkout my blog site
http://softwaretesting-hardinassociates.blogspot.com/

Unknown said...

thanks for sharing information.for more knowledge go on: testing