Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, 14 June 2014

Introduction to JavaBeans

Every Java user interface class is a JavaBeans component. Understanding JavaBeans will help you to learn GUI components.JavaBeans is a software component architecture that extends the power of the Java language by enabling well-formed objects to be manipulated visually at design time in a  pure Java builder tool, such as NetBeans and Eclipse.

JavaBean Rules :
  • A JavaBean must have a public, no-argument constructor (a default constructor). This is required so that Java frameworks can facilitate automated instantiation.
  • The JavaBean class attributes must be accessed via accessor and mutator methods that follow a standard naming convention (getXxxx and setXxxx, isXxxx for boolean attributes). It’s important to note that an “attribute” is a named memory location that contains a value, while a “property” refers to this set of methods used to access an attribute. This allows frameworks to automate operations on attribute values.
  • The JavaBean class should be serializable. This allows Java applications and frameworks to save, store, and restore the JavaBean state.That means a bean must implement the Serializable interface to ensure a persistent state.
package player; 
// The class is serialized for IO operations
public class PersonBean implements java.io.Serializable {
 // attributes declared as private
 private String name;
 private boolean counter;
 

 // Default Constructor
 public Person() { }

 // getXxx to access the name attribute
 public String getName() {
  return this.name;
 }

 // setXxxx to mutate the name attribute
 public void setName(String name) {
  this.name = name;
 }

 // isXxxx to access boolean attribute
 public boolean iscounter() {
  return this.counter;
 }

 // setXxx to mutate boolean attribute
 public void setCounter(boolean counter) {
  this.counter = counter;
 }
}
 
import player.PersonBean;
 
/**
 * Class TestPersonBean
 */
public class TestPersonBean {
    /**
     * Tester method  for class PersonBean
     */
    public static void main(String[] args) {
        PersonBean person = new PersonBean();
 
        person.setName("Bob");
        person.setcounter(false);
 
        // Output: "Bob [alive]"
        System.out.print(person.getName());
        System.out.println(person.isCounter() ? " [counter]" : " [alive]");
    }
} 
Advantages:
  • The properties, events, and methods of a bean that are exposed to another application can be controlled.
  • A bean may register to receive events from other objects and can generate events that are sent to those other objects.
  • Auxiliary software can be provided to help configure a java bean.
  • The configuration setting of bean can be saved in a persistent storage and restored at a later time.
 Disadvantages:
  • A class with a nullary constructor is subject to being instantiated in an invalid state. If such a class is instantiated manually by a developer (rather than automatically by some kind of framework), the developer might not realize that the class has been improperly instantiated. The compiler can’t detect such a problem, and even if it’s documented, there’s no guarantee that the developer will see the documentation.
  • Having to create a getter for every property and a setter for many, most, or all of them can lead to an immense quantity of boilerplate code.

Monday, 9 June 2014

Singleton Design Pattern in java

Singleton pattern in Java is one of the most common patterns available and it’s also used heavily in core Java libraries.
A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern.
Java has several design patterns Singleton Pattern being the most commonly used.
There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.
GOF says, “Ensure a class has only one instance, and provide a global point of access to it."
That means this design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.

The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.
The key is not the problem and definition. In singleton pattern, tricky part is implementation and management of that single instance.
There are many classes in Java Development Kit which is written using singleton pattern, here are few of them:

 1.Java.lang.Runtime with getRuntime() method
 2.Java.awt.Toolkit with getDefaultToolkit()
 3.Java.awt.Desktop with  getDesktop()

There are at least four ways to implement Singleton pattern in Java.
1) Singleton by synchronizing getInstance() method
2) Singleton with public static final field initialized during class loading.
3) Singleton generated by static nested class, also referred as Singleton holder pattern.
4) From Java 5 on-wards using Enums
This article is an attempt to explain the basics on singleton design pattern.If you want more insight on singleton then i will explain it in detail later.

Monday, 2 June 2014

What is DatabaseMetaData?

DatabaseMetaData is used to know which type of driver we are using and whether is it compatable or JDBC complaint or not. It is used to know all details about database provider as well.Here is the example--
 
package com.rexofcyber.jdbc;
 
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class MyDatabaseMetadata {
 
    public static void main(String a[]){
         
        Connection con = null;
        try {
            con = DriverManager.
                getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
                        ,"user","password");
            DatabaseMetaData dm = con.getMetaData();
            System.out.println(dm.getDriverVersion());
            System.out.println(dm.getDriverName());
            System.out.println(dm.getDatabaseProductName());
            System.out.println(dm.getDatabaseProductVersion());
        } catch (SQLException e) {
         
            e.printStackTrace();
        } finally{
            if(con != null){}
                try {
                    con.close();
                } catch (SQLException e) {
            
                    e.printStackTrace();
                }
            }
        }
    }
}

How to execute any type of query in JDBC?

The Statement.execute() method allows us to execute any kind of query like select, update. It returns boolean. If the return value is true, then it executed select query, get the ResultSet object and read the resulted records. If it returns false, then it can be update query, call getUpdateCount() method to get total records updated.
package com.rexofcyber.jdbc;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class MyExecuteMethod {
 
    public static void main(String a[]){
         
        Connection con = null;
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.
                    getConnection("jdbc:oracle:thin:@<hostname>:<port num>:<DB name>"
                        ,"user","password");
            Statement stmt = con.createStatement();
            //The query can be update query or can be select query
            String query = "select * from emp";
            boolean status = stmt.execute(query);
            if(status){
                //query is a select query.
                ResultSet rs = stmt.getResultSet();
                while(rs.next()){
                    System.out.println(rs.getString(1));
                }
                rs.close();
            } else {
                //query can be update or any query apart from select query
                int count = stmt.getUpdateCount();
                System.out.println("Total records updated: "+count);
            }
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            try{
                if(con != null) con.close();
            } catch (Exception ex){}
        }
    }
}


Saturday, 24 May 2014

Puzzle 1: Hello, Goodbye

This program adds an unusual twist to the usual Hello world program. What does
it print?

public class HelloGoodbye {
public static void main(String[] args) {
try {
System.out.println("Hello world");
System.exit(0);
} finally {
System.out.println("Goodbye world");
}
}
}
Solution :
The program contains two println statements: one in a try block and the other in the corresponding finally block. The try block executes its println and finishes execution prematurely by calling System.exit. At this point, you might expect control to transfer to the finally block. If you tried the program, though, you found that it never can say goodbye: It prints only Hello world.
It is true that a finally block is executed when a try block completes execution whether normally or abruptly. In this program, however, the tryblock does not complete execution at all. The System.exit method halts the execution of the current thread and all others dead in their tracks.The presence of a finally clause does not give a thread special permission to continue executing.
When System.exit is called, the virtual machine performs two cleanup tasks before shutting down. First, it executes all shutdown hooks that have been registered with Runtime.addShutdownHook. This is useful to release resources external to the VM. Use shutdown hooks for behavior that must occur before the VM exits.The following version of the program demonstrates this technique,
printing both Hello world and Goodbye world, as expected:

public class HelloGoodbye {
public static void main(String[] args) {
System.out.println("Hello world");
Runtime.getRuntime().addShutdownHook(
new Thread() {
public void run() {
System.out.println("Goodbye world");
}
});
System.exit(0);
}
}

The second cleanup task performed by the VM when System.exitis called concerns finalizers. If either System.runFinalizersOnExitor its evil twin Runtime.runFinalizersOnExit has been called, the VM runs the finalizers on all objects that have not yet been finalized. These methods were deprecated a long time ago and with good reason. Never call System.runFinalizersOnExitor Runtime.runFinalizersOnExit for any reason: They are among the most
dangerous methods in the Java libraries. Calling these methods can result in finalizers being run on live objects while other threads are concurrently manipulating them, resulting in erratic behavior or deadlock.
In summary, System.exit stops all program threads immediately; it does not cause finally blocks to execute, but it does run shutdown hooks before halting the VM. Use shutdown hooks to terminate external resources when the VM shuts down. It is possible to halt the VM without executing shutdown hooks by calling System.halt, but this method is rarely used. 

Extract a zip file using Java

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
 
/**
 * This utility extracts files and directories of a standard zip file to
 * a destination directory.
 */
public class UnzipUtility {
    /**
     * Size of the buffer to read/write data
     */
    private static final int BUFFER_SIZE = 4096;
   

    public void unzip(String zipFilePath, String destdirectory)throwsIOException {
        File destDir = new File(destDirectory);
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file
        while (entry != null) {
            String filePath = destDirectory + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // if the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();
    }
 
    private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        byte[] bytesIn = new byte[BUFFER_SIZE];
        int read = 0;
        while ((read = zipIn.read(bytesIn)) != -1) {
            bos.write(bytesIn, 0, read);
        }
        bos.close();
    }
}

Monday, 31 March 2014

How can you improve Java I/O performance?

Java applications that utilise Input/Output are excellent candidates for performance  tuning. Profiling of Java applications that handle significant volumes of data will show significant time spent in I/O operations. This means substantial gains can be had from I/O performance tuning. Therefore, I/O efficiency should be a high priority for developers looking to optimally increase performance.
The basic rules for speeding up I/O performance are
  • Minimise accessing the hard disk.
  • Minimise accessing the underlying operating system.
  • Minimise processing bytes and characters individually.   
Let us look at some of the techniques to improve I/O performance.

Use bufferingto minimise disk access and underlying operating system. As shown below, with buffering large chunks of a file are read from a disk and then accessed a byte or character at a time.

Without buffering : inefficient code
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
int count = 0;
int b = ;
while((b = fis.read()) != -1){
if(b== '\n') {
count++;
}
}
// fis should be closed in a finally block.
fis.close() ;
}
catch(IOException io){}
Note: fis.read() is a native method call to the underlying system.
With Buffering:yields better performance
try{
File f = new File("myFile.txt");
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
int count = 0;
int b = ;
while((b = bis.read()) != -1){
if(b== '\n') {
count++;
}
}
//bis should be closed in a finally block.
bis.close() ;
}
catch(IOException io){}
Note:bis.read() takes the next byte from the input buffer and only
rarely access the underlying operating system.

Instead of reading a character or a byte at a time, the above code with buffering can be improved further by reading one line at a time as shown below:

FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
While (br.readLine() != null) count++;

Sunday, 16 March 2014

How Volatile in Java works ?

What  is Volatile variable in Java  and when to use Volatile variable in Java is famous multi-threading interview question in Java interviews.
apart from use in multitreaded programming it is also used for optimization.
When Compiler compiles a program it performs some sort of optimization in it.
if a variable is decleard to be volatile then compiler does't perform any  optimization on it

When to use Volatile variable in Java

1) You can use Volatile variable if you want to read and write long and double variable atomically. long and double both are 64 bit data type and by default writing of long and double is not atomic and platform dependence. Many  platform perform write in long and double variable 2 step, writing 32 bit in each step, due to this its possible for a Thread to see 32 bit from two different write. You can avoid this issue by making long and double variable volatile in Java.
2) Volatile variable can be used as an alternative way of achieving synchronization in Java in some cases, like Visibility. with volatile variable its guaranteed that all reader thread will see updated value of volatile variable once write operation  completed, without volatile keyword different reader thread may see different values.
3) volatile variable can be used to inform compiler that a particular field is subject to be accessed by multiple threads, which will prevent compiler from doing any reordering or any kind of optimization which is not desirable in multi-threaded environment. Without volatile variable compiler can re-order code, free to cache value of volatile variable instead of always reading from main memory. like following example without volatile variable may result in infinite loop
4) Another place where volatile variable can be used is to fixing double checked locking in Singleton pattern. As we discussed in Why should you use Enum as Singleton that double checked locking was broken in Java 1.4 environment.
 

Friday, 7 March 2014

Why are GUIs Single-threaded?

In the old days, GUI applications were single-threaded and GUI events were processed from a "main event loop". Modern GUI frameworks use a model that is only slightly different: they create dedicated event dispatch thread (EDT) for handling GUI events.

Single-threaded GUI frameworks are not unique to Java; Qt, NextStep, MacOS Cocoa, X Windows, and many others are also single-threaded. This is not for lack of trying; there have been many attempts to write multithreaded GUI frameworks, but because of persistent problems with race conditions and deadlock, they all eventually arrived at the single-threaded event queue model in which a dedicated thread fetches events off a queue and dispatches them to applicationdefined event handlers. (AWT originally tried to support a greater degree of multithreaded access, and the decision to make Swing single-threaded was based largely on experience with AWT.)

Multithreaded GUI frameworks tend to be particularly susceptible to deadlock, partially because of the unfortunate interaction between input event processing and any sensible object-oriented modeling of GUI components.

Another factor leading to deadlock in multithreaded GUI frameworks is the prevalence of the
model-view-control (MVC) pattern. Factoring user interactions into cooperating model, view, and controller objects greatly simplifies implementing GUI applications, but again raises the risk of inconsistent lock ordering. The controller calls into the model, which notifies the view that something has changed. But the controller can also call into the view, which may in turn call back into the model to query the model state. The result is again inconsistent lock ordering, with the attendant risk of deadlock.

Java ArrayList Tutorial

It’s also important to remember that ArrayList is not synchronized and should not be shared between multiple threads. If multiple threads access a Java ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (As per Java doc a structural modification is any operation that adds or deletes one or more elements, or explicitly re-sizes the backing array; merely setting the value of an element is not a structural modification.)


1) Creating an ArrayList
You can use ArrayList in Java with or without Generics both are permitted by generics version is recommended because of enhanced type-safety.
In this example we will create an ArrayList of String in Java. This Java ArrayList will only allow String and will throw compilation error if we try to any other object than String.

ArrayList<String> stringList = new ArrayList<String>(); //Generic ArrayList to Store only String objects
2) Putting an Item into ArrayList
Second line will result in compilation error because this Java ArrayList will only allow String elements.
stringList.add("Item"); //no error because we are storing String
stringList.add(new Integer(2)); //compilation error
3) Checking size of ArrayList
Size of an ArrayList in Java is total number of elements currently stored in ArrayList.

int size = stringList.size();

4) Checking Index of an Item in Java Arraylist
You can use indexOf() method of ArrayList in Java to find out index of a particular object.

int index = stringList.indexOf("Item"); //location of Item object in List
5) Retrieving Item from arrayList in a loop
Many a times we need to traverse on Java ArrayList and perform some operations on each retrieved item. Here are two ways of doing it without using Iterator. We will see use of Iterator in next section.
for (int i = 0; i < stringList.size(); i++)
   String item = stringList.
get(i);
   System.
out.println("Item " + i + " : " + item);
}

From Java
5 onwards you can use foreach loop as well

for(String item: stringList){
System.
out.println("retrieved element: " + item);
}
6) Checking ArrayList for an Item
Sometimes we need to check whether an element exists in ArrayList in Java or not for this purpose we can use contains () method of Java. contains() method takes type of object defined in ArrayList creation and returns true if this list contains the specified element.
7) Checking if ArrayList is Empty
We can use isEmpty() method of Java ArrayList to check whether ArrayList is empty. isEmpty() method returns true if this ArrayList contains no elements. You can also use size() method of List to check if List is empty
boolean result = stringList.isEmpty(); //isEmpty() will return true if List is empty

if(stringList.size() == 0){
   System.
out.println("ArrayList is empty");
}

8) Removing an Item from ArrayList
There are two ways to remove any elements from ArrayList in Java. You can either remove an element based on its index or by providing object itself. Remove remove (int index) and remove (Object o) method is used to remove any element from ArrayList in Java. Since ArrayList allows duplicate its worth noting that remove (Object o) removes the first occurrence of the specified element from this list, if it is present. In below code first call will remove first element from ArrayList while second call will remove first occurrence of item from ArrayList in Java.
stringList.remove(0);  
stringList.remove(item);

9) Copying data from one ArrayList to another ArrayList in Java
Many a times you need to create a copy of ArrayList for this purpose you can use addAll(Collection c) method of ArrayList in Java to copy all elements from on ArrayList to another ArrayList in Java. Below code will add all elements of stringList to newly created copyOfStringList.
ArrayList<String> copyOfStringList = new ArrayList<String>();
copyOfStringList.
addAll(stringList);

10) Replacing an element at a particular index
You can use set (int index, E element) method of java ArrayList to replace any element from a particular index. Below code will replace first element of stringList from "Item" to "Item2".

stringList.set(0,"Item2");

11) Clearing all data from ArrayList
ArrayList in Java provides clear () method which removes all of the elements from this list. Below code will remote all elements from our stringList and make the list empty. You can reuse Java ArrayList after clearing it.

stingList.clear();

12) Converting from ArrayList to Array in Java
Java ArrayList provides you facility to get the array back from your ArrayList. You can use toArray(T[] a) method returns an array containing all of the elements in this list in proper sequence (from first to last element). "a" is the array into which the elements of the list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
String[] itemArray = new String[stringList.size()];
String
[] returnedArray = stringList.toArray(itemArray);

13) Creating Synchronized ArrayList
Some times you need to synchronize your ArrayList in java to make it shareable between multiple threads you can use Collections utility class for this purpose as shown below.

List list = Collections.synchronizedList(new ArrayList(...));
14) Creating ArrayList from Array in Java
ArrayList in Java is amazing you can create even an ArrayList full of your element from an already existing array. You need to use Arrays.asList(T... a)  method for this purpose which returns a fixed-size list backed by the specified array.

ArrayList stringList = Arrays.asList(new String[]{"One", "Two", "Three"); //this is not read only List you can still update value of existing elements

15) Traversing in ArrayList in Java
You can use either Iterator or ListIterator for traversing on Java ArrayList. ListIterator will allow you to traverse in both directions while both Iterator and ListIterator will allow you to remove elements from ArrayList in Java while traversing.
Iterator itr = stringList.iterator();
while(itr.hasNext()){
System.
out.println(itr.next());
}

ListIterator listItr = stringList.
listIterator();
while(listItr.hasNext()){
System.
out.println(itr.next());
}

Why character array is better than String for Storing password in Java ?

1) Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text and that's another reason you should always used an encrypted password than plain text. Since Strings are immutable there is no way contents of Strings can be changed because any change will produce new String, while if you char[] you can still set all his element as blank or zero. So Storing password in character array clearly mitigates security risk of stealing password.
2) Java itself recommends using getPassword() method of JPasswordField which returns a char[] and deprecated getText() method which returns password in clear text stating security reason. Its good to follow advice from Java team and adhering to standard rather than going against it.
3) With String there is always a risk of printing plain text in log file or console but if use Array you won't print contents of array instead its memory location get printed. though not a real reason but still make sense.

String strPassword="Unknown";
char[] charPassword= new char[]{'U','n','k','w','o','n'};
System.out.println("String password: " + strPassword);
System.out.println("Character password: " + charPassword);

String password: Unknown
Character password: [C@110b053

Thursday, 6 March 2014

How to Find IP address of Localhost, Server or Your Machine

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

/*
 * @author Pandey
 */
public class IPAddress {

    public static void main(String args[]) {

        // First get InetAddress for the machine, here localhost
        InetAddress myIP = null;
        try {
            myIP = InetAddress.getLocalHost();

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // getHostAddress() returns IP address of a machine
        String IPAddress = myIP.getHostAddress();

        // getHostname returns DNS hostname of a machine
        String hostname = myIP.getHostName();

        System.out.printf("IP address of Localhost is %s %n", IPAddress);
        System.out.printf("Host name of your machine is %s %n", hostname);

    }

}

Output:
IP address of Localhost is 192.168.1.41
Host name of your machine is Jaachase