Results for java

All About Class Image in AWT in Java

December 10, 2018

The abstract class Image is the superclass of all classes that represent graphical images. The structure of the class is given as below:

public abstract class java.awt.Image extends java.lang.Object{
//member element:
public final static Object UndefinedProperty;
//The UndefinedProperty Object should be returned whenever a property which was defined for a particular
//image is fetched.
//constructor
public Image()//default constructor
//Methods:
public abstract void flush();
public abstract Graphics getGraphics();
public abstract int getHeight(ImageObserver observer);
public abstract Object getProperty(String name,ImageObserver observer);
public abstract ImageProducer getSource();
public abstract int getWidth(ImageObserver observer);
}
 
All About Class Image in AWT in Java All About Class Image in AWT in Java Reviewed by Animesh Chatterjee on December 10, 2018 Rating: 5

All About Class NotSerializableException in Java

December 10, 2018

An application that throws NotSerializableException indicates that the target object , that it tried to serialize,could not be serialized.This can happen to classes which does not implement Serializable interface. A class may implement Serializable interface but may refer or contain a non serializable object,in this case when we try to serialize the class,we will get NotSerializableException.

A subclass of a serializable class can prevent itself from being serialized by throwing this (NotSerializableException) exception from its writeObject() or readObject() methods.

It is a child class of ObjectSreamException.
The structure of the NotSerializableException class given as :

public class java.io.NotSerializableException extends java.io.ObjectStreamException{
//constructors:
public NotSerializableException();//default constructor
public NotSerializableException(String className);
}
 
All About Class NotSerializableException in Java All About Class NotSerializableException in Java Reviewed by Animesh Chatterjee on December 10, 2018 Rating: 5

All About Class NoRouteToHostException in Java

December 10, 2018

An application can throw this -NoRouteToHostException exception to indicate a socket could not be connected with remote host, as the host could not be connected due to one of the following reasons:

  • Host could not be connected before establishing socket
  • Some intermediate link/links between local machine to host is/are down.
  • Host may be behind a firewall.
This excaption-NoRouteToHostException is a subclass of SocketException.
The structure of NoRouteToHostException is given as:

public class java.net.NoRouteToHostException extends java.io.SocketException{
//constrcutors:
public NoRouteToHostException();//default constrcutor
public NoRouteToHostException(String message);
}
 
All About Class NoRouteToHostException in Java All About Class NoRouteToHostException in Java Reviewed by Animesh Chatterjee on December 10, 2018 Rating: 5

All About PopupMenuPeer in AWT in Java

December 09, 2018


The PopupMenuPeer Interface specifies the methods that all implementations of Abstract Window Toolkit must define while working with PopupMen
The hierarchy of calling this component is as follows:
[PopupMenuPeer(MenuPeer(MenuItemPeer(MenuComponentPeer)))]

The architecture of the interface PopupMenuPeer is given as :

public abstract interface java.awt.peer.PopupMenuPeer extends java.awt.peer.MenuPeer{
//methods:
public abstract void show(Event evt);

} 

 
All About PopupMenuPeer in AWT in Java All About PopupMenuPeer in AWT in Java Reviewed by Animesh Chatterjee on December 09, 2018 Rating: 5

Thread Priority Concept Simplified in Java

December 05, 2018


In my earlier post here I have shown details about a thread and how to create a thread. In this post we will see an important property of a thread called Priority.In java each thread is assigned a priority which effects the execution of the thread.By default threads will be created with normal priority and threads with having same priority are given equal time slot to execute. Mostly it is first come first serve basis.
Whenever multiple threads are ready for execution ,the java will choose the highest priority thread and will execute.For a lower priority thread to gain control ,one of the following condition should happen to a high priority thread:

  1. It stops running at the end of the run().
  2. It is made to sleep using sleep()
  3. It is made to wait using wait().
If another thread of a higher priority comes along the currently running thread will be preempted by the incoming thread along,forcing the current thread to move to runnable state.Higher priority threads will always preempts any lower priority thread.
How to set priority to a thread:

ThreadName.setPriority(int priorityNumber);
 
int priorityNumber is a constant ranging from 0 to 10. Most user level processes should be NORM_PRIORITY+/- 1
An example:

class A extends Thread{
    public void run(){
        System.out.println("Running Thread A");
        for(int i=0;i<10;i++){
          System.out.println("Running from Thread A "+i);   
        }
         System.out.println("Ending Thread A");
    }
}
class B extends Thread{
    public void run(){
        System.out.println("Running Thread B");
        for(int i=0;i<10;i++){
          System.out.println("Running from Thread B "+i);   
        }
         System.out.println("Ending Thread B");
    }
}
class C extends Thread{
    public void run(){
        System.out.println("Running Thread C");
        for(int i=0;i<10;i++){
          System.out.println("Running from Thread C "+i);   
        }
         System.out.println("Ending Thread C");
    }
}
public class ThreadPriorityTest{
    public  static void main(String args[])
    {
        A threadA=new A();
        B threadB=new B();
        C threadC=new C();
        threadC.setPriority(Thread.MAX_PRIORITY);
        threadB.setPriority(threadA.getPriority()+2);
        threadA.setPriority(Thread.MIN_PRIORITY);
        System.out.println("Start thraed A");
        threadA.start();
        System.out.println("Start thraed B");
        threadB.start();
        System.out.println("Start thraed C");
        threadC.start();
        System.out.println("Out of main thread");
    }
}
 
output of the code:
$javac ThreadPriorityTest.java
$java -Xmx128M -Xms16M ThreadPriorityTest
Start thraed A
Start thraed B
Running Thread A
Start thraed C
Running from Thread A 0
Running from Thread A 1
Running from Thread A 2
Running from Thread A 3
Running Thread B
Out of main thread
Running from Thread A 4
Running from Thread B 0
Running from Thread B 1
Running Thread C
Running from Thread A 5
Running from Thread C 0
Running from Thread B 2
Running from Thread B 3
Running from Thread B 4
Running from Thread B 5
Running from Thread B 6
Running from Thread B 7
Running from Thread B 8
Running from Thread B 9
Ending Thread B
Running from Thread C 1
Running from Thread C 2
Running from Thread C 3
Running from Thread C 4
Running from Thread C 5
Running from Thread C 6
Running from Thread C 7
Running from Thread C 8
Running from Thread C 9
Ending Thread C
Running from Thread A 6
Running from Thread A 7
Running from Thread A 8
Running from Thread A 9
Ending Thread A
Thread Priority Concept Simplified in Java Thread Priority Concept Simplified in Java Reviewed by Animesh Chatterjee on December 05, 2018 Rating: 5

All About Class TextComponent in AWT in Java

December 04, 2018


TextComponent is the super class of any component that allows the editing of some text.Read here for TextArea and read here for TextField.
The class structure of TextComponent class is given below:

public class java.awt.TextComponent extends java.awt.Component{
//methods
public String getSelectedText();
public int getSelectionEnd();
public int getSelectionStart();
public String getText();
public boolean isEditable();
protected String paramString();
public void removeNotify();
public void select(int selectionStart,int selectionEnd);
public void selectAll();
public void setEditable(boolean t);
public void setText(String str);
}
 
All About Class TextComponent in AWT in Java All About Class TextComponent in AWT in Java Reviewed by Animesh Chatterjee on December 04, 2018 Rating: 5

All About Choice Class in AWT in Java

December 04, 2018


The choice class presents a popup menu of choices.The current choice is displayed as the title of the menu.After any choice is made,AWT sends an action event to the choice menu.The event's target is the choice menu and it's object is the String label of the currently selected item. . The Choicebox is a single line window with a dropdown arrow revealing a dropdown Listbox.it has the same constructor and methods as the Listbox.The events for a choicebox are slightly different selecting an item from a Choicebox.It generates an action performed event,while clicking on an item in a List box,generates an itemStateChanged event.The choicebox is not a window style combo box where we can type in or select from the top line.But we could easily construct such a combo box from a textfield,a button and a hidden listbox.An application should override the action method of the choice menu or one of it's parent containers in order to cause some action to occur.
The class structure of Choice class is given as:


public class java.awt.Choice extends java.awt.Component{
//constructors:
public Choice();//Creates a new Choice menu.The menu initially has no item in it.By default
//the first item added the Choice menu becomes the selected item,until a different selection
//is made by the user or by calling one of the select methods.
//methods:
public void addItem(String item);
public void addNotify();
public int countItems();
public String getItem(int index);
public int getSelectedIndex();
public String getSelectedItem();
protected String paramString()
public void select(int pos);
public void select(String str);
}
 


An example:-


Choice os=new Choice();
os.addItem("A");
os.addItem("B");
os.addItem("C");
//method related to Applet
int width=Integer.parseInt(getParameter("width"));
int height=Integer.parseInt(getParameter("height"));
//method supported:
reshape(int x,int y,int x1,int y1);
getSelectedItem();//returns the String of the item itself.
getSelectedIndex();//returns the index of the item itself.
select(int pos);//selects the item by index position.
select(String name);//selects the item by name.
addItem(String item);//adds an item to the choice.
 
The items of a choice will be left justified.
All About Choice Class in AWT in Java All About Choice Class in AWT in Java Reviewed by Animesh Chatterjee on December 04, 2018 Rating: 5

How A Java Program Looks Like?

December 04, 2018


Class is the heart of java way of development.So when we talk about a structure of java code we will look how a class is structured.
Class contains data members and methods to operate on those data members of the class. Methods contain data type deceleration and executable statements.

A dot operator is used to access the variables and methods of the class.

Structure of a java program:


#Documentation section
#package section
#import statements
#Interface Statements
#class definition
#class member deceleration
#method declaration
#local variable deceleration
 
A java source code may contain multiple class definitions,multiple member variables, multiple methods,multiple local variables.
Documentation Section:
A set of comment lines that gives the name of the program,the author information and other details. refer this link for information.These are the details the programmers like to refer at a later stage.Comments must explain why and what of classes and how of algorithms.This improves the greater maintainability. The javadoc comment style (/**.....*/) is used for generating documentation automatically.It is optional though.
Package Statement:
The first valid statement of the program.This statement declares a package name and informs the compiler that the classes defined here belong to this package. However if our program does not refer to any other classes,it must be part of default package. This statement is not required then. It is also optional.refer this link for more details.
Import Statement:
After package statement next comes import statements. This statement instruct the interpreter to load the correct class/classes in the package specified.
Interface Statement:
An interface is like a class but includes a group of methods decelerations. This is important when we wish to implement multiple inheritance.However it is also optional.
keywords Statement:
Rest all in the java are 90% keywords. Java keywords have a specific meaning so we can not use them as names for variables,classes , methods,libraries or any other user defined forms.All keywords needs to be written in lower case form(lower case letters). Since java is case sensitive,one can use these words as identifiers by changing one or more letters to uppercase or lower case.However this should be avoided.
How A Java Program Looks Like? How A Java Program Looks Like? Reviewed by Animesh Chatterjee on December 04, 2018 Rating: 5

All About Class CheckboxMenuItem in AWT in Java

December 03, 2018


CheckboxMenuItem represents a checkbox that can be included in a menu.Clicking on the checkbox in th emenu changes its state from "ON" to "OFF" or "OFF" to "ON".When a CheckboxMenuItem is clicked, the AWT sends an action event to CheckboxMenuItem's containing frame. The event's target is the checkbox menu  items and its object is the String label of the checkbox.

The structure of the CheckboxMenuItem is given as:

public class java.awt.CheckboxMenuItem extends java.awt.MenuItem{
//constructor
public CheckboxMenuItem(String label);//creates a checkbox with the specified label
//The checkbox is initially set to "OFF".
//methods:
public void addNotify();
public void getState();
public String paramString();
public void setState(boolean t);
}
 
All About Class CheckboxMenuItem in AWT in Java All About Class CheckboxMenuItem in AWT in Java Reviewed by Animesh Chatterjee on December 03, 2018 Rating: 5

All About Class CheckboxGroup in AWT in Java

December 03, 2018


CheckboxGroup groups a set of check buttons.Exactly one checkbox button in a CheckboxGroup can be in the "ON" state at any given point of time.Pushing any button turns it in and forces any other button that is "ON" to become "OFF".When a checkbox in a checkbox group is clicked,AWT sends an action event to that checkbox.This event's target is the checkbox and its object is a value equal to Boolean.TRUE.No action event is sent to the checkbox(if any) that is turned off.An application should override the action method of the checkbox or one of its parent containers in order to cause some action to occur.
The class structure of the CheckboxGroup is given as:

public class java.awt.CheckboxGroup extends java.lang.Object{
//constructors
public CheckboxGroup();// default constructor,creates a new CheckboxGroup.
//methods:
public Checkbox getContext();
public void setContent(Checkbox box);
public String toString();
}
 
All About Class CheckboxGroup in AWT in Java All About Class CheckboxGroup in AWT in Java Reviewed by Animesh Chatterjee on December 03, 2018 Rating: 5

How Inter Thread Communication Happens In Java?

November 28, 2018


Before you start reading  this post please read this post for thread creation concept,read this post for actual thread class and read this life cycle of a thread. These links will give you a better idea how a thread works. Coming back to the topic,Inter thread communication happens in three ways.

  • Through common shared data
  • Using thread control methods
  • Through inter process communication
Through common shared data
All the threads in the same program share the same memory space.If an object is accessible to various thread then these threads share access to that object's data members and thus communicate with each other.

Using thread control methods
There are three ways by which threads communicate to each other by this technique.
They are as follows:

  1. suspend();--> A thread can suspend itself and waits for another thread to resume it.
  2. resume();-->A thread can wake another thread (waiting state) through resume method. Then they can run concurrently.
  3. join()-->This method is used for caller thread to wait for completion of the called thread.
Through inter process communication
There are three methods available for inter process communication in this technique. They are as follows:

  1. wait();-->This method tells the caller thread to give up the monitor and make the calling thread wait until either a time out occurs or another thread calls the same thread's notify() or notifyAll() method.
  2. notify();-->This method wakes up the only one(first) waiting thread called wait() or the same object
  3. notifyAll();-->This method will wake up all the threads that have been called by wait() on the same object.
These three methods are defined in class -Object under java.lang package.These three methods provide an elegant interprocess communication mechanism to take care of a deadlock situation in java. A deadlock may occur when a thread holding the key of the monitor is suspended or is kept waiting for another thread's completion. If the other thread is waiting or needs to get into same monitor,both threads will be waiting for ever.
How Inter Thread Communication Happens In Java? How Inter Thread Communication Happens In Java? Reviewed by Animesh Chatterjee on November 28, 2018 Rating: 5

Annotation Concept Simplified in Java

November 27, 2018


Annotation is known as metadata for a code. We can use this feature to merge additional java elements with programming code like in classes,methods,parameters,local variables,packages,fields etc. Annotations viz metadata are stored in java class file(source file)by the compiler.These class files are used by the JVM or by the program to find out the metadata for interacting with the code elements.Java.lang.annotation package contains all annotation classes.The classes that implement Annotation element interface are:

  • java.lang.reflect.accesibleObject
  • java.lang. class
  • java.lang.reflect.Constructor
  • java.lang.reflect.field
  • java.lang.package
  • java.lang.reflect.method
Standard Annotation:

Annotation Comments
@Depreciated Compiler warns when deprecated java elements are used in non deprecated program or context.
@Overrides Compiler generated error when the method uses this annotation type does not override the methods present in the super class
@Documented Indicates annotation of this type to be documented by javadoc
@Inherited Indicates that this type is automatically inherited
@Retention Indicates the extended period using annotation type.
@Target Indicates to which program element the annotation is applicable

The annotation declaration is similar to interface declaration. we need to use @<annotation name> or keyword and we need to use @before keyword interface.


package myPackage.annotation;
import java.lang.annotation*;
@Retention(Retentionpolicy.RUNTIME);
@Target(ElementType.METHOD)
public @interface MyTest{
    Integer calculate();
}
 
//Meta annotations which declares that the @MyTest annotations must be stored in a class file.
@Target meta annotation is used to declare the @MyTest annotation which annotates the methods in the java class file.
@interface meta annotation is used to declare the @MyTest annotation with the member called calculate which returns Integer as an object.

Generic Guideline to Create Annotation:

  • Do not use extends clause.It automatically extends the market interface java.lang.annotation.Annotation.
  • Do not use any parameter for method
  • Do not use generic methods
  • Do not use throws clause
Annotations are majorly used to test the class,method,variable etc.

import junit.annotation.*;
public class TestMyMethods{
    @UnitTest(value="Test positive")
    public void positiveTest(int no)
  {
        assert no>0;
   }
@UnitTest(value="Test negative")
    public void negativeTest(int no)
 {
        assert no<0
 }
We can merge annotation with code elements.We can also use the methods available in the marker interface,java.lang.reflect.Annotated element query about the existence of programming element and get their values.
The methods of the Annotated Element interface are:

  1. IsAnnotationPresent();
  2. getAnnotations();
  3. getAnnotation();
  4. getDectaredAnnotations()
Use of Annotation in real code:


import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MySingle{
int value();
}
public class Single{
//annotate a method using a marker
@MySingle(100)
public static void myMethod(){
Single ob=new Single();
try{
Method m=ob.getClass().getMethod("myMethod");
MySingle assno=m.getAnnotation(MySingle.class);
System.out.println("The value is"+assno.value());//displays 100
}
catch(NoSuchMethodException e)
{
System.out.println("Metod not found");
}
}
public static void main(String args[])
{
MyMethod();
}
}

 

Annotation Concept Simplified in Java Annotation Concept Simplified in Java Reviewed by Animesh Chatterjee on November 27, 2018 Rating: 5

All About Class URLEncoder in Java

November 26, 2018


URLEncoder class defines a single static method which is used to convert a String to its URL-encoded form. The space is converted to + and non alphanumeric characters other than underscore are output as two hexadecimal digits following a percentage sign(%).This technique only works for 8-bit characters.This method is used to determine canonical value of an URL specification so that the users uses only characters from an externally portable subset of ASCII which can be correctly handled by computers around teh globe.

The structure of the class is given as :

public class java.net.URLEncoder extends java.lang.Object{
//methods:
public static String encode(String s);
}
 
All About Class URLEncoder in Java All About Class URLEncoder in Java Reviewed by Animesh Chatterjee on November 26, 2018 Rating: 5

What Is Public Static Void Main Method in Java?

November 25, 2018


For stand one java program,the class name should be same as file name. we will get a compilation error if otherwise.The class should contain a main() method with the given signature:

public static void main(String[] args){}
 
Conceptually every java program must include a main() method to run independently.main() is the starting point or triggering point for interpreter to begin execution.A java program can have n-numbers of classes but only one of them include  a main() method to initiate the execution.

public-> is available for the world to use. check this link for more.
String[] args->It declares a parameter name args of type String array.The argument to the main is an array of String objects.In IDE mode of development,they will never be used in general,but they hold the arguments invoked on the command line.
Static:Static keyword declares this method /variable as one that belongs to the entire class and not part of any objects of the class. The main() method must always be declared as static since the interpreter uses this method before any objects are created.
void-->this modifier declares that main() method does not return any value. 
What Is Public Static Void Main Method in Java? What Is Public Static Void Main Method in Java? Reviewed by Animesh Chatterjee on November 25, 2018 Rating: 5

All About Class Polygon In AWT in Java

November 21, 2018

A Polygon consists of a list of x and y coordinates where each successive parts of co-ordinates defines a side of a Polygon.
The class structure of the Polygon is defined as below:

public class java.awt.Polygon extends java.lang.Object{
//member elements
public int npoints//total number of points
public int xpoints[]//the array of x coordinates
public int ypoints[]//the array of y coordinates
//constructors
public Polygon();// creates an empty Polygon 
public Polygon(int xpoints[],int ypoints[],int npoints);// creates and initializes a Polygon 
//from the specified parameters
//methods:
public void addPoint(int x,int y);//appends a point to this Polygon.If an operation that calculates the bounding
//box of this Polygon(getBoundingBox() or inside()) has already been performed ,this method updates the bounding box.
public Rectangle getBoundingBox();//returns the smallest rectangle that contains this Polygon.
public boolean inside(int x,int y);//Determines if the specified point is inside this Polygon.This method
//uses an even odd insideness rule also known as alternating rule to determine whether point (x,y) is inside this 
//Polygon.Returns true if the point (x,y) is inside this Polygon ,false otherwise.
}
 
All About Class Polygon In AWT in Java All About Class Polygon In AWT in Java Reviewed by Animesh Chatterjee on November 21, 2018 Rating: 5

All About Class TextArea in AWT in Java

November 20, 2018


TextArea class is used when large amount of text data is needed to be input/displayed.A TextArea is a multi line area for displaying text.It can be set to allow editing or to be read only.It is derived from TextComponent hence it can receive text Value changed events as well as keyPress and FocusEvents.
The structure of TextArea class is given as:

public class java.awt.TextArea extends java.awt.TextComponent{
//constructors
public TextArea();//default constructor constructs a new TextArea
public TextArea(int rows,int columns);//constructs a new TextArea with the specified number of rows and columns
public TextArea(String initialText);//constructs a new TextArea with the specified text dicplayed
public TextArea(String initialText,int rows,int columns);//constructs a new TextArea with the specified text and 
// the specified rows and columns.
//methods
public void addNotify();
public void appendText();
public String getText();//returns the current text in the box.
public void setTest(String text);//sets text to the text area.
public void insertText(String str,int pos);
public void replaceText(String str,int start,int end);
public int getColumns();
public int getRows();
protected String paramString();
public Dimension minimumSize();
public Dimension minimumSize(int rows,int cols);
public Dimension preferredSize();
public Dimension preferredSize(int rows,int cols);
public void setEditable(boolean option);
public String select(start,end);//select text characters between specified start and end characters
}
 
Example:

TextArea ta1=new TextArea("Input text here",20,30);
 

All About Class TextArea in AWT in Java All About Class TextArea in AWT in Java Reviewed by Animesh Chatterjee on November 20, 2018 Rating: 5

All About Class TextField in AWT in Java

November 20, 2018


TextField is a single line text input box.So it is a component that presents user with a single editable line of text.The constructors of this class allow us to create textfileds of a specific character width with default values.The text is editable using keys and mouse selections.This class can be used to accept text to echo it or hide it the echo(like password).It is derived from TextComponent hence it can receive text Value changed events as well as keyPress and FocusEvents.
The class structure of TextField is given as:


public class java.awt.TextField extends java.awt.TextComponent{
//constructors
public TextFiled();//default constructor,creates an empty TextFiled.
public TextFiled(int numberOfCharacters); //constructs a new textfield with the specified number of character wide.
public TextFiled(String initialText);//constructs a new textfield initialized with specified text
public TextFiled(String initialText,int numberOfCharacters);//constructs a new textfield initialized with 
//specified text wide enough to hold the specified number of characters.
//methods
public void setEchoCharacter(char c);//mostly used in password field.
public void addNotify();
public boolean echoCharIsSet();
public String getText();//returns the current text in the box.
public void setTest(String text);//sets text to the text field.
public int getColumns();
public char getEchoChar();
protected String paramString();
public Dimension minimumSize();
public Dimension minimumSize(int cols);
public Dimension preferredSize();
public Dimension preferredSize(int cols);
public void setEditable(boolean option);//determines if the field is editable or not
public String select(start,end);//select text characters between specified start and end characters
}
 
Example:

TextField txt1=new TextFiled();
TextField txt1=new TextFiled(20);
TextField txt1=new TextFiled("Enter your Name");
TextField txt1=new TextFiled("Enter your Name",20);
 
All About Class TextField in AWT in Java All About Class TextField  in AWT in Java Reviewed by Animesh Chatterjee on November 20, 2018 Rating: 5

Java Documentation-JavaDoc Concept Simplified in Java

November 19, 2018


To use API effectively,we need good documentations.  In java it is always not about writing the code but also about the documentation of our code so that the users of the code can understand in details without going through the code. Static documentation faces challenges of maintenance. If we change the code in,general we have to update the documentation. If documentation and code are different , it becomes an overhead to maintain it, whenever code changes.The best solution is to put everything in the same file but that needs some syntax to mark special documentation and a tool to extract those comment and put them in a useful form.

In java, the tool that extract comments is called javadoc. The documentation for most java APIs are prepared using javadoc. It extracts the comments,class,method names etc from the source file itself.The output of the javadoc is a HTML file which can be seen in a web browser. This tool allows us to create and maintain single source file and generates the documentation automatically.So javadoc is a tool that reads source code file, extracts javadoc comments and create a set of webpages containing comments in a nicely formatted and interlinked form.Javadoc takes the syntactic information to add semantics and pragmatics.

By default javadoc will only collect information about public classes,public subroutines and public members variables,but it also allows option to create documentation for non public things as well.
If javadoc does not find any javadoc comments for a source file,it will create one with very basic information  like- name,type of member variables,return types,parameter lists of the method etc.

Syntax of javadoc
javadoc comments are placed just before the sunroutine for which we are commenting on.All the javadoc commands starts with /** and ends with */. There are two ways to create javadoc. They are as follows:

  • Use doc tags 
  • Embedded HTML
Doctags:

Doctags are passed to javadoc tool.Doctags are commands that starts with a '@' and are placed at the beginning of the comment line.A leading star(*) is ignored or *s at the beginning of lines are optional .The Javadoc tool will remove them. This rule is always followed.Like any other comment javadoc comments are ignored by the compiler when it is compiled.Doc comments should immediately precede the deceleration of the class,field or method that are associated with it.The first sentence of a doc comment should be a summary sentence ,suitable for display. The next few line of sentences may document the feature in details.The text that follows a tag may span multi lines and contimue until the next javadoc tag or javadoc end tag is encountered.

Doctag commands are like
@param =>description of the parameters
@return =>description of the return values
@throws =>descriptions of the exceptions
Descriptions can be off several lines. The description ends at the next tag or at the end of comment.

Comments are special section of the text inside a program.It's purpose is to help people understand the program.A comment is part of a good programming documentation.

Javadoc supports multiple comment styles:
  • // single line comment-End line comment
  • /**  ....*/ multiple line  comments -javadoc comments
  • /*......*/ old style multi line comments-traditional comment 
No text inside the comment gets handled by the compiler.There are three types of comment documentation which corresponds to the element that comment precedes.They are as follows:

  • Class
  • Variable 
  • Method

Class comment:
A class comment appears right before the definition of a class.

/** A class comment*/
public class Aclass{}
 
Variable comment:
A variable comment appears right in front of the definition of a variable.

/** A variable comment*/
public int sizeOfString;
 
Method comment:
A method comment appears right in front of the definition of the method.

/** A method comment*/
public int getValue(){}
 
Javadoc processes comment documentation for public and protected members only. Comments of private and friendly members are ignored. They produce no output.All class comments are included in the output.
@see:refer to other classes/method/variables:
All three of the comment documentation can contain @see tags which allows us to refer to the documentation in other classes. javadoc will generate HTML having a @see tags hyperlinked to  other documentation.@see -creates a  hyperlink to the specified class,It may be used before classes,methods or fields,


@see classname
@see fully_qualified_clasname
@see filly_qualified_classname#methodname
 
Each one adds a hyperlinked "see also" entry to the generated documentation. javadoc will not check the validation of the hyperlinks.
class documentation tags:
Class documentation may also contain the below tags along with @see tag. @see -creates a  hyperlink to the specified class,It may be used before classes,methods or fields

@see classname
@version-version information(when version information is placed on the javadoc command line,the version 
information will be called out specially in the generated HTML).It is mostly applicable for class definition.
javadoc ignores this tag until -version command line argument is specified.
@author-This tag adds an "Author:" entry in the documentation.author information like name,email id etc will be 
placed on the javadoc command line,the author information will be called out specially in the generated HTML).
If we have multiple authors ,they must be placed consecutively.They will be placed in a single paragraph.This 
entry is ignored by javadoc until -author command line argument specified.
 
Variable documentation tags:
This can only include embedded HTML and @see reference.@see -creates a  hyperlink to the specified class,It may be used before classes,methods or fields
Method documentation tags:
Along with @see tag , the below written are also supported:@see -creates a  hyperlink to the specified class,It may be used before classes,methods or fields

@param- This tags adds an entry as "Parameter:" in the documentation.it says the parameter name description 
where parameter name is the identifier in the parameter list and the description is considered finished
when a new documentation tag is encountered.We can have any number of these,presumably one for each parameter.
it may roll over to multiple lines.
@return- This tag adds a "Returns:" section is the documentationHere the description talks about the meaning of 
these values.It can continue on subsequent lines.
@exception-This tag adds a "Throws:" section in the documentation.Fully qualified class name description which 
gives us an unambiguous name of the exception class that is defined somewhere and description tells us why 
this particular type of exception can emerge from the method call.It can continue on subsequent lines.This 
should signify the exception.Mostly used in method context.
@deprecated-This tag adds a "Deprecated:" section-in the documentation.It is used to tag features which 
have been suspended by an improved feature.The deprecated tag is a suggestion that the feature is no longer
 used or the feature is likely to be removed in future.
 
@param tag for every parameter of the method and @throws for many types of exceptions can be included if we want to include all of them in the document.
@return for every non void method/function.We can have only one.
@since version- This is an undocumented tag used to specify when the class method or field that follows.It should followed by a version number.
The tags may not follow a particular order but it is always good to have a sequence followed as a style approved by the designer.

Embedded HTML
In addition to the normal text,the javadoc comment may contain special codes(HTML markup commands).javadoc passes HTML commands through to the generated HTML document. This will allow us to format the code and attach them to webpage.

/**
*<pre>
*System.out.println("Hello Java");
*</pre>
*/
We can use HTML just as we do for other HTML web documents. javadoc removes the star or asterisk(*) at the beginning of a line and the white spaces.It re formats everything.It is advisable not to use <hi> or <hr> as embedded since javadoc inserts its own heading.
All types of comment documentation :class,variable,method can support embedded HTML.

/**
* even we can use <em>hello</em> a list
*<ol>
*<li>one</li>
*<li>two</li>
*<li>three</li>
*</ol>
*/

Coding guidelines:
Unofficially all class names should start with Capital letters,everything else methods,variables object handles should start with small letter.
Only constants will contain all capital letters.
An Example

//:Myclass.java (it acts as a marker for comment line containing the source file name
import java.util.*;
/* the first example of java doc
*  @author-Animesh Chatterjee
*  @author-mydigitalvoice.in
*  @version 1.0
*/
public class MyClass{
/** the sole entry point to this class and application 
* @param args Array of String argument
* @return no return value
* @exception no exception is thrown
*/
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
///:~ indicating the end of the source code
 
commands
javac MyClass.java
javadoc MyClass.java-author -version[flags]

Javadoc comments are good practice even if we are not generating the javadoc.It is always good to have proper documentation. The best part of javadoc are as follows:

  1. The only person who has to look at the piece of java code is the programmer who writes the code. Other people who use the code can find out what the code does by viewing the automatically generated webpage.
  2. Because other people don't look at the java code,other people don't make changes to the java code.So they don't introduce errors into existing code.Errors may be accidental.
  3. Because the client of the code don't look at the java code,they don't have to decipher the inner working of the java code.All what the client needs to know about the code is what they read in the code's webpage.
  4. The programmer does not create two different things here(coding and documentation). Instead the coder create one piece of java code and attach the documentation inside the code in the form of javadoc comments.
  5. The generation of webpages from javadoc comments is done automatically.So everyone's documentation has the same format.  

Java Documentation-JavaDoc Concept Simplified in Java Java Documentation-JavaDoc Concept Simplified in Java Reviewed by Animesh Chatterjee on November 19, 2018 Rating: 5

Event Handling Concept Simplified in AWT in Java

November 19, 2018


The components we create in general like button,radio,frame etc do not do anything on their own with respect to user input .To make a valid GUI ,we need to provide controls to these components. Providing controls to a component is done via GUI programming or Event Driven programming. Below are the events:

  • Windows Events-Destroying, exposing,iconifying,deconifying and moving windows.
  • Mouse Events-Moving the mouse,dragging a mouse,enter and exit from components,engage and release button of a mouse.
  • Keyboard Events-pressing a key and releasing a key.
  • List Events-Selecting and deselecting a list item.
  • Scrolling Events:-Scrolling a line up or down. page up or down or scrolling to an exact location.
For each type of component object in AWT, there is a handleEvent() method.When a device activity occurs that generates an event,the event is first sent to the component which in turn calls the event handler of the component class. The event handler there after returns a boolean value as either false or true depending on the event handling routine. if it returns false,the event is passed on the component's parent(container).If the method returns true,it means the component acted on the event and more processing of the event takes place.

Various handling methods available with Event class and their practical usage.Event handler uses number of information regarding the activity that took place.These information variables are designed in Event class.When an event occurs, the corresponding event object is instructed and these variables are initialized.

The variables includes:

Object target;//the component that originally received the event.
long when;//the time stamp of when the event occured.
int id;//the type of the event
int x;//the x coordinate of the event.
int y;//the y coordinate of the event. 
int key;//the key that was passed in a keyboard event.
int modifier;//the state of the modifier key(Shift,control,alt)
int clickCount;//the number of consecutive clicks.
Object arg;//an event dependent argument that helps to identify the event causing GUI events.(Label of a button)
 
Different event types possible are listed below:

Event types Details Comments
Windows Events WINDOWS_ICONIFY
WINDOWS_DEICONIFY
WINDOWS_MOVED
WINDOWS_DESTROY
WINDOWS_EXPOSE
These events occurs when the corresponding activity is performed on a window object.
Mouse Events MOUSE_ENTER
MOUSE_EXIT
MOUSE_MOVE
MOUSE_DRAG
MOUSE_UP
MOUSE_DOWN
These are generated by mouse actions within the borders of canvas,Frame and Panel components
Focus Events GOT_FOCUS
LOST_FOCUS
Generated as the mouse enters or exits the borders of canvas,Frame and Panel components.They
are also generated as we click a mouse in a Text,TextArea,List,Combo etc components.
Keyboard Events KEY_PRESSED
KEY_RELEASED
KEY_ACTION
KEY_ACTION_RELEASE
Generated by pressing or releasing keys on the keyboard when we are on the borders of canvas,Frame
and Panel components or inside a Text,TextArea,List,Combo etc components.
Action Events ACTION_EVENT Generated when we click on a Button,choice or checkbox component,press enter in a TextFiled or double
click on a list item.
Scrollbar Event SRCOLL_LINE_UP
SRCOLL_LINE_DOWN
SRCOLL_PAGE_UP
SRCOLL_PAGE_DOWN
SRCOLL_ABSOLUTE
Generated by actions involving the scrollbar in scrollbar component.
The id variable in the Event class will be initiated by the corresponding event type during the automatic instantiation of the respective Event object. There are numbers of event handling methods declared in component class and Event class. The method handleEvent(Event evt) in component class is the central event dispatcher for a component.This method for a given event type(evt.id) calls the corresponding method.

evt.id handleEvent.class
Event MOUSE_DOWN mouseDown(Event e,int x,int y)
Event MOUSE_UP mouseUp(Event e,int x,int y)
Event MOUSE_DRAG mouseDrag(Event e,int x,int y)
Event MOUSE_ENTER mouseEnter(Event e,int x,int y)
Event MOUSE_EXIT mouseExit(Event e,int x,int y)
Event KEY_PRESS keyDown(Event e,int key)
Event KEY_ACTION keyDown(Event e,int key)
Event KEY_RELEASE keyUp(Event e,int key)
Event KEY_ACTION_RELEASE keyUp(Event e,int key)
Event LOST_FOCUS lostFocus(Event e,Object o)
Event GOT_FOCUS getFocus(Event e,Object o)
Event ACTION_EVENT action(Event e,Object o)
List and Scrollbar components do not have their helper functions.To handle these, it is required to override the handleEvent() method.
Event Handling Concept Simplified in AWT in Java Event Handling Concept Simplified in AWT in Java Reviewed by Animesh Chatterjee on November 19, 2018 Rating: 5

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{
//Methods
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
Powered by Blogger.