Tuesday, October 22, 2013

Arrays in Java

What is an array ?

  • An array is a container object that holds a fixed number of values of a single type. 
  • This is used to store fixed size sequential collection of same type data.
  • It means this is a simple type of data structure.

How to create an array ?

There are three steps when you are going to create an array
  1. Declare array
  2. Construct array
  3. Initialize array

Declare a array

Arrays can be declared as follows.

        Datatype [] Arrayname ;
        Datatype Arrayname [] ;

Look following the examples for understand.

        int marks[]; String names[]; int [] ages;

Construct an array

You can construct an arrays using new keyword. 

       Datatype [] Arrayname  = new Datatype [];

Please look at following examples.
       int marks[] = new int[10]; or you can use as follows.

       int marks[] ; 
       marks = new int[];

Initialize an array

Initialize means, fill the array. Look at followings.
       int marks[0] = 10;
       int marks[1] = 10;
       int marks[2] = 10;
       int marks[5] = 10;

Anonymous arrays

You can declare and initialize arrays in simple manner as follows.
         int marks [ ] =  {10,20,30,40};

You may look at following example to understand about arrays.

public class ArrayDemo {
 public static void main(String args[]) {

  int marks[] = new int[3];
  marks[0] = 10;
  marks[1] = 50;
  marks[2] = 80;

  String names[] = { "Ravi", "Sean", "John" };

  char grade[] = { 'A', 'B', 'C' };

Array length attribute

This can be used to get the length of a array.

public class ArrayLengthDemo {
 public static void main(String args[]) {

  int marks[] = new int[3];
  int ages [] = {26,28,24,30};


2D arrays

Look at the following example. In this table it has columns and rows. Generally 2D arrays can be declare as follows.

         int [][] = new int [2][3];

You may look at the following example to understand about arrays. 

public class ArrayDemo{
 public static void main(String args[]) {

  int i, reg = 0, marks = 0;

  Scanner scn = new Scanner(System.in);
  int arr[][] = new int[10][2];

  for (i = 0; i < 5; i++) {
   System.out.print("Enter reg number: ");
   reg = scn.nextInt();
   arr[i][0] = reg;

   System.out.print("Enter your marks: ");
   marks = scn.nextInt();
   arr[i][1] = reg;

  System.out.println("\n-----Marks table-----\n");
  System.out.println(" Reg No \t Marks");

  for (i = 0; i < 5; i++) {
   System.out.print(" " + arr[i][0]);
   System.out.println("\t\t " + arr[i][1]);

Friday, October 18, 2013

Non access modifiers

Java provides a set of non access modifiers to produce some other functionality.
  1. static
  2. final
  3. abstract
  4. synchronized
  5. native
  6. transient
  7. volatile
  8. strictfp


Static variables
  • We have learned about this thing as class variables in Java variables post in this blog.
  • You can get the idea about static variables after referring that post.

Static methods
  •  These methods are defined using 'static' keyword.
  • Class variables and also class methods ( static methods ) can be accessed using class name.
          Ex:-     className.staticMethodName( );
  • Static methods can directly access to other static members in the class.
  • But non static members can't access to static methods.
Try this program

public class StaticDemo{

   int x;
   static int y=10;

   public static void main(String args[]){
      Apple.test(); // Static methods are called using class name 

   public static void test(){
      System.out.println(y);//Static variables can be used directly in static method
      //System.out.println(x); you can't access x in a static method

You can remove comment on last line and compile it.
Then you can see a error message as follow .

Static initialization block
  • This is a simple block With static keyword and { }.
  • Only static members can accessed to this block.
  • When you run the program, static initialization blocks are called to the order to their positions in the program
Try this program to understand static block.

public class StaticDemo{

      System.out.println("Static block 1");

   public static void main(String args[]){ 
      System.out.println("Main method");

      System.out.println("Static block 2");

      System.out.println("Static block 3");


  • You can get the idea about this keyword thinking on its real meaning.
  • This can be used to classes, methods, objects and variables. 
  • If you used this once the value  can't be changed again.

Final variables

  • We have discussed three types of variables ( instance, static,local ) in this series. 
  • This ' Final ' keyword can be used all of these types.
  • These are like constants. 

Try this program.

public class FinalDemo{
   public static void main(String args[]){
       final int MAX_DIS = 5;

       //MAX_DIS = 10;

Now you can see the output is 5.
  • You can see I commented some lines.
  • If you can remove these comments and compile it again. 
  • Then it will give a error message as follow. 

It means that the final variable can't be changed.

Final methods

  • Final methods cannot be overridden in other sub classes.
  • It means the behavior of that method cannot be changed.
Try this program

public class Fruit{
   public static void main(String args[]){      
      Fruit obj1 = new Fruit();
      Banana obj2 = new Banana();


   final void eat (){

class Banana extends Fruit{ 
   void drink(){
   //void eat(){ }

  • Now I think you can understand what this program does. 
  • In my super class ( Apple ) I have defined two methods ( main, eat ).
  • The eat( ) method is final method.
  • Then I have created another sub class Banana which extends keyword. It means that Banana class is inherited by Apple class ( Apple - parent, Banana - child ). This is oop concept, so it will discussed later on the series.
  • When you compile and run this program it is ok and it gives the output.
  • Now you can remove comments in the program and compile it. Then you will be able to see the error message as follow.

Final classes

  • Final classes cannot be extended.
  • It is a final segment of class hierarchy of the program.
Try this program...

public class Apple{
   public static void main(String args[]){

      Apple obj1 = new Apple();
      Banana obj2 = new Banana();


   final void eat (){

final class Banana{ 
   void drink(){

/* class Pear extends Banana{
 *    void steam() { }
 * }

  • This is same as above example.
  • If you remove comment on this program and compile it, you will be able to see a error message.


  • Abstract keyword can be applied to classes and instance methods only.
  • This means things incomplete or to be complete later.
  • Abstract is like opposite of 'final' keyword.

Abstract classes

  • The class can be declared as abstract class using ' abstract ' keyword.
  • But even if you not declared class as abstract, the can become abstract if there is at least one abstract method.
  • Abstract class can have non abstract methods also. 
  • An abstract class can never be instantiated. It can't be created objects using abstract class.

abstract class Apple{
   public abstract void mix(); //abstract class
   public void blend () {  };  //non abstract class

Abstract methods
  • Abstract methods doesn't have a method body. It has only specification.The method body is provided by sub class.
  • These methods can never be final and it can't be used private access modifier.
  • The method declaration of this methods are different from other methods.
Ex:-    public abstract void eat();

Try this.

abstract class Apple{
   public abstract void eat();
   public void cook(){ } ;

class Mango extends Apple{
   public void eat(){

public class Fruit{
   public static void main(String args[ ]){

      Mango obj1 = new Mango();
      Apple obj2 = new Mango();
      //Apple obj3 = new Apple(); 

See more about abstraction.


  • This can only be used to methods or you can use is as a block.
  • If you use this keyword in a method, that indicate the method can be accessed by only one thread at a time.
  • You can use any of access modifiers to set access level.
Ex:-    public synchronized void DisplayDate( ) {   }

You may look at this post which is about Synchronization.


  • This can only be used for methods.
  • Native methods are used to access some other platforms by loading native libraries. 
  • Native methods do not have method body.
Ex:-    native void DoSomething( );


  • This can be used to variables.
  • The types of variables are used to signify the JVM to skip this variable in serialization process.
  • In serialization process, it can be stored the state of object.
  • Serialization transform object into output type.

public transient int avg = 10; //transient value
public int spd;  //persist value



  • This can be applied to interfaces, classes and methods.
  • Strictfp ensures that you get exactly the same results from your floating point calculations on every platform.
  • But most programmers never need to use strictfp modifier, because it affects only a very small class of problems in programming.
  • A strictfp method ensures that all code in the method is executed strictly.

    Tuesday, October 15, 2013

    Access modifiers

    Access modifiers are used to set access level to a program. There are four types of levels we are talking about in Java. 
    1. Private
    2. Protected 
    3. Default
    4. Public

    We have classes, packages, sub classes and the world in programs. Look at this graph. 

    This may help you to understand about access levels.

    Now we focus on how to access using these modifiers and where can it be applied.

    Try this programs to understand about this theory.

    public class Fruit{
       public static void main(String args[ ]){
          Fruit obj1 = new Fruit( ); 
          Apple obj2 = new Apple( ); 
          Mango obj3 = new Mango( ); 
          //Woodapple obj4 = new Woodapple( ); 
          obj1.mix( );
          obj1.extract( );
          obj1.blend( );
          obj2.boil( );
          obj3.fry( );
          //obj4.cool( );
      void mix( ){
          System.out.println(" Class Access method ");
          System.out.println("Fruit--> default----> mix( )");
      private void extract( ){
          System.out.println("Fruit--> private----> extract( )");
      protected void blend( ){
          System.out.println("Fruit--> protected--> blend( )");
    class Apple{
      void boil( ){
          System.out.println("Apple--> default----> boil( )");
    class Mango{
      protected void fry( ){
          System.out.println("Mango--> protected--> fry( )");
    * class Woodapple{
    *   private void cool( ){
    *       System.out.println("Woodapple--> private--> cool( )");
    *   }
    * }

    In this program my super class is Fruit. There are other two classes named Apple and Mango.
    Within my super class it has three methods ( mix, extract, blend ) and main method. each of method has different types of access levels.
    • mix - default
    • extract - private
    • blend - protected
    Now you can see that within the same class you can access any access modifier. 

    But in this program it is difficult to explain about the behavior with interfaces and packages. Because interfaces are not discussed yet in this series. These things will be discussed later on this blog.

    You can try changing access levels in classes also.

    In this program I have commented some lines. You can remove comments and see the error message appeared. 

    It means that it can't be accessed outside class with 'private' access level.

    You can download the code HERE...
    Compile and run the program HERE...

    Sunday, October 13, 2013

    Classes, methods and objects in Java

    Classes in Java

    • Anything that you want to represent in Java, should be capsuled to a class.
    • A class is a blue print from which individual objects are created.

    • Class create objects and methods are used to communicate between these objects.
    • Actually methods are behaviors of objects. 

    How to declare a class 
    • Simply a class can be declared as follows.

    class ClassName{

    • This Java naming conventions post may help you to understand; how to declare a class with correct Java standards.
    • According to the object's behaviors, you can modify a class with Access modifiers, Non access modifiers, implementing to an interface or extending to a class.

    public class ClassName extends AnotherClass implements interface1, interface2{

    • In Java you can inherit from only one class but more interfaces. 
    • Access or non access modifiers should be used just before the class keyword. 

      Methods in Java

      • Methods are used to manipulate data in an object.
      • Actually methods are behaviors of an object (class). Look at the following example.

      accessModifier returnType methodName(parameter list){
         method body

      Access modifiers
      • Access modifiers gives permissions to access. As you can see access modifiers can be used for classes, methods and also variables.
      • You may look the following example about Access modifiers.
      Return type
      • Return types are used to represent the type of returning element.
      • It can be int, double, char, String, void, Object or any type.
      • If you use void, it means you don't return anything.
      • Look at this post which is about Java naming standards. 
      Parameter list
      • Parameters should be used with in brackets in a method.
      • Look at the following example.

      public int getData(int x, int y){

      Types of methods

      Basically there are three types of methods.
      1. Instance methods
      2. Static methods
      3. Abstract methods
      Instance methods
      • These methods are loading when object is created.
      • We can call instance methods just calling through objects.
      public int getData(int x, int y){

      Static methods
      • Static methods are defined, using "static" keyword.
      • We need not to use objects to call static methods, so we can call it by using the class name. But if you want it can be called through objects.

        public class Demo {
           public static void main(String[] args) {
               eat(); //Just calling method
               Demo.eat(); // Calling method through class
               Demo demo = new Demo();
               demo.eat(); //calling methof through class object
           public static void eat(){
               System.out.println("eat method");

        Abstract methods
        • These methods are defined with abstract keyword before method name.
        • Abstract methods are defined without an implementation.
        • It means there is no method body in abstract classes.
        • Semi colon is used instead of curly braces. Look at the following example.
        public abstract int getData();

        Method argument passing
        1. Object type
        2. Primitive type
        Object type
        • Original value can be changed within this type.
        Primitive type
        • In this type we just using a copy of the original variable.
        • The value can be changed inside method, but no effect to original value.

        public class Demo {
           int i;
           public static void main(String args[]) {
               Demo demo = new Demo();
               demo.i = 10;
           public void CheckResult(Demo d) {
               i = 50;

        Objects in Java

        • Objects are real world objects (Car, Dog, Student...etc.)
        • Object has states and behaviors.
        • Just a moment think about a cat.
                           states - color, name, breed
                           behaviors - eat(), drink(), walk()

        • Scientifically Java Objects are defined as a memory locations in RAM.

        How to create objects ?

        Look at the following example to get an idea about objects.

        public class Demo{
            public static void main(String[] args) {
                Demo obj1 = new Demo();
                Demo obj2 = new Demo();
            public void apple() {
                System.out.println("This is apple method");
            public void mango() {
                System.out.println("This is mango method");