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

Polymorphism Concept Simplified in Java

November 27, 2018


Java allows polymorphism in term of methods.Polymorphism means one definition and many different behaviors.It is polymorphism's ability to take more than one form.An operation may exhibits different behaviors in different instance.The behaviors depends upon the types of data used in the operations. Encapsulation creates new data types by data and methods.Implementation hiding separates the interface from the implementation by making details private. Polymorphism deals with decoupling in terms of types. Inheritance allows the treatment of an object as its own type or its base type.This feature allows many types which are derived from main base class to be treated as if they were one type and a single piece of code to work on those different child classes equally. The polymorphic method call allows one type to express its distinction from another.similar type,as long as they are derived from the same base class(type).This difference is expresses through differences in behavior of the methods , we call through base class.In other word Polymorphism is a dynamic binding.  
an example:

class MyClass{
    public int x,y; 
    MyClass(int x,int y)
    {
        this.x=x;
        this.y=y;
    }
    float difference(int x,int y)
    {
        int dx=this.x-x;
        int dy=this.y-y;
        return (float)Math.sqrt(dx*dx+dy*dy);
    }
    float difference(MyClass mc)
    {
        return difference(mc.x,mc.y);
    }
}
class MyAnotherClass extends MyClass{
    int z;
    MyAnotherClass(int x,int y,int z)
    {
        super(x,y);
        this.z=z;
    }
    float difference(int x,int y,int z)
    {
        int dx=this.x-x;
        int dy=this.y-y;
        int dz=this.z-z;
        return (float)Math.sqrt(dx*dx+dy*dy+dz*dz);
    }
    float difference(MyAnotherClass mac)
    {
        return difference(mac.x,mac.y,mac.z);
    }
}
public class TestPoly{
    public static void main(String args[])
    {
        MyClass mc1=new MyClass(2,3);
        MyAnotherClass mac1=new MyAnotherClass(3,4,5);
        MyClass mc2=new MyClass(5,6);
        MyAnotherClass mac2=new MyAnotherClass(7,8,9);
        float d0=mc1.difference(0,0);
        float d1=mc1.difference(mc2);
        System.out.println("Difference between them"+d0);
        System.out.println("Difference between them"+d1);
        d0=mac1.difference(0,0,0);
        d1=mac2.difference(mac1);
        System.out.println("Difference between them"+d0);
        System.out.println("Difference between them"+d1);
        }
}
 
output of the code:
$javac TestPoly.java
$java -Xmx128M -Xms16M TestPoly
Difference between them3.6055512
Difference between them4.2426405
Difference between them7.071068
Difference between them6.928203
How method call Binding happens?
Polymorphism plays an important role in allowing objects having different internal structres to share the same external interface.A generic class of operations may be accessed in the same manner even though specific action associated with each operation may differ.

Connecting a method call to a method body is called binding.When binding is performed before the programming is run by compiler and linker, it is called early binding.But the issue with early binding is that compiler can not know the correct method call when it has an object handle.To resolve this we have to come up with late binding that is the binding occurs at runtime based on the type of the object. Late binding is also called dynamic binding or runtime binding.This is to help compiler/JRE to understand the type information that needs to be installed in the object itself.All method binding in java are late binding until it is a final. This means that we don't have to make any decision about whether late binding will occur. JRE does that automatically.This is one of the main reason why final methods exists as it prevents anyone to override the method. So by final , it turns off the dynamic binding that is it tells compiler that dynamic binding is not necessary.A method call associated with a polymorphic reference depends on the dynamic type of that reference.
How the right method call happens?
As all binding of methods in java happen polymorphically via late- binding,we can always write our code to talk to the base class and know that all the derived class will work correctly using the same code.In this way,if we send a message to an object and let the object figure out the right thing to do.

Shape
---------
draw()
erase()
---------
        |
       v
----------
        |
      v
----------
       |
       v
Circle
---------
draw()
erase()
Square
---------
draw()
erase()
Line
---------
draw()
erase()
Handles of each object needs to caste up the inheritance diagram. The upcasting could occur in the following manner-

Shape sCircle=new Circle();
Shape sSquare=new Square();
Shape sLine=new Line();
 
Here the Circle object is created and resulting handle immediately assigned to a Shape.This looks error (assigning one type to other).But this is fine as Circle is a Shape by inheritance.So the compiler agrees with the statement and does not give any compilation error.So when we call one of the base class methods(which may been overridden in the derived classes)like-

sCircle.draw();
 
It is expected that the Shape's draw(base class method) method is called as it is a Shape handle.The compiler won't know anything else,but still Circle's draw() method is called due to late binding(Polymorphism).
Polymorphism Concept Simplified in Java Polymorphism 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
Powered by Blogger.