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.