3 Aug 2012

Packages in java with examples

A Package is a collection of related classes, interfaces and sub packages having in each class file a package directive with that directory name at the top of the file.
Packages are nothing more than the way we organize files into different directories according to their functionality, usability as well as category they should belong to. An obvious example of packaging is the JDK package from SUN.
ex: java.util as a package name for the Vector class (java.util.Vector).
The benefits of using package reflect the ease of maintenance, organization, and increase collaboration among developers. 

How to create a package:

Suppose we have a file called HelloWorld.java, and we want to put this file in a package world. First thing we have to do is to specify the keyword package with the name of the package we want to use on top of our source file, before the code that defines the real classes in the package, as shown in our HelloWorld class below:
ex: 
// only comment can be here
package world;

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World");
  }
}
In our case, we have the world package, which requires only one directory. So, we create a directory world and put our HelloWorld.java into it. 

Setting up the CLASSPATH:

 we put the package world under C:. So we just set our CLASSPATH as:
 set CLASSPATH=.;C:\;
We set the CLASSPATH to point to 2 places, . (dot) and C:\ directory.
If you used to play around with DOS or UNIX, you may be familiar with . (dot) and .. (dot dot). We use . as an alias for the current directory and .. for the parent directory. In our CLASSPATH we include this . for convenient reason. Java will find our class file not only from C: directory but from the current directory as well. Also, we use ; (semicolon) to separate the directory location in case we keep class files in many places.
When compiling HelloWorld class, we just go to the world directory and type the command:
C:\world\javac HelloWorld.java
If you try to run this HelloWorld using java HelloWorld, you will get the following error:
C:\world>java HelloWorld
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong name: 
world/HelloWorld)
        at java.lang.ClassLoader.defineClass0(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:442)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:101)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:248)
        at java.net.URLClassLoader.access$1(URLClassLoader.java:216)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:191)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:290)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:286)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
The reason is right now the HelloWorld class belongs to the package world. If we want to run it, we have to tell JVM about its fully-qualified class name (world.HelloWorld) instead of its plain class name (HelloWorld).
C:\world>java world.HelloWorldC:\world>Hello World
fully-qualified class name is the name of the java class that includes its package name.
We can run the HelloWorld from anywhere as long as we still include the package world in the CLASSPATH. For example,
C:\>set CLASSPATH=.;C:\;
C:\>set CLASSPATH // see what we have in CLSSPATH
CLASSPATH=.;C:\;
C:\>cd world
C:\world>java world.HelloWorld
Hello World
C:\world>cd ..
C:\>java world.HelloWorld
Hello World

Subpackage (package inside another package):

Assume we have another file called HelloMoon.java. We want to store it in a subpackage moon, which stays inside package world. The HelloMoon class should look something like
package world.moon;

public class HelloMoon {
  private String holeName = "rabbit hole";
  
  public getHoleName() {
    return hole;
  }
  
  public setHole(String holeName) {
    this.holeName = holeName;
  }
}
Although we add a subpackage under package world, we still don't have to change anything in our CLASSPATH. However, when we want to reference to the HelloMoon class, we have to use world.moon.HelloMoon as its fully-qualified class name.

How to use package:

There are 2 ways in order to use the public classes stored in package. 1. Declare the fully-qualified class name. For example,
...
world.HelloWorld helloWorld = new world.HelloWorld();
world.moon.HelloMoon helloMoon = new world.moon.HelloMoon();
String holeName = helloMoon.getHoleName();
...
2) Use an import keyword:
import world.*;  // we can call any public classes inside the world package 
import world.moon.*;  // we can call any public classes inside the world.moon package
import java.util.*;  // import all public classes from java.util package
import java.util.Hashtable;  // import only Hashtable class (not all classes in java.util package)
Thus, the code that we use to call the HelloWorld and HelloMoon class should be
...
  HelloWorld helloWorld = new HelloWorld(); // don't have to explicitly specify world.HelloWorld anymore
  HelloMoon helloMoon = new HelloMoon(); // don't have to explicitly specify world.moon.HelloMoon anymore
... 
Note that we can call public classes stored in the package level we do the import only. We can't use any classes that belong to the subpackage of the package we import. For example, if we import package world, we can use only the HelloWorld class, but not the HelloMoon class.

Using classes stored in jar file:

Jar files are the place where we put a lot of files to be together. We compress these files and make them as a single bundle. Jar files may also include directories, subdirectories to represent class and package hierachy. Normally, we can see what is inside a jar file by using the command jar -tcf filename.jar as shown in Figure:
we have to include this package in the CLASSPATH as well.
set CLASSPATH=.;D:\JSDK2.0\lib\jsdk.jar;
Note that if the package is stored inside a jar file, we have to include the jar file with its extension (.jar) in the CLASSPATH. However, if the package is a plain directory, we just put the name of directory into the CLASSPATH

2 Aug 2012

Methods in java

A method is a collection of statements that are grouped together to perform an operation. 
       Creating a Method:
           In general, a method has the following syntax:

           modifier return_type method_name(list of parameters)
          {
              //method body;
          }

       A method definition consists of a method header and a method body. Here are all the parts of          a method:
  • Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.
  • Return Type: A method may return a value. The return_type is the data type of the value the method returns. Some methods perform the desired operations without returning a value.
  • Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.signature represents any one of the following.
    -> Number of Parameters
    -> types of Parameters
    -> Order of Parameters, at least one thing must be different
  • Parameters: A parameter is a container. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
  • Method Body: The method body contains a collection of statements that define what the method does.

    Calling a Method:

    In creating a method, you give a definition of what the method is to do. To use a method, you have to call or invoke it. There are two ways to call a method; the choice is based on whether the method returns a value or not.
    When a program calls a method, program control is transferred to the called method. A called method returns control to the caller when its return statement is executed or when its method-ending closing brace is reached.
    If the method returns a value, a call to the method is usually treated as a value. For example:
    int l=max(10,20);

    println() method, print()  method are two predefined methods present in a predefined class called PrintStream class. To access these two methods we must create an object of PrintStream class. an object of PrintStream class called out created as static data member in another predefined class called System. Hence, println() and print()  methods must be accessed as follows
    System.out.print();
    System.out.println();

    Using Command-Line Arguments:
    Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ).
    A command-line argument is the information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy.they are stored as strings in the String array passed to main( ).
    Example:
    The following program displays all of the command-line arguments that it is called with:

    class demo
    {
      public static void main(String arg[])
      {
        for(int i=0;i<arg.length;i++)
        System.out.println(arg[i]);
      }
    }

    Try executing this program, as shown here:
    C:\java demo this is command line args
    Output:
    this
    is
    command 
    line 
    args

    Overloading Methods: Overloaded Method is one in which method name is same but its signature is different.
    ex:
    public void test(double  a, double b)
    {
                  //method body;
    }

    public void test(int a, int b)
    {
                  //method body;
    }

    If you call test with int parameters, the test method that expects int parameters will be invoked; if you call test with double parameters, the test method that expects double parameters will be invoked. This is referred to as method overloading.
    Overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or return types.
    Constructors:
    Constructors are special methods which will be called by the JVM automatically whenever an object is creating for placing our own values. Most often you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method.

    Advantages:
    1. It eliminates in placing default values.
    2. It eliminates in calling ordinary methods explicitly.
    3. Constructors are always used for initializing an object.

    ex:

    class myclass
    {
      int x;
      myclass()
      {
         x=10;
       }
    }

    class demo
    {
     public static void main(string arg[])
     {
       myclass my=new myclass(); //You would call constructor to initialize objects
      }
    }

    Passing Parameters by Values:

    When calling a method, you need to provide arguments, which must be given in the same order as their respective parameters in the method specification.
    When you invoke a method with a parameter, the value of the argument is passed to the parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method.

    ex:
    public static void Println(String msg, int n)
    {
       for(int i=0; i<n; i++)
       System.out.println(msg);
    }

    Here, you can use Println("Hello", 3) to print "Hello" three times. The Println("Hello", 3) statement passes the actual string parameter, "Hello", to the parameter, msg; passes 3 to n; and prints "Hello" three times. However, the statement Println(3, "Hello") would be wrong.

what is JVM?

JVM stands for Java Virtual Machine. It is a set of programs developed by Sun micro system and supplied as a part of Java Run Time Environment(JRE).Firstly we write the simple java program(source code) the java compiler converts the source code into the byte code, after that JVM reads this bytecode and converts this into the machine code.

The byte code format is same on all platforms as it runs in the same JVM and it is totally independent from the Operating System and the Processors without considering their architecture.
Byte code is an intermediary language between Java source and the host system. Most programming language like C and Pascal converts the source code into machine code for one specific type of machine as the machine language vary from system to system . Mostly compiler produce code for a particular system but Java compiler produce code for a virtual machine. .

How to write first Java Program:

public class demo
{
public static void main(String arg[])
{
   System.out.println("This is my first program....");
}
}


Save the file with same name as the public class just adding the extension '.java' 
ex: demo.java 
Now compile as:
c:\ javac  demo.java
This creates a  class file in with the same name, This is the bytecode form of Java program. 
Now to execute this code:
c:\ java  demo
OUTPUT:
This is my first program....

1 Aug 2012

super() in java with example


A class can contain a single default constructor and 'n' number of constructors. If you want to call 
the base class constructors from the derived class constructors, in java we have two methods.
1.super()
2.super(...)

this(): It is used for calling super class's default constructor from the default(zero argument) or parameterized constructor of derived class and applying super() in the context of derived class constructors is optional.
this(...): It is used for calling  super class's  parameterized constructor from the default(zero argument) or parameterized constructor of derived class.
     Whenever we use either super() or super(...) in the current class constructors, they must be used as first statement in the current class constructors. Otherwise, we get compile-time error.

Sample Code:

class test
{
  int a,b;
  test()
   {
     test(1000);
     a=10;
     b=20;
     System.out.println("a: "+a);
     System.out.println("b: "+b);
    }
    test(int x)
    {
      a=b=x;
      System.out.println("a: "+a);
      System.out.println("b: "+b);
    }
}

class test1 extends test
{
 test1()
{
 super();
 }
}
class demo
{
 public static void main(String arg[])
 {
   test1() t=new test1();
 }
}

super keyword in java with example


the super keyword indicates the following :

1. The super keyword in java programming language refers to the superclass of the class where the super keyword is currently being used.
2. The super keyword as a standalone statement is used to call the constructor of the super class of the class which extends 
the super class or to call the method of the super class of the class which extends the super class .

Example to use the super keyword to call the constructor of the superclass in the base class:
public class class1
{
public class1(String arg)
{
super(arg);
}
..................
}
-->  The syntax super.<method_Name>() is used to give a call to a method of the superclass in the base class.
--> This kind of use of the super keyword is only necessary when we need to call a method that is overridden in this base class in order to specify that the method should be called on the superclass.


Example to use the super keyword with a variable:

class A
{
int k = 10;
}
class Test extends A
{
public void m()
{
System.out.println(super.k);
}
}

Example to use the super keyword with a method:


public class class1
{
.............................//block of statements
public String fun()
{
 ............................//block of statements
}
.............................//block of statements
}


public class class2 extends class1
{
.............................//block of statements
public String fun()
{
return super.fun();
}
.............................//block of statements
}


this() in java

A class can contain a single default constructor and 'n' number of constructors. If you want to call 
a constructor of same class from another category constructor of same class then you must use the following methods.
1.this()
2.this(...)

this(): It is used for calling a default constructor from parameterized constructor of same class.
this(...): It is used for calling a  parameterized constructor of current class from another category constructors of same class.
     Whenever we use either this() or this(...) in the current class constructors, they must be used as first statement in the current class constructors. Otherwise, we get compile-time error.

Sample Code:

class test
{
  int a,b;
  test()
   {
     test(1000);
     a=10;
     b=20;
     System.out.println("a: "+a);
     System.out.println("b: "+b);
    }
    test(int x)
    {
      a=b=x;
      System.out.println("a: "+a);
      System.out.println("b: "+b);
    }}
class demo
{
 public static void main(String arg[])
 {
   test() t=new test();
 }
}

this keyword in java with example


The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid name conflicts. As we can see in the program that we have declare the name of instance variable and local variables same. Now to avoid the confliction between them we use this keyword. Here, this section provides you an example with the complete code of the program for the illustration of how to what is this keyword and how to use it.

In the example, this.length and this.breadth refers to the instance variable length and breadth while length and breadth refers to the arguments passed in the method. We have made a program over this. After going through it you can better understand.

1. It points to current class object.
2. In order to differentiate between formal parameters and data members of the class when both variable names are same, data members of the class must be preceded by keyword this.

Here is the code of the program:

class test
{
    int a,b;
    disp(int a,int b)
    {
     this.a=a;
     this.b=b;
     System.out.print("a: "+a+"b: "+b);
     }
}

class demo
{
 public static void main(String arg[])
 {
  test t=new test();
  t.disp(10,20);
  }
}

new operator in java


In Java in order to create an object ,we must follow dynamic memory allocation by using new operator.
new operator is known as dynamic memory allocation operator.

operations of 'new':
1. It allocates sufficient amount of memory space for the data members of the class.
2. It takes an address of created memory space or address of the class and placed into object name.

Syntax:

 <class_name> object_name=new <class_name()>;
                            (or)
<class_name> object_name; //declaration
    object_name=new <class_name()>;

Here,
class_name is the name of the class.
object_name represents a valid variable name of java.

Whenever an object is declared whose default value is 'null'.Any attempt to use object_name,will result in compile time error.

Whenever an object is referenced whose default value is not 'null'.It simply holds the memory address of the actual object_name.

Final Variable in Java


Any variable either member variable or local variable (declared inside method or block) modified by final keyword is called final variable. Final variables are often declare with static keyword in java and treated as constant.

In Java to make any thing thing as constant we use a keyword final.
The final keyword is placing an important role in three levels.They are

1. At variable level

syntax:    final datatype variable_name=variable_value;
example: final int a=10;

Therefore final variable values can not be modified.

2. At method level

Final keyword in java can also be applied to methods. A java method with final keyword is called final method and it can not be overridden in sub-class. You should make a method final in java if you think it’s complete and its behavior should remain constant in sub-classes. Final methods are faster than non-final methods because they are not required to be resolved during run-time and they are bonded on compile time.

syntax: final return type method_name(list_of_parameters)
{
//body
}

Once the method is final which can not be overridden.

3. At class level

Java class with final modifier is called final class in Java. Final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer and other wrapper classes.
syntax: final class <class_name>
{

//.................................
}

final classes never participates in inheritance process.But, a inner class may be final or abstract.

Features of Java


Features of any Programming Language is nothing nut the list of services provided by the language to the industry programmers.
Java language provides 13 features.They are

1.Simple
2.platform independent
3.Architecture Neutral
4.Portable
5.Multithreaded
6.Interpreted
7.Object Oriented
8.Robust
9.Distributed
10.Dynamic
11.Secure
12.Performance
13.Networked

The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language.

1. SimpleThere are various features that makes the java as a simple language. Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system but we can not say about the other programming languages. Java provides the bug free system due to the strong memory management. It also has the automatic memory allocation and deallocation system.The java programming environment contains in build garbage collector for improving the performance of the java applications by collecting unreferenced memory space.

2. Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language. Not even a single language is idle to this feature but java is more closer to this feature. The programs written on one platform can run on any platform provided the platform must have the JVM. 

3. Architecture Neutral
Java is an architectural neutral language as well. The growing popularity of networks makes developers think distributed. In the world of network it is essential that the applications must be able to migrate easily to different computer systems. Not only to computer systems but to a wide variety of hardware architecture and Operating system architectures as well.  The Java compiler does this by generating byte code instructions, to be easily interpreted on any machine and to be easily translated into native machine code on the fly. The compiler generates an architecture-neutral object file format to enable a Java application to execute anywhere on the network and then the compiled code is executed on many processors, given the presence of the Java runtime system. Hence Java was designed to support applications on network.


4. Portable
A portable application is one which runs on all operating systems and on all available processors without considering their vendors and architectures.

portability=platform independent + architectural neutral

5.  Multithreaded
Java is also a Multithreaded programming language. Multithreading means a single program having different threads executing independently at the same time. Multiple threads execute instructions according to the program code in a process or a program. Multithreading works the similar way as multiple processes run on one computer.
Multithreading programming is a very interesting concept in Java. In multithreaded programs not even a single thread disturbs the execution of other thread. Threads are obtained from the pool of available ready to run threads and they run on the system CPUs. This is how Multithreading works in Java which you will soon come to know in details in later chapters.

6. Interpreted
We all know that Java is an interpreted language as well. With an interpreted language such as Java, programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program.
Advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.

7. Object Oriented
To be an Object Oriented language, any language must follow at least the four characteristics.
  • Inheritance   :   It is the process of creating the new classes and using the behavior of the existing classes by extending them just to reuse  the existing code and adding the additional features as needed.
  • Encapsulation  :   It is the mechanism of combining the information and providing the abstraction.
  • Polymorphism   :   As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the functions  having the same name based on the signatures of the methods.
  • Dynamic binding  :   Sometimes we don't have the knowledge of objects about their specific types while writing our code. It is the way of providing the maximum functionality to a program about the specific type at runtime.  
Java, it is a fully Object Oriented language because object is at the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into object by using the wrapper class.

 8. Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust.

9. DistributedThe widely used protocols like HTTP and FTP are developed in java. Internet programmers can call functions on these protocols and can get access the files from any remote machine on the internet rather than writing codes on their local system.

10. Dynamic
While executing the java program the user can get the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the Internet.
The language java always follows dynamic memory allocation only.
Dynamic memory allocation is one in which memory will be allocated at run time.

11. SecureJava does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading. 

12. PerformanceJava uses native code usage, and lightweight process called  threads. In the beginning interpretation of bytecode resulted the performance slow but the advance version of JVM uses the adaptive and just in time compilation technique that improves the performance. 

13. Networked
The basic aim of networking is to share the data between multiple machines either locally or globally.we can develop internet applications by making use of J2EE and also we can develop intranet application by making use of J2SE.