Results for java

All About Methods with Varagrs in Java

December 15, 2018


In this post, I have discussed regarding methods in Java. Varargs represents variable length arguments in method. This makes java simple yet very powerful. 
The general syntax is given as:

<access specifier><return type>methodName(<argument type>... arguments)
 
This method contains an argument referred as varargs in which we are going to pass the specific type of arguments.
An ellipsis(...) is the key to varargs and argument is the name of the variable.

public void registration(String userName,String password,String emailId);
//can be written as:
public void registration(String... registrationDetails)
 
String... registrationDetails specifies that we can pass any number of String arguments to the registration() method.
How to retrieve the values:

class Registration{
testVarargs(String... registrationDetails)
{
for(String details:registrationDetails)
{
System.out.println(details);
}
} 
public static void main(String args[])
{
testVarargs("MydigitalVoice","abc123","hello@mydigitalvoice.in");
}
}
 
At compile time the String... registrationDetails is converted to String[] varargs. we can pass any array of Strings to the methods.Varargs does not generate any compile time errors even if an empty argument is passed as a parameter to the method
All About Methods with Varagrs in Java All About Methods with Varagrs in Java Reviewed by Animesh Chatterjee on December 15, 2018 Rating: 5

Wrapper Class Concept Simplified in Java

December 13, 2018


Traditional containers like vector can not handle primitive data types like int,float,long,char and double.Primitive data types can be converted to objects using the wrapper classes.Wrapper classes are contained in the java.lang package.

Simple type Wrapper class
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
Wrapper classes have number of unique methods for handling primitive data types and objects.
Converting primitive numbers to object:

Constructor calling conversion action
Interger intval=new Integer(i); primitive integer i to Integer Object
Float floatval=new Float(f); primitive float f to Float Object
Double doubleval=new Double(d); primitive double d to Double Object
Long longval=new Long(l) primitive long l to Long Object
i,f,d,l are primitive data values denoting int,float,double,long data type. They may be constant or any variable.
Converting object numbers to primitive numbers using typeValue() method:

Method Action
int i=intVal.intValue() Object to primitive integer
float f=floatVal.floatValue() Object to primitive float
long l=longVal.longValue() Object to primitive long
double d=doubleVal.doubleValue() Object to primitive double
Converting numbers to String using toString() method:

Method Action
String str=Integer.toString(i); primitive integer to String
String str=Float.toString(f); primitive float to String
String str=Double.toString(d); primitive double to String
String str=Long.toString(l) primitive long to String

Converting String objects to Numeric objects using static valueOf() method:

Method Action
intVal=Integer.valueOf(str); String to integer object
longval=Long.valueOf(str); String to long object
floatVal=Float.valueOf(Str); String to float object
doubleVal=Double.valueOf(str) String to double object
Converting Numeric Strings to primitive Numbers:

Method Action
int intVal=Integer.parseInt(str) String to primitive integer
long longval=Long.parseLong(str); String to primitive long
float floatVal=Float.parseFloat(str) String to primitive float
double doubleVal=Double.parseDouble(str) String to primitive double
All these methods may throw the NumberFormatException if the value of the String(str) does not represent proper number.
An Example:

public class InterestCalculate{

     public static void main(String []args){
         //converting Number to object
         Float principalAmount=new Float(0);
         Float interestRate=new Float(0);
         int numYears=0;
         try{
             DataInputStream in=new DataInputStream(System.in);
             System.out.println("Enter Principal Amount:");
             System.out.flush();
             String principalString=in.readLine();
             //converting string to float object
             principalAmount=Float.valueOf(principalString);
             System.out.println("Enter rate of interest :");
             System.out.flush();
             String interestString=in.readLine();
             //converting string to float object
             interestRate=Float.valueOf(interestString);
             
             System.out.println("Enter number of years :");
             System.out.flush();
             String yearString=in.readLine();
             //converting string to int
             numYears=Integer.parseInt(yearString);
             }
             catch(IOException e)
             {
                System.out.println("I/O Error has occured");
             }
             catch(NumberFormatException e)
             {
                System.out.println("Number format is not correct");
             }
             float value=total(principalAmount,interestRate,numYears);
             System.out.println();
             System.out.println("The final amount you will get"+value);
     }
     static float total(float p,float r,int n)
     {
         int year=1;
         float sum=p;
         while(year<=n)
         {
             sum=sum(1+r);
             year=year+1;
         }
         return sum;
     }
}
 
Wrapper Class Concept Simplified in Java Wrapper Class Concept Simplified in Java Reviewed by Animesh Chatterjee on December 13, 2018 Rating: 5

DataTypes Concept Simplified in Java

December 11, 2018



To create an object with new for a small simple variable is not efficient.As new operator places objects on the heap. For these types java,instead of creating the variable using new,an automatic variable is created which is not a handle.The variable holds the value itself. Variables are created on the stack instead of heap. Datatypes in java is divided into two major parts. Namely Primitive/intrinsic datatype and Non primitive/derived/reference type.Primitive datatype is divided into Numeric,non numerical datatype. Numerical data type is divided into Integral and floating point. Integral is further divided to Byte,Short,int,long. On the other hand floating point is divided into float and double. Non numerical type is divided into characters and boolean.

Non Primitive or derived or reference type is divided into classes,arrays,String and interfaces.

Integer Type:
Integer can hold whole numbers(exp-14,1234) etc.The size of the value depends on the type of the integer we choose. Storage also gets allocated accordingly.Wider data types requires more time for manipulation hence,we should use smaller data types whenever possible.This will improve the speed of execution(Example-instead of using int to store 10,we can use byte or Short).
we can also make integers long by appending the letter L or l at the end of the number.(Example- 124L or 567l).Java int types may not be used as boolean types and always signed.

Floating point Type: Floating point can hold containing fractional parts of a number.(Example-12.34,56.789 etc). Floating point types is divided into two parts:
  1. float-float type values are single precision numbers.
  2. double-double type values are double precision numbers.

default Floating point numbers are double precision numbers.We need to force them to single precision numbers by appending a f or F to the number. like-
1.23f or 456.789e2F



Double type:
Double precision types are used when we need greater precision in storage of floating point numbers. All mathematical functions-Sin,cos,sqart,etc return double type values.Floating point datatypes support a special values known as Not a Number(NaN).NaN represents the result of operation such as diving by zero,where an actual number is not produced.

Character type: To store character constant java supports character data type called char.

Primitive Datatypes in Java:

DataType Language Elements Wrapper Class Size Range Comments
Logical boolean Boolean 8 bits value true or false
Text Char Character 16 bits

Unicode-0 to Unicode-2 to the power 16-1 ASCII Characters use 16 bits

Literal value enclosed between ''
like 'a'
Integral byte Byte 1 byte
8 bits
To declare variables to store binary form of data
Integral short Short 2 bytes
16 bits
Integral int Integer 4 bytes
32 bits
Integral long Long 8 bytes
64 bits
Real double Double 8 bytes
64 bits
IEEE754 to IEEE1985
Real float Float 4 bytes
32 bits
IEEE754 to IEEE1985
Non Primitive Data types:

DataType Language Elements Wrapper Class Size Range Comments
Non Primitive String String String is a java class that is loaded with class coder . Typically 16 bit characters 
Non Primitive Void - - - -
Non Primitive Reference - - - stores the handle default value is null
Conversion between Primitive Datatypes:
Conversion between datatypes is called casting. So casting means explicitly telling java to force a conversion that the compiler would otherwise not carry out explicitly.Narrowing conversion is often referred as casting. However widening casting is also a type of casting. This is implicit and compiler will do that automatically. For narrowing conversion or down casting we need to provide the desired type is placed inside a bracket "()".
Case-1:When java run time explicitly changes the type without users interaction
Case-2:All conversion of primitive data types is checked at compile time in order to establish whether or not the conversion is permissible.
Statement-1

int i=10;
double d=i;
 
In this case an int type is converted to double type.It is an automatic conversion.
Statement-2

double d=10.0;//compiler will throw an error.
double d=(int)10.0;//conversion is done with loss of information
int i=d;
 
It is not directly permissible.The compiler will throw an error that there could be possible loss of precision. To forcefully do the conversion we need to cast it to int. The cast (int) forces d to be an int.


public void someMethod(double myValue)
{
//dosomethoing
} 
In this method is expecting a value of type double to be passed to it,when it is invoked.If we pass a float value or other data type(Integral or real), as double being top of the primitive data type hierarchy,the value will be converted to double.
Boolean values can not be converted to any other type.
A non boolean type can be converted to another non-boolean type provided that the conversion is widening conversion.
A non boolean type can not be converted to another non-boolean type if the conversion is narrowing conversion.
DataTypes Concept Simplified in Java DataTypes Concept Simplified in Java Reviewed by Animesh Chatterjee on December 11, 2018 Rating: 5

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