Friday, 8 March 2013

Objects in Java

Background

In last post we learned what is a class, what does it represent and how do you define one.Lets move on to knowing about objects.Before proceeding to knowing objects in details it is important to know difference between instance variable and local variables.

Difference between local variable and instance variable

  • Instance variable are class level member variables where as local variable are variables defined locally in functions or code blocks.
  • Values of instance variables are unique to each instance of a class i.e objects of that class.
  • In programming languages such as Java, instance variables are stored on the stack memory allocated by the Operating system. This contrasts with reference variables (variables that are references to existing instance variables) which are stored on the heap.
  • Instance variables are always assigned a default value.

Lets move on to how to create an object in Java.

Creating an object in java

     Before i show you how we create any object in java let me explain a bit of it's technical part.So as we know Java is an OOP language which means everything is an object which also means everything must have an associated class.
    This object which we keep referencing so ofter is parent class of all classes that exist in Java i.e classes which are already defined in Java libraries as well as Classes which you(User) defines. In more technical terminology all classes extends from object class. I know polymorphism and inheritance are not yet covered so i will not get into details of this but for now just keep in mind all classes inherit/extend or is a direct or indirect child of class object. 
    Lets go ahead in creating objects. You create object using the keyword new. Syntax for creating an object is as follows
  ClassName objectName = new ClassName();
  ClassName is the name of the class whose object you wish to create. objectName is the name of the object.It can be any user defined name as long as it sticks to naming rules.
Eg. MyGreeting greeting = new MyGreeting();

Where are objects stores in Java?

     Before i answer this question there is one thing you must understand which is difference between reference and an actual object.When i just say  MyGreeting greeting; it is perfectly valid. What are we doing here is that we are saying greeting is a reference to an object which will be of type MyGreeting. Note that we have not created object yet.Object is created only when we use that new keyword. So when i say MyGreeting greeting = new MyGreeting(); there is a reference variable called  greeting of type MyGreeting   and there is an object created using new of MyGreeting  class and the greeting reference points to that created object.

I hope now we understand what is a reference variable and what is an object.So lets get to our original question where are objects stored? Objects are always stores on the heap(also known as garbage collectable heap) where as reference variable are stored on stack. So to sum it up greeting variable is stored on stack and points to an object in the heap.Remember heap is where the memory needed for the object is allocated and this memory allocation is automatic.Also this memory is freed automatically by garbage collector which we will see in detail after some time.Note garbage collector is invoked automatically by JVM. We can also specify to invoke garbage collector by using System.gc() but still it is not necessary JVM will invoke garbage collector when it encounters above command.Do not worry about garbage collector for now.Our primary focus is to learn objects in this post.


Consider following code


Book b = new Book();
Book c = new Book();
Book d = c;


Now references 'c' and 'd' point to same Book instance on Heap where as reference 'c' point to a difference instance. So

System.out.println(c == d); //will print true
System.out.println(c == b);//will print false

I hope this completely clears the difference between a reverence variable and an actual object.

What actually happens when i create an object?

When you create an object, more specifically when you use the new  keyword an instance on the class is returned as an object.It will have its own copy of instance variables and functions.First thing that happens after an object is created is calling of a constructor.So lets understand constructors in our next post.

What are getter and setter methods we keep referring to?

      As we define our member variable to be private which we should because that is the essence of data encapsulation(will be explained later), we cannot directly access these variables using object as objectName.variableName. So we must define public methods which will be use to get and set the values of such member variables.These methods are called getter and setter methods.Since the functions are public we can use our object to get or set value of any member function i.e value of any private member variable can only be changed by member variables in same class.If you are using an IDE like Eclipse or Netbeans you can directly generate these getter and setter methods.Go to Source-->Generate getters and setters.

I have seen usage like "this.VariableName" is a class.What is that?

     This question can be better explained using an example. Consider an setter method for some member variable private int count;
   public void setCount(int c)
   {
        count = c; 
    } 

Observer above code carefully.We have not used this.count and is still perfectly valid.Now we know that count is an instance variable and c is a local variable.In case c was named as count(why not it's perfectly valid) then the function would be something like below

  public void setCount(int count)
   {
        count = count; 
    } 

Though this may look valid, this will give erroneous results. Now which count is which.It is for cases like this we use this.variableName to avoid confusion and maintain standards. this.variableName means that the variable is an instance variable.
So finally your function will look like

  public void setCount(int count)
   {
        this.count = count; 
    } 

You will specifically see this when you are automatically generating setter methods using an IDE.You can always use different name for local variable but using this.variableName will help you as well as others understand the code better.

Finally what is the difference between a class and an object?

A class is a blue print for an object!

It tells JVM how to create object of that particular type.Each object made from that class have it's own values for the instance variables of the class. For eg cosider


public class Dog
{
      String breed;
       int height; 
}



Above Dog class represent a Dog. Each dog will have unique breed and height (have just taken two properties for argument sake .... we can consider more) that will determine what type of Dog it is. So as I said previously Classes are blueprints of Objects.


Classes in Java

We said that one of the advantages of using Java as a programming language over C is its Object Oriented nature.In this tutorial lets see what it means to be an object oriented programming language. In this post we will see what are classes, what are objects and how they interact with each other.

What is OOP?

     OOP(Object oriented programming) means your program or code comprises of objects and these objects interact with each other to deliver the final result you are interested in.Why to program in an OOP language one might ask.Well, there are many advantages to use an OOP language over other languages. Some of them are Data Encapsulation, Polymorphism, Inheritance etc. These terms may sound a little advanced at this point of time but we will have separate posts of each of them.

    So lets get started with Classes and Objects.

Classes in Java

   Classes in java are nothing but blue print or templates for creating objects. Syntax for defining a class is

<AccessModifier> Classname
{
    member variable
    member functions
}

As  we had mentioned in post on Access modifier just recall that class level modifier are public and no modifier(default). So you can have only either public  as a access modifier or nothing  i.e just class. I would recommend just go through the access rules table Access Modifiers once again.
    Classname can be any name of your choice as long as it follows the naming rules.Take a quick look at the Naming Rules . Class definition must go inside curly braces following the class name. Inside these curly braces you must specify member variables Eg. private int count and member functions Eg. public int getCount() or public void setCount(int count).

Naming conventions for classes and its members

    There is a standard naming conventions that all Java programmers follow.These are not mandatory rules but some standards defined to make our lives easy.

Note  - A common convention for all is that try to give meaningful names relevant to your project or code.For example you are writing a program say to print "Hello World!", then you can have class name something like MyGreetings.
  • Package : If you don't know what a package is it is simply a directory or rather call it a structure which hols all your classes.It is recommended to make your our package and put your classes there than to use the default package.Package name must be entirely in lower case.
    Eg. package greeting or package com.javatutsforgeeks.greetings. For all your classes in a package must have first line as package packageName . If you are using an IDE like Eclipse or Netbeans you will automatically see it when you create a class inside a package. For others you have to manually specify.
  • Classes : Class names must be in Camel case.In Camel case all sub-words in a word start with an upper case.Also try giving name to your class which is a noun because a class represents an object in real world. Ex class MyGreeting .
  • Interfaces : Same convention as classes. Do not worry about interfaces for now.It's a very interesting topic and we will cover it soon after we learn inheritance. 
  • Members : Now when i say a member it can be a member variable or a member function. Conventions are same for both. Member name must start with a lowercase and starting letter of all subsequent sub-words are in capital letter.
    Eg. private String welcomeMessage or public String printGreetingd(String message).

Note : Your class name should be same as your file name in which you have your class. For example if your class is like public class MyGreeting then your file name should be MyGreeting.java. Again an IDE will do this automatically for you but if you coding in some editor like notepad++ or vim then you must take care of this.

But i heard that we can have two classes in one file.What should we do in that case?

     Yes it is possible to have more than one class defined in a single file.In this case you must give file name same as the name of first class in your file.Though this is allowed it is strongly recommended to have one class per file.

Writing classes - Example

     Lets write complete code so that we understand classes completely once and for all.

package greetings;

public class MyGreetings {
   
    private String welcomeMessage;

    public String getWelcomeMessage() {
        return welcomeMessage;
    }

    public void setWelcomeMessage(String welcomeMessage) {
        this.welcomeMessage = welcomeMessage;
    }
   
    public static void main(String args[])
    {
        MyGreetings greetings = new MyGreetings();
        greetings.setWelcomeMessage("Welcome to javatutsforgeeks!");
        System.out.println(greetings.getWelcomeMessage());
    }
   
}

 Explaination - Above code defines a class called MyGreetings in a package called greetings. It has a member variable called welcomeMessage which is of type String and has access modifier as private. We then have member function which are nothing but getter and setter methods for our member variable welcomeMessage. Then we have out main() function which creates an object of our class MyGreetings, sets the value for member variable and prints it to standard output.

Quick Note : Since our member variable welcomeMessage is defined to be private we cannot access it using greeting. welcomeMessage and hence we have our getter and setter methods. This also forms a base for data encapsulation which we will study later.
 

Member variables and member functions

Member variable have the syntax 
AccessModifier variableType variableName;
Eg. private int count;
Member functions have the syntax
AccessModifier returntype functionName(arguments);
Eg. public void setCount(int count); 
 As stated earlier we have four member level access modifiers.Go through the post on Member level Access modifiers to review it once again.

We already know the Access modifiers and return types.Lets focus on arguments now.Arguments are parameters or variables that you want to pass to a function.These are local variables and their scope extend in the particular function only.You can pass as many arguments as you want.
Eg. public void setCountandName(int count,String name);
In Java we pass arguments as pass-by-value which means a copy of the reference to the object is passed.


Note : Java is pass by value! Java passes objects as references and those references are passed by value.




 We will see what are objects, how we create them in next post.This is one of the basic posts that forms the basis of other posts yet to come..Please let me know if you have any question.I will be more than happy to clarify them.


Thursday, 7 March 2013

Transfer statements in Java

We are discussing control flow statements in Java and so far we have covered Selection and Loop statements. Lets go ahead and see Transfer statements.

Transfer statements are
  • continue
  • break
  • return
  • try-catch-finally

Continue statement

We use continue statement when we are in a loop and wish to skip some code execution based on certain criteria.Continue statement causes execution to resume at the top of the nearest enclosing loop.You use a continue statement when you do not want to execute the remaining statements in the loop, but you do not want to exit the loop itself.

Lets us take an example.Lets say we want to print even numbers from 0 to 10.Lets use for loop to achieve this.

for(int i=0;i<=10;i++)
{
     if(i%2!=0)
     {
           continue;
     }
     System.out.println(i + "\n");
}


Frankly the code is redundant and not the best way to print even numbers from 0 to 10 but will serve our purpose to understand continue statement.

Lets see what above code does.It's a for loop where variable i runs from 0 to 10.Inside the for loop we say if(i%2!=0) which means if remainder obtained by dividing i by 2 is not zero then just continue with the execution i.e skip rest of code in loop and start the loop again.However if the remainder is  0 then go ahead and print the number on standard output.

break statement

break statement is used when you want to stop the execution of the loop forcefully and come out.The break statement transfers control out of the enclosing loop ( for, while, do or switch statement).

Lets take the same example mentioned above to demonstrate this.We want to print even numbers in the range 0 to 10.Lets do it this time using a infinite while loop.
int i = 0;
while(true)
{
    if(i%2=0)
    {
         System.out.println(i + "\n);
    }
  if(i>10)
  {
      break;
   }
 i++;
}

Above code is very much similar to the code sample used to demonstrate continue statement.Above while loop is infinite and so we must stop the loop manually which in fact is done by break statement.Above code
starts with i=0 before the while loop begins and increments in each loop(i++). There is slight change is first part of the loop as compared to previous sample code.This program checks if remainder is zero and if it is then prints i to standard output but what is important is second part of the loop.As we keep on incrementing i when its value goes above 10 i.e 11 it will enter the second if statement and execute break.break will simply break from the loop and come out.

Note : Both continue and break statement are used only in loops.break is also used in switch statement.I have seen programmers doing silly mistake of using break and continue in "if" statements.

return statement

Return statement is very much simple. It will return the the execution control from the point where it is encountered to the point where the function containing the return statement is called.Lets take an example to understand this better.If you wish to return some value you can do even that but remember you can return one and only one variable from any function or module.

What if we have to return more than two variable from a function you might ask.Well there are ways to achieve that and we will cover that in some time. Lets take an example of return statement.
Class Greeting
    private String name;
    public void setName(String name)
    {
         this.name = name;
     }
     public String getName()
     {
          return(this.name);
      }
   public static void main(String args[])
  {
       Greeting greeting = new Greeting();
         greeting.setName("John");
         System.out.println(greeting.getName());
  }

}

Above code may look complicated but it isn't. Don;t worry about classes and object for now. We will see it later.Lets just concentrate on understanding return statement for now.

In above code we create a Greeting object called greeting. Set the name parameter to "John". When you call greeting.getName() it will call the getName() method in Greetings class which will then return the name variable which was set earlier.So "John" will be printed to standard output.

Note : Since name is defined using private access modifier you cannot access it using greeting.name. Refer Access modifiers to brush up access levels. Even if you are not getting this at this point don't worry we have lot of example and sample coming our way to demonstrate all these concepts again :).

try-catch-finally

This statement is used in exceptions so it is better we not cover it here otherwise it will lead to unnecessary confusions.Just keep in mind at this point that this is a transfer statement and is used to handle exceptions.


Note : Java is a case sensitive language. So take care of your cases. Also an important thing to mention here is that all keywords in Java are lowercase. So these keywords break,continue,return,try,catch,finally are all lower in case. Also recall that we can't use keywords as variable names.



Sunday, 3 March 2013

Loop Statements in Java

In last post we saw selection statements like if,if-else and switch. Now lets take a look at Loop statements also known as iteration statements.
So this category consist of  while, do while and for statements.Lets see each of them in detail.
  •  while loop - 

    Syntax for while statement is as follows -
    while(condition)
    {
        //Execute some code
    }
     Now lets see what above piece of code actually does.Code which is in the curly braces will keep on executing as long as condition is true.So there mush be some point in execution that the condition must go false only then the context comes out of the loop and proceeds with normal execution.If condition remains true forever the corresponding code will keep on executing unless you give a break statement.We will look into this break statement in detail in Transfer statements. We call this situation as infinite loop condition.Note  condition expression must evaluate to a boolean.

    Note : If you don't provide any curly braces first statement is taken as the code to be executed in while loop by default.If condition is false at the start of the loop, corresponding code will not be executed even once.
  •  do-while loop 

    Syntax for do while loop is as follows - 
    do{
    //Execute some code
    }while(condition)

    Above code will do the same thing as what while loop  does.It will keep on execution some code as long as  condition is evaluated to be true.

    So what is the difference between while and do-while loop?
    Answer is simple. If you observe in while loop we specify condition before the corresponding code whereas in do-while loop we specify it after the code.So if the condition is evaluated to be false while loop will not be executed whereas even if condition is evaluated to be false at the start of execution do-while loop will b executed once.So no matter what do-while loop will be executed at least once.
      
  •  For loop

    Syntax for for loop  is as follows - 
    for (<initialization>; <loop condition>; <increment expression>)
    {
         //Code to execute
    }
    Example
    for(int i=0;i<10;i++)
    {
        System.out.println(i + "\n");
    }
    Above code prints numbers from 0 to 9.Let us analyze it now.
    Inside you for loop first expression in initialization i.e you initialize some variables.Next expression is your looping condition i.e code in curly braces will be executed only when the looping condition is satisfied.Final expression is your increment expression where you increment or decrement variable so as at some point in execution of loop looping condition will not be satisfied and the loop will be terminated.In above code variable i of type integer.i=0 assigns value 0 to variable i.Then for each value of i ranging from 0 to 9 it just prints the value on standard output.When i becomes 10 it checks if i i.e 10 is greater that 10.No i.e loop condition is not satisfies.Terminate the loop and come out.

    Note: initialization is done only once at the start of the for loop.Loop condition is checked every time before entering the loop to execute corresponding code and increment/decrement expression is executed every time after a loop code is executed.

    Another way to use for loop is as follows
    String[] vehicle={'Car','bike','truck'};
    for(String x : vehicle)
    {
        System.out.println(x);
    }

    Above code iterates over all values in array vehicle and prints them to standard output.x here is a local variable to the loop and you can name it anything you want of-course sticking to naming conventions and taking care of scope.Above code will print Car bike and truck to standard output.

    One more thing if you write the following

    for(;;)
    {
       //Code to execute
    }

    it is completely legal.This is nothing but an infinite loop.This is same as doing

    while(true)
    {
       //execute some code
    }

    Note: if you are a C user you might try something like 
    while(1)
    {
       //do something
    }
    but as i mentioned earlier condition must evaluate to be of type boolean.So above code will throw an compile time error.So you need to use true instead of 1 to achieve infinite loop.

    In next post we will see transfer statements like break,continue etc.
     

     

Control flow statements in Java

To actually dictate how your program will run and which part of code should be executed when it is important to know control flow statements.Some of these are same as what we use in C or C++. So lets look into these statements.

There are 3 main categories of control flow statements -
  • Selection statements - if, if-else and switch.
  • Loop statements - while, do-while and for.
  • Transfer statements -  break, continue, return, try-catch-finally and assert.
Now lets look control flow statements in each category in a bit more detailed manner.

Selection statements

  • if statement -  Syntax for if statement is as follows -
    if(condition)
    {
         //code to be executed if condition is true
    }

    Lets analyze above code. We have if keyword followed by condition in brackets.This condition must evaluate to be true or false.If the condition evaluates to be true the code in the curly braces following the if statement is executed.If condition evaluates to be false this code is skipped.
  • if-else statement - Syntax for if-else statement is as follows -
    if(condition)
    {
         //code to be executed if condition is evaluated to be true
    }
    else
    {
         //code to be executed if condition is evaluated to be false
    }
    Very much same as if statement if we neglect the else part. If condition is evaluated to be true code in if part is executed and if condition is evaluated to be false code in else part is executed.
    You can have as many if else statements as you need. Moreover you can even cascade them as below -
    if(condition1)
    {
         if(condition2)
           {
                //condition to be executed when both condition1 and condition2 are true
           }
    }
    You may say above code is same as writing
    if(condition1 && condition2)
    {
         //execute some code
    }

    yes it will implement same logic as above but let sat you want to execute some code when condition1 is true and condition2 is false in order.In this case you have to use cascading method.
    Note - If order is not important you can do something like
    if(condition1 && !condition2){//Do something}
    ! is negation operator
    Also please keep in mind that whenever you write any code please stick to proper "indentation". It not only helps readability but will also help you read your own code better.
  • switch statement - switch statement is used when we know that a variable can take some n values and we need to execute some code corresponding to each value that the variable takes.
    Yes it same as using multiple if-else statements but switch statement gives more clarity and readability to the code.
    Syntax for switch statement is as follows
    switch(vehicle)
    {
       case 'bike' : System.out.println("I am on a bike");
                         break;
      case 'car' : System.out.println("I am in a car");
                         break;
      default : System.out.println("I prefer walking.");
    }

    Lets understand this code line by line.
    First we have switch keyword follower by a variable called vehicle which is of type String.If the vehicle has value bike then program will print I am on a bike on the standard output else if  vehicle has value car then program will print I am in a car on the standard output. If value of vehicle is neither bike nor car then it will go ahead and pick up default case and print I prefer walking.

    Note : I have used String in above case to help you understand how switch works but support for string is added only in Java SE 7 . So if you are using any JDK version before this String will not work. You can only have primitive data types like int, char etc.

    What is the break statement we keep writing in each case?

         break statement simply says if a case is selected and code corresponding to that is executed there is no need to check and cases after that. So just break out of switch statement and carry on with the execution.I have seen many beginners do this mistake. So just note this point.

    What if i miss this break statement?

    To explain this question lets go again to our example code.Lets say vehicle has value bike. So it prints
    I am on a bike .Now if you have not provided with break statement it will go ahead till end of switch statement or till it finds a break statement and execute code corresponding to all values except default of course.

    Important point to be noted in case of switch statement

    •  A switch works with the  byte, short, char, and int primitive data types. It also works with enumerated data types(will be discussed later).
    • default case is executed only when no other cases match. Also since it is the last one to be executed there is no need of break statement. Also position of default case in switch statement is irrelevant.
    • Also note that if variable used in switch statement is of integer type you don't have to put  single quotes like we did in vehicle case as it was of type String.Ex - case 1 : //execute something.
    • It is important to put a break statement in each case.

    We will look into Loop statements and  Transfer statements in next post.



t> UA-39527780-1 back to top