Saturday, August 2, 2014

Important points about the main method - 1/2

Let's see a "Hello world!" program:

 public class HelloWorld {  
     public static void main(String[] args) {  
         System.out.println("Hello world!");  

Running the program...

 C:\Dropbox\practice\blog>java HelloWorld  
 Hello world!  

1. HelloWorld is an executable class because it contains the main method.

2. The main method is executed first thing when a program is run.

3. The main method is thus called the entry point of a program.

4. It must be declared exactly as described above.

Otherwise the class will compile but we will get a runtime error:

 public class HelloWorld {  
     //Not public, but will compile  
     private static void main(String[] args) {  
         System.out.println("Hello world!");  

Running the program....

 C:\Dropbox\practice\blog>java HelloWorld  
 Error: Main method not found in class HelloWorld, please define the main method  
   public static void main(String[] args)  

The method signature should not vary. 

5. The String array args passed as argument is the list of command line arguments given when executing the program  

 public class HelloWorld {  
    public static void main(String[] args) {  
       System.out.println("No. of arguments passed: " + args.length);  
       if(args.length != 0){  
          System.out.println("Arguments passed: ");  
          for(int i=0; i<args.length; i++){  
             System.out.println(i + ": " + args[i]);  


 C:\Dropbox\practice\blog>java HelloWorld  
 No. of arguments passed: 0  
 C:\Dropbox\practice\blog>java HelloWorld 0 1 2  
 No. of arguments passed: 3  
 Arguments passed:  
 0: 0  
 1: 1  
 2: 2  

I will cover more details on the topic in the following post. Experiment with the code so that you may feel comfortable before reading on.

Sunday, July 6, 2014

Primitives and references in Java

1. There are two kinds of data values that can be stored in variables namely primitive values and reference values.

2. The primitive types are the numeric types (byte, short, char, int, long, float and double) and boolean. Primitives hold the value directly.

3. The reference types are class and interface types, and array types - keep in mind that all arrays are treated as objects.

4. Each of the primitive types has a corresponding wrapper class - primitive types can be AUTOMATICALLY INTERCONVERTED to objects of their corresponding wrapper classes - a process called autoboxing/unboxing. 

Primitive types and their corresponding wrapper classes:
  • byte       ---> Byte
  • short      ---> Short
  • char       ---> Character
  • int           ---> Integer
  • long        ---> Long
  • float        ---> Float
  • double    ---> Double
  • boolean  ---> Boolean

4. String is a class, not a primitive type.

5. A char[] (a character-array) is not the same as a string but both can be inter-converted. 

6. Java uses references to store addresses of objects (as opposed to pointers in C++). 

7. Multiple references may point to the same object. There may be objects in the memory which are not tied to any references (and will probably be garbage-collected).

What is garbage collection?

Garbage collection means reclaiming unused memory in the heap space. Objects are tied to references. When an object is not, the runtime guesses that it is of no use further in the program and treats it as garbage. Such objects MAY OR MAY NOT BE destroyed to reclaim memory. This process cannot be controlled by the programmer. 

Consider this:

 class SomeClass{}  
 public class ReferencesTest{   
   public static void main(String[] array){   
     SomeClass obj1 = new SomeClass();    //1         
     new SomeClass();                     //2  
     SomeClass obj2 = obj1;               //3  
     obj1 = null;                         //4  
     SomeClass obj3;                      //5  

At line 1 we are creating a new SomeClass object which can be manipulated using variable obj1. Put another way, obj1 stores the address (and other memory-related data) for that SomeClass object.

At line 2 we create another SomeClass object which is not tied to any reference (and thus eligible for garbage collection). This object is different from that created in line 1. 

At line 3 we are creating a new reference variable obj2 that points to the same SomeClass object as obj1

So far we have created 2 SomeClass objects.

Now at line 4, obj1 is made null - it is not referring to any object now. Keep in mind that the SomeClass object created at line 1 is still there (being referred to by obj2).

At line 5 we created a new SomeClass reference obj3 (which must be initialized or assigned to an object before it is used since it is a local variable). 

Thursday, May 15, 2014

Defining your first class in Java

A class is simply a category of objects. Each of these objects share common functionality and characteristics:
  • All cars have 4 wheels, an engine, a fuel tank etc.
  • All shapes have an area. (Though method of calculation may be different)
  • Each person has a name, age and gender.

Let's start with a classic example of a Animal class.

1:  abstract class Animal{  
2:    abstract void eat();  
3:    abstract void makeSound();  
4:  }  

The class is abstract as each kind of animal has a different behavior. In other words, the behavior is different for each kind of animal (for example, dogs bark and cats say "meow") and we cannot associate one general behavior with all kinds.

So the Animal class declares that all animals have some common behavior. abstract methods mean that each kind (or each subclass) of Animal will define its own way of making sounds and eating. 

Let's see a simple example

A dog is-a-kind-of Animal. So we define the following class:

1:  class Dog extends Animal{  
3:    //Following methods are common behavior   
4:    //declared in superclass Animal  
5:    //Now defined in a general way for Dog objects  
7:    void eat(){  
8:      System.out.println("Eating biscuits");  
9:    }  
11:    void makeSound(){  
12:      System.out.println("Barks...");  
13:    }  
14:  }  

This represents a blueprint of a Dog object.

Now let us test our code.

Full program:

1:  abstract class Animal{  
2:    abstract void eat();  
3:    abstract void makeSound();  
4:  }  
5:  class Dog extends Animal{  
7:    //Following methods are common behavior   
8:    //declared in superclass Animal  
9:    //Now defined in a general way for Dog objects  
11:    void eat(){  
12:      System.out.println("Eating biscuits");  
13:    }  
15:    void makeSound(){  
16:      System.out.println("Barks...");  
17:    }  
18:  }  
19:  class Test{  
20:      public static void main(String[] args){  
21:          System.out.println("Creating a new Dog object");  
22:          Dog dog = new Dog();  
23:          System.out.println("Calling eat() method on the Dog object");  
25:          System.out.println("Calling makeSound() method on the Dog object");  
26:          dog.makeSound();  
27:      }  
28:  }  

Running the code...

 D:\Dropbox\practice\blog>java Test  
 Creating a new Dog object  
 Calling eat() method on the Dog object  
 Eating biscuits  
 Calling makeSound() method on the Dog object  

This finishes the basics of defining your first class in Java.


Define two String variables in the Dog class. Both should be instance variables. One denotes the name of the dog and the other denotes the dog's breed. In the main method, print both the fields (without assigning any values). Now assign values to both the variables and print them again. Remember that you must use the dog variable to access the fields in main().

Saturday, May 10, 2014

Packages in java (2/2) - Setting the CLASSPATH

This is the 2nd article on packages.

We'll be discussing a simple "Hello world!" program with packages.

CLASSPATH settings

You do not need to set your CLASSPATH for this exercise. But we will have a look at it.

Windows: Go to My Computer > Right Click > Properties > Advanced tab > Environment variables > System variables (in the lower half)

If you don't find the entry CLASSPATH, don't bother

If set, your CLASSPATH settings must positively contain '.' (period). This is the default value of CLASSPATH and must be added when and if you decide to add more directories to it.

The entries in the CLASSPATH are separated by semi-colons.

Now you are all set to code.

First, download the source file here.

//Hello world with packages
//Simple program that says "Hello world!"
//with packages
//First line of code should be package statement:

class Hello{
  public static void main(String... args){
System.out.println("Hello world!");

Basically the package statement specifies the directory tree.

Place the com folder in the root directory (say D: drive)

Run javac and java commands:

You should get the above output. Note that if CLASSPATH is defined, there should a period in there as it tells the compiler to look in the current directory.

Wednesday, May 7, 2014

Introduction to OOP concepts

Q. What is a class?

"A dog is an animal."

"Animals make different sounds."

"A dog barks."

"My dog's name is Abby."

Consider this in programming terms. 

"Everything is an object"

"Each object has a category (or class in programming terms)"

"A dog is an (object of class) Animal."

"The Animal class has many subcategories (of which Dog is one)."

"The Animal class itself can be said to be a subclass of Object."
This is called singly rooted heirarchy (will be covered later)

"Each object of class Animal makes sounds differently. For example, dogs bark. Cats say meow"
This is called polymorphism

"Each class (i.e. category) of objects has some particular behavior(s) and properties associated with it."

Some classic examples of OOP concepts: 

  1. Consider a car. How the engine works (say) is not known to the driver. The mechanics behind the workings of the car are hidden from the driver. If the car was to break down, only the mechanic at the workshop knew what went wrong and only he could fix it. NOT the driver. This is called abstraction and encapsulation.
  2. A smartphone has a camera. This is called HAS-A relationship. It is commonly called composition.
  3. A dog is an animal. This is called IS-A relationship. It is called inheritance in object oriented programming.
  4.  A shape can be of any type - a triangle, square, hexagon etc. However the method of calculation of area is different for each shape. Thus the area of a shape is said to be calculated dynamically i.e. polymorphically. 

Saturday, May 3, 2014

Primitives and references are passed by value in Java

In Java there is no pass by reference.

People say that primitives are passed by value, and objects are passed by reference. This is incorrect. To be precise,


Consider the following program

 class PassByValue1{  
     private static void someMethod(int i){  
         i = 20;  
     public static void main(String[] args){  
         int someInt = 10;  
         System.out.println("Before calling someMethod(), someInt: " + someInt);  
         System.out.println("After calling someMethod(), someInt: " + someInt);          


 D:\Dropbox\practice\blog>java PassByValue1  
 Before calling someMethod(), someInt: 10  
 After calling someMethod(), someInt: 10  

We see that primitives are indeed passed by value. No surprises there...

Now consider a String object:

 class PassByValue2{  
     private static void someMethod(String s){  
         s = null;  
     public static void main(String[] args){  
         String someString = "Some text";  
         System.out.println("Before calling someMethod(), someString: " + someString);  
         System.out.println("After calling someMethod(), someString: " + someString);          


 D:\Dropbox\practice\blog>java PassByValue2  
 Before calling someMethod(), someString: Some text  
 After calling someMethod(), someString: Some text  

Inside someMethod(), s points to the same String object as someString. Then s simply points to null as someMethod() returns.

Arrays are objects as well. Consider this:

 import java.util.Arrays;  
 class PassByValue3{  
     private static void someMethod(int[] ia){  
         ia[2] = 20;  
     public static void main(String[] args){  
         int[] someIntArray = {0, 1, 2, 3};  
         System.out.println("Before calling someMethod(), someIntArray: " + Arrays.toString(someIntArray));  
         System.out.println("After calling someMethod(), someIntArray: " + Arrays.toString(someIntArray));          


 D:\Dropbox\practice\blog>java PassByValue3  
 Before calling someMethod(), someIntArray: [0, 1, 2, 3]  
 After calling someMethod(), someIntArray: [0, 1, 20, 3]  

Again as someMethod() is called, ia points to the same array object referenced by someIntArray. We just modify the array using ia

Friday, May 2, 2014

Important points about the main method - 2/2

Continuing our discussion from the previous post on the main method.

6. Multiple classes can contain the main method in a source file

 public class HelloWorld {  
     public static void main(String[] args) {  
         System.out.println("No. of arguments passed: " + args.length);  
         if(args.length != 0){  
             System.out.println("Arguments passed: ");  
             for(int i=0; i<args.length; i++){  
                 System.out.println(i + ": " + args[i]);  
 class SomeClass1{  
     public static void main(String[] args){  
         System.out.println("main() in SomeClass");  
 class SomeClass2{  
     public static void main(String[] args){  
         System.out.println("main() in SomeClass2");  


 C:\Dropbox\practice\blog>java HelloWorld  
 No. of arguments passed: 0  
 C:\Dropbox\practice\blog>java HelloWorld 0 1 2  
 No. of arguments passed: 3  
 Arguments passed:  
 0: 0  
 1: 1  
 2: 2  
 C:\Dropbox\practice\blog>java SomeClass1  
 main() in SomeClass  
 C:\Dropbox\practice\blog>java SomeClass2  
 main() in SomeClass2  

7. The class with the main method may or may not be public.

8. There can be only one public class in a source file.

9. The source file must be named EXACTLY as the public class. If there is no public class present, then the source file may be named anything.

The source file containing the above code above MUST be named (as the HelloWorld class is public). If the public modifier is removed then the file may be named anything (eg, etc.). You cannot apply public modifier to SomeClass1 (or SomeClass2) while HelloWorld is public.

10. There can be any number of classes/interfaces in a single source file. 

This completes discussion on the main() method.

Tuesday, April 29, 2014

Packages in java (Part 1/2)

This is the first article on packages. 

Simply put, a package is a folder that organizes related top-level classes and interfaces.

A package contains source code files (containing top-level classes and interfaces) and sub-packages with source code files of their own. 

Important points about packages:
  • The package statement should be the first line of code in a compilation unit.
  • There is only one package statement in each compilation unit.
  • The package java.lang.* is imported automatically in each .java file.
  • The containing package may be imported. Such an import is ignored.

//First line of code is package statement

package com.choosejava.blogspot;

//java.lang package is automatically imported

//May specify redundantly
import java.lang.*;
import somepackage.*;

//This line is ignored
import com.choosejava.blogspot.*;

//Top-level classes and interfaces
class A{...}
interface I1{...}

You cannot single-import a type with the same simple name as a top-level class or interface.

Also, 2 single-type import declarations should not attempt to import types with the same simple name. Following is invalid.

package somepackage;

import otherpackage.TestClass;

class TestClass{...}

//Reference to TestClass will be ambiguous

Following is also invalid:

import otherpackage.Vector;
import java.util.Vector;
//Reference to Vector class will be ambiguous


Duplicate import declarations are allowed.

Let's modify the above code with TestClass a little bit. 

Following is valid:

package somepackage;

import otherpackage.*;

class TestClass{...}

//Refer to otherpackage.TestClass using the fully qualified name

Monday, April 28, 2014

Identifiers in Java

Identifiers are names of classes, interfaces, methods, variables and packages.
Must start with:
  • A - Z or a - z                     
  • $  or _ (underscore)
Can also contain:
  • 0-9
Cannot be 
  • null literal
  • boolean literal (true or false)
  • a keyword
No limits on number of characters.
List of keywords:
Note: goto and const are reserved keywords in Java. (They are not used anywhere).
Legal identifiers:
MyClass (Class name)
m1 (Method name)
var (Variable name)
_123 (Not recommended but legal)
$UNLIMITED (Strange)
MAX_VALUE (static final variable)
Illegal identifiers
public (keyword)
123_ (starts with number)
null (null literal)