Sunday, December 11, 2011

Strings are immutable

Tip: Strings are immutable; once they are created they cannot be changed.

We can test this concept by creating an instance of String and try to modify it and then test if the original instance is modified or not.

Sounds simple, let's get to it:

public class StringTest {

 public static void main(String[] args) {
  foo();
 }

 public static void foo() {
  String a = "Hello";
  String b = a.concat(" World!");

  System.out.println("a : " + a);
  System.out.println("b : " + b);
 }
}
Output of StringTest will be:

a : Hello
b : Hello World
As you can see even after concat () method value of a did not change. It just returned a new String instance.

Available in Android Market

Monday, November 28, 2011

Access modifiers for Local Class

Tip: Local class declaration can not have any access modifier.

Since local classes are defined within method body, they follow the same modifier rule as any other variable within method.

We will test this by defining a local class and put private access modifier and see if this compiles and runs.
class Furniture {
    public static void print() {
        final int i = 30;
        private class Table { // compilation error here
            void printVar() {System.out.println(i);}
        }
        Table table = new Table();
        table.printVar();
    }
}
Above code defines a class Furniture with one method print (), within print, Table local class is defined and to test today's tip an access modifier is used with class definition.

The code above will get a compilation error where private is defined before local class Table .

Available in Android Market

Wednesday, November 23, 2011

Impact of System.exit on Finally block

Tip: Finally block will not be executed when System.exit () is called within try block.

When System.exit () is called it will shut down the Java Virtual Machine and finally block will not be executed.
class Bar {
 public static void testExit() {
  try {
   System.out.print("Before System.exit(0)");
   System.exit(0);
   System.out.print("After System.exit(0)");
  } finally {
   System.out.print("in finally.");
  }
 }
 public static void main(String[] args) {
  testExit();
 }
}
In above class method testExit () method contains a try-finally block with some print statements, lets run and see what the output is.
Before System.exit(0)
Not only the finally block is skipped, even statement within try block also did not execute. Like we said earlier, System.exit(0) is a hard shut-down of JVM, no statement will be executed after that.

Available in Android Market

Monday, November 21, 2011

Array length

Tip: Once an array object is created, its length never changes. To make an array variable refer to an array of different length, a reference to a different array must be assigned to the variable.

We don't have any method in array to change its length, we can try changing the length of variable by creating two different array instance and printing its length.
class ArrayLength {

 public static void main(String[] args) {
  int [] a = {1, 2, 3};
  System.out.println("Length : " + a.length);
  
  a = new int [2];
  System.out.println("Length : " + a.length);
 }
} 
If we compile and run this code, output will be:

Length : 3
Length : 2
Next exercise we will try to increase length of array by assigning at an index more than the array was initialized with.
 ArrayLength {

 public static void main(String[] args) {
  int [] a = {1, 2, 3};
  System.out.println("Length : " + a.length);

  a [3] = 4;
  System.out.println("Length : " + a.length);
 }
}
When above code is run, it will throw java.lang.ArrayIndexOutOfBoundsException
Length : 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
 at com.quiz.questions.ArrayLength.main(TestArray.java:18)
Very simple fact, but sometimes even the experienced programmers miss this.

Available in Android Market

Sunday, November 20, 2011

Enum as nested class

Tip: Enums can be declared as a top level class, or an inner class, but not within a method.

We can easily test this by defining a class with Enum defined within a method:
class LocalEnum {
 void printCar () {
  enum CarClass { // compilation error here
   COMPACT, MIDSIZE, FULLSIZE;
  }
  System.out.println(CarClass.COMPACT);
  }
}
If you try to compile and run above code snippet you will get error in line enum CarClass.

On the other hand if we take out enum CarClass out of method the definition will be fine.
class LocalEnum {
 enum CarClass {
  COMPACT, MIDSIZE, FULLSIZE;
 }

 static void printCar() {
  System.out.println(CarClass.COMPACT);
 }

 public static void main(String[] args) {
  printCar();
 }
}
We have modified the little bit above so that it could be run easily by putting a main method, printCar is static and enum is defined out of the method. It works ....

Available in Android Market

Wednesday, November 16, 2011

Switch expression

Tip: A switch expression must evaluate to a char, byte, short, int, enum.

Lets put some code together and test this statement.
class SwitchTest {
 static final String ONE = "ONE";
 static final String TWO = "TWO";
 static final String THREE = "THREE";
 
 public static void testSwitch (String number) {
  switch (number) { // compilation error here
   case ONE:
    System.out.println(ONE);
    break;
   case TWO:
    System.out.println(ONE);
    break;
   case THREE:
    System.out.println(ONE);
    break;
   default:
    System.out.println(ONE);
  }
 }
 
 public static void main(String[] args) {
  testSwitch(TWO);
 }
}
If you try to compile and run the above code you will get the compilation error.

Now change data type of number from String to a char, byte, short, int, enum type and it will compile and run just fine.

Available in Android Market

Tuesday, November 15, 2011

Static member classes and instance variables - Part 2.

Tip: Static member classes have access to all static members of parent or top level class.

This tip is continuation of Static member classes and instance variables.

We will put together a code snippet to test it:

class Dolls {

    public static int dollCount = 25;

    protected static String doll = "doll";

    private static int toyCount = 10;

    static String toy = "toy";

   

    static void printTipResult () {

     System.out.println("access : true!");

    }

   

    public static class Barbie{

        void printVar () {

            System.out.println(doll + " : " + dollCount);

            System.out.println(toy + " : " + toyCount);

            printTipResult();

        }

    }

    public static void main(String[] args) {

        Dolls.Barbie barbie = new Dolls.Barbie();

        barbie.printVar();

    }}

What we have done above is defined 4 class variables with different access modifiers to test all scopes of static member variables. One static member method is also added to cover methods also.  

When you run this code it won't generate compilation error or runtime error, the output will be:


doll : 25
toy : 10
access : true!


This proves today's Tip.



Available in Android Market