Featured Posts


All About INTERFACE ListPeer in AWT in Java

November 16, 2018

The scrolling ListPeer Interface specifies the methods that all implementations of Abstract Window Toolkit must define while working with lists.
The structure of interface ListPeer is given as:

public interface java.awt.peer.ListPeer extends java.awt.peer.ComponentPeer{
public abstract void addItem(String item,int index);
public abstract void clear();
public abstract void delItems(int start,int end);
public abstract void delselect(int index);
public abstract void makeVisible(int index);
public abstract void select(int index);
public abstract void setMultipleselections(boolean v);
public abstract int[] getSelectedIndexes();
public abstract Dimension minimumSize(int v);
public abstract Dimension preferredSize(int v);

All About INTERFACE ListPeer in AWT in Java All About INTERFACE ListPeer in AWT in Java Reviewed by Animesh Chatterjee on November 16, 2018 Rating: 5

All About Methods in Java

November 16, 2018

Parameter names are arbitrary but meaningful identifiers for types that are passed to the methods. Methods may or may not have parameters.

Arguments represents actual values passed to method when it is executed so that it can use them for some specific purpose within the implementation of the method.The data types defined in the implementation language of the class or it can be class type.

The return type is the type that the method returns when method is finished its execution. The return is also primitive data types(defined in Java). On the other hand there may not be any return type . In that case it will be void. Void says that the method does not return any value when it finishes its execution.
Method declaration syntax:

methodName(parameterList) throws ExceptionLists
main(String args[]) throws ArrayOutOfBoundException,IllegalThreadStateException
Method implementation

access_specifier modifier returnType methodName(parameterList) throws ExceptionLists{

public static void main(String args[]) throws ArrayOutOfBoundException,IllegalThreadStateException{
Method calling general Syntax:

Student std=new Student();

a method can not be passed as an argument to another method or in constructor.Instead an object reference is passed to the method or constructor so that the object reference is made available to that method or constructor or to other members of the class that invokes the method.The single parameter is replaced by a computable value i.e an argument when the method is invoked and executed.
Return types of a method:
Java methods can return one of the following:

  • Void- if the method does not return anything
  • One of the java's primitive datatypes
  • A class object
The return keyword has two objectives:

  1. It indicates that the method is done,no statement after return will be executed.
  2. It produces a value and passed right after the return statement.
If we wish to return nothing from a method then we can do the followings:
  1. We have to remove return statement.
  2. We have to write void instead of any datatype. 

The return statement in second and third cases must match the return type specified in the deceleration of the method.In that it must return a value of the same type as the return type.If stated void there should not be any return statement in the method body.
The argument list
The method argument list specifies what info we will pass into the method. The argument list is nothing but form of object.So what we pass via argument list is/are the handle(s)[Exception-the primitive datatypes(boolean,char,byte,short,int,long,float,double)].

int getSize(String str)
return str.length();
This argument is of type String and called str,passed into the method to find the size of str to the method called getSize().length() method is defined in the String class that returns the number of characters present in the string.
All About Methods in Java All About Methods in Java Reviewed by Animesh Chatterjee on November 16, 2018 Rating: 5

Inheritance Concept Simplified In Java

November 16, 2018

Inheritance allows descendants of  a class (known as child class or subclass) to inherit all of its member elements and methods from its ancestor(Known as Parent class or super class).
The advantage of Inheritance is that it supports incremental development by allowing us to write new code without affecting the previously deployed code. By inheriting from an existing functional class,we add new methods and data members. This mechanism leaves the actual code as it is and all changes happens to be in defined  in derived class . This also helps in tracking the bugs easily.
Another aspect of Inheritance is that we don't need the source code of the base class. Rather we need to import that class and write an extend keyword to our class.No copy paste is required.
Inheritance works as a building block providing incremental support which is very much sustainable.

An Example

class MyClass{
    public int x,y;
    MyClass(int x,int y)
class MyAnotherClass extends MyClass{
    int z;
    //inherits x,y from 
    MyAnotherClass(int x,int y,int z)
    //code duplication
    //instead use super
    void displayValues()
public class TestInheritance{
    public static void main(String args[])
        MyAnotherClass mac=new MyAnotherClass(3,2,2);
relax!! the code won't compile if we do not activate super() and activate the two commented lines. This is just to show how we can do repetition of data if we do not take help from Inheritance.To avoid the repetition of code ,java uses a special keyword called Super,this can be used to refer directly to super class constructor.
this is another keyword user to tell java compiler that this will refer to current object.
Let us see one more example

class Toy{
    void createNoice()
        System.out.println("DUM DUM");
class RailToy extends Toy{
    void createNoice()
        System.out.println("JHIK JHIK");
class BusToy extends Toy{
    static boolean noHorn;
    void createNoice()
public class MyToy{
    public static void main(String args[])
        RailToy rt=new RailToy();
        BusToy bt=new BusToy();
Output of the code:
$javac MyToy.java
$java -Xmx128M -Xms16M MyToy
Here createNoice() method is overridden in the respective classes,with a condition that if noHorn is set to true it will invoke the Toy class's createNoice() method.
Inheritance Concept Simplified In Java Inheritance Concept Simplified In Java Reviewed by Animesh Chatterjee on November 16, 2018 Rating: 5

What Is UpCasting in Java?

November 16, 2018

The relationship between base class and derived class is called casting.The derived class is a type of base class.
Due to inheritance all methods in the base class are available to the derived class or child class. So any message we sent to base class can also be sent to derived class or child class.
lets us check an example:

//parent class
class Shape{
public void calculateArea(){
public static void createShape(Shape i)
//Rectangle object is a Shape as they have same interface
public class Rectangle extends Shape{
    public static void main(String args[])
        Rectangle rect=new Rectangle();
The base class Shape has a method -calculateArea() so as the child class-Rectangle.createShape() method accepts an Shape reference.In Rectangle class the main method call createShape by providing Rectangle object.
Java is popular for type checking but in this case it accepts another type. But here Rectangle is a Shape object and there is no method that createShape() could call for instrument that is not in Rectangle class.Inside createShape() , the code works for Shape and anything derived from Shape.The act of converting a Rectangle object (derived/child class object) reference or pointer into an Shape object is called upcasting.
When class inheritance diagram is drawn it is traditionally downwards.Casting from derived to base moves up the inheritance diagram -popularly known as upcasting.
Upcasting is always safe as we move towards to more generic type from specific type.The downside of upcasting is that the more we go towards up,we loose the methods.This is why compiler allows us to do upcasting (without any explicit casts or other specific notation).To determine whether we should use composition or inheritance,we need to ask if we need to upcast from our new class to base class. If we must upcast , then inheritance is necessary.
What Is UpCasting in Java? What Is UpCasting in Java? Reviewed by Animesh Chatterjee on November 16, 2018 Rating: 5

Package Concept Simplified In Java

November 08, 2018

Hide the implementation: Package concept
Java provides an opportunity to separate the things that change from the  things that stay the same. For example a Library,the client who is using it should be able to rely on the part they are using and know that they wan't have to rewrite code if a new version of library comes out.The library creator must have the freedom to make modification and improvements with utmost care so that the client programmer's code won't be affected by those changes.
The common conventions are:

  • The library programmer must agree not to remove existing methods when modifying a class in the library,as it may break the client code.
  • The library creator can not revamp the entire package or library.
To avoid the issue regarding this java provides access specifier to allow the library creator to specify something is available for consumers and remaining are not.Java does that by access specifiers.(public protected,private etc). This concept will ensure that all internal methods and data are private and only some method and data are exposed to the consumer.To understand it better lets us understand the .class file creation from a class. There can be only one public class in each compilation unit. When we compile a .java file,we get a .class file with same name as the public class. If there are many classes in a .java files, those many .class files will be created.These .class files are packaged together with linker to create an executable file.A working program is a bunch of .class files compressed in a jar.Java interpreter is responsible for finding ,loading and interpreting these files.There is nothing in java that forces the use of an interpreter. There exist native code , that produces a single executable file.A library is also a bunch of class files.Each file has one class that is public and there is one component for each file.
Advantages of Package

  • Ability to reuse a code by sub classing existing classes (by inheritance)
  • Collection of related classes(audio,video,text,graphics,project etc)
  • Make a structure that is compartmentalized.()
Import statement
In java we use import statement or keyword to bring in an entire library.The compiler will use this import statements to locate the actual class or where it is defined.

import java.util.*;
//.* will wildcard the package name and includes all packages under util.
import java.util.Vector
//Specify the full name only that particular class from the util package will be imported
How package solve namespace or name collision issue
The reason for import statement is to provide a mechanism to manage 'namespace'.Say classA has a foo() method and another class ClassB also has a foo() method. By the above way we can resolve the name collision and namespace.If there is any name collision like same class name is located under x and y both packages,in that case we have to use import x.nameoftheclass or y.nameoftheclass to use respective class
How to create our own package

package MyPackage;//package declaration 
public class MyClass{//class definition 
public void test(){
System.out.println("Welcome to my class");
Once saved in MyClasss.Java,it will be located in a directory named MyPackage. After compilation,we will get MyClass.class file in the same directory.We are indicating the compiler unit that MyPackage library will also be part of the compilation unit.That is teh public class name within this compilation unit is under the umbrella of the name-MyPackage.If anyone wants to use the name,they will either have to fully specify the name or use the import statement in combination with MyPackage.If the name of the file is MyClass.java,this means there can be one and only one public class in that file. The name of that class must be in MyClass.

How to access:
If anyone wants to use MyClass(any public class in the MyPackage),they must use import statement to make the name or names available for using.

import MyPackage.MyClass;
class PackageTest{
public static void main(String args[])
MyClass mc=new MyClass();
Alternatively we need to give fully qualified name-

MyPackage.MyClass m=new MyPackage.MyClass();
The package and import statements allow us to divide up. This single global name space so that no name clashing will occur(No matter how many people get on the internet and start creating classes in java).
Common Guidelines:

  • .class file must be located in a directory that has the same name as the package,this directory should be a sub directory of the directory where classes will import package are located.
  • Exact location of the package should be mentioned in the package statement.One can specify the directory hierarchy like package MyProject.Test.GUITest;
  • The directory in which the package is stored should be under the directory where java application want   to share the package classes
  • Java <---------------------------------working directory
    .package MyProject.Test.GUI.class

    <---------------------------------package directory
  • The best approach is to setup the system variable in CLASSPATH.The specific location that java compiler will consider as the root of any package hierarchy. This is also controlled.
    SET CLASSPATH=java\classes;java\project\packages;
Popular Packages in java:

Package Comments
java.lang.* The java language package provides the classes and interfaces that form core of java language and JVM.
It provides support for classes,objects,String,thread exceptions and wrapper classes.
It got imported automatically into every java program.  
java.io.* This package provides a set of I/O streams used to read and write files to I/O sources.
They are byte oriented and the classes defined here can be chained to implement more sophisticated stream functionalities.
java.utility.* This package contains a collection of utility classes and related interfaces.It provides classes that provides generic data structure
(Dictionary,Hashtable,Stack,Vectors),String manipulation(String tokenizer),calander,date utilities.Interfaces like-observer
observable class which allow objects to notify one another when they change.
java.net.* This package contains networking classes and interfaces,including classes that represent a URL and URL connection.Socket
connection and a class that represents Internet address.
java.awt.* This package provides standard graphical user interface elements(Button,List,Menus etc) with  containers(Window,Frame,MenuBar).
It also provides higher level dialogs. It supports Abstract Window Toolkit.It also has two more sub classes.
java.awt.image This package contains classes and interfaces for performing sophisticated image producing.This is needed to create or manipulate
image and colors
java.awt.peer This package contains interfaces used to connect AWT components to their windows,Systems specific implementations.(Motif widget)
Unless we are creating a window specific or system specific implementation,we need not use this interface.
Package creation guidelines

  • Package is never gets packaged into a single file.
  • Package contains many .class files.
These two concepts may have destroyed concept as files may cluttered.To prevent this we place all the .class files for a particular package into a single directory.It is bit logical too.This follows the hierarchical file structure of the operating system.This way of packaging resolves the problem of class  clutter. By using packages,we can resolve the namespace and name collision. But if the package names are same,in that case it will tough to use them. To support this we need to write Internet friendly naming convention. But issue with this approach is that it may download the classes automatically without the knowledge of the user.
So still there are two issues:
  1. Creating unique package names
  2. Finding the classes(may be buried in the directory structure)
To resolve these issues,Java developers has provided the below solutions:

  • To encode the path of the creation of the .class file into the name of the package(The compiler will enforce this).But in addition,by connection with the first part of the package name is the internet domain name of the creator of this class in reversed order.Since Internet domain names are generally to be unique(like mydigitalvoice.in so the package will be in.mydigitalvoice,so say oracle.com the package will be com.oracle)If we follow this conversion,we will never face nameclash. What if we do not have our own domain name? Well in that case use surname,name etc to make it unique.
  • The second part of the trick is resolving the package name into a directory on our own machine. So when the java program is running,it needs to load the .class file.(May be dynamically,where it needs to create an object of that particular class),It can locate the directory where the .class files reside. 
How Java Interpreter works for packages
It finds the environment variable CLASSPATH(set via operating system where java CLASSPATH contains one or more directories that may be used as a root for a search for .class files.)Starting at the root,the interpreter will take the package name and replace each dot with a slash to generate a path name from CLASSPATH root. So package foo.abc.mno.xyz will become foo\abc\mno\xyz or foo/abc/mno/xyz depending on the operating system.This is then concatenated to the various entries in the CLASSPATH. That's where it looks for the .class file with the name corresponding to the class, we are trying to create.
An Example:

package IN.MydigitalVoice.util;
this package name can be used as an umbrella name space for the following two files:

package IN.MydigitalVoice.util;
public class Vector{
public Vector()
system.out.println("Vector from mydigitalvoice");
Now when we try to create our own package-

package IN.MydigitalVoice.util;
public class List{
public List(){
system.out.println("List from mydigitalvoice");
Since we have given first non comment code,both of these files are placed in the sub directory on our system like-

if the package name is In.MyDigitalVoice.Util but the first portion of the path comes from CLASSPATH environment variable,which is written

The CLASSPATH can contain other alternative search path also. The following code can be placed in any directory-

import IN.MyDigitalVoice.Util.*;
public class LibTest{
public static void main(String args[])
Vector v=new Vector();
List l=new List();
When compiler encounters the import statement, it begin searching at the directory specified by the CLASSPATH looking for a sub directory IN\MyDigitalVoice\Util.Then search the compiled files of the appropriate names(Vector.class and List.class for Vector and list respectively). Note both the classes are desired methods in the respective class must be public.
Package Concept Simplified In Java Package Concept Simplified In Java Reviewed by Animesh Chatterjee on November 08, 2018 Rating: 5
Powered by Blogger.