Showing posts with label Basic Programs. Show all posts
Showing posts with label Basic Programs. Show all posts

Tuesday, March 6, 2012

How do I create a scheduled task using timer in java?


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerExample extends TimerTask {
        private DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
        
        public static void main(String[] args) {
                // 
                // Create an instance of TimerTask implementor.
                //
                TimerTask task = new TimerExample();
                
                //
                // Create a new timer to schedule the TimerExample instance at a 
                // periodic time every 1000 milliseconds and start it immediately
                //
                Timer timer = new Timer();
                timer.scheduleAtFixedRate(task, new Date(), 1000);
        }
        
        /**
         * This method is the implementation of a contract defined in the TimerTask
         * class. This in the entry point of the task execution.
         */
        public void run() {
                //
                // To make the example simple we just print the current time.
                //                              
                System.out.println(formatter.format(new Date()));
        }
 }

How do I create an encrypted string for password in Java?


You are creating a user management system that will keep user profile and their credential or password. For security reason you'll need to protect the password, to do this you can use theMessageDigest provided by Java API to encrypt the password. The code example below show you a example how to use it.

import java.security.MessageDigest;

public class EncryptExample {
    public static void main(String[] args) {
        String password = "secret";
        String algorithm = "SHA";

        byte[] plainText = password.getBytes();

        MessageDigest md = null;

        try {           
            md = MessageDigest.getInstance(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
        }
                
        md.reset();             
        md.update(plainText);
        byte[] encodedPassword = md.digest();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < encodedPassword.length; i++) {
            if ((encodedPassword[i] & 0xff) < 0x10) {
                sb.append("0");
            }

            sb.append(Long.toString(encodedPassword[i] & 0xff, 16));
        }

        System.out.println("Plain    : " + password);
        System.out.println("Encrypted: " + sb.toString());
    }
}


Below is the output....

Plain    : secret
Encrypted: e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4

How do I use for-each in Java?


import java.util.ArrayList;
import java.util.List;

public class ForEachExample {
        public static void main(String[] args) {
                Integer[] numbers = {10, 100, 1000, 10000, 100000, 1000000};
                
                for (Integer i : numbers) {
                        System.out.println("Number: " + i);
                }
                
                List<String> names = new ArrayList<String>();
                names.add("James");
                names.add("Joshua");
                names.add("Scott");
                
                for (String name : names) {
                        System.out.println("Name: " + name);
                }
        }
}

How do I create random number in Java?


public class RandomExample 
{
    public static void main(String[] args)
    {
        // The Math.random() returns a random number between 0.0 and 1.0 
        // including 0.0 but not including 1.0.
        double number = Math.random();
        System.out.println("Generated number: " + number);
        
        // By multiplying Math.random() result with a number will give
        // us a range of random number between, for instance 0.0 to 10.0 as
        // shown in the example below.
        number = Math.random() * 10;
        System.out.println("Generated number: " + number);
        
        // To get a random number fron n to m we can add a n value to the 
        // Math.random() as the lowest number and then multiply it with the
        // the highest number. The example below creates random number
        // between 100.0 and 200.0.
        number = 100 + (Math.random() * 100);
        System.out.println("Generated number: " + number);
        
        // Creates an integer random number
        int random =  100 + (int)(Math.random() * 100);
        System.out.println("Generated number: " + random);
    }
}

Below is the output....

Generated number: 0.3568523577844326
Generated number: 7.0804177939495165
Generated number: 176.8077611008594
Generated number: 103

How do I convert decimal to octal in Java?


public class IntegerToOctalExample {    
    public static void main(String[] args) {
        int integer = 1024;
        //
        // Converting integer value to octal string representation.
        //
        String octal = Integer.toOctalString(integer);
        
        //
        // Output the value to console.
        //
        System.out.printf("Octal value of %d is '%s'.\n", integer, octal);

        //
        // When for formatting purposes we can actually use printf
        // or String.format to display an integer value in other
        // format (o = octal, h = hexadecimal).
        //
        System.out.printf("Octal value of %1$d is '%1$o'.\n", integer);

        //
        // Now we converting back from octal string to integer
        // by calling Integer.parseInt and passing 8 as the radix.
        //
        int original = Integer.parseInt(octal, 8);
        System.out.printf("Integer value of octal '%s' is %d.", octal, original);
    }
}


Below is output...

Octal value of 1024 is '2000'.
Octal value of 1024 is '2000'.
Integer value of octal '2000' is 1024.

How do I convert decimal to binary in Java?


public class IntegerToBinaryExample 
{
    public static void main(String[] args)
    {
        int integer = 127;
        String binary = Integer.toBinaryString(integer);
        System.out.println("Binary value of " + integer + " is " 
                + binary + ".");
        
        int original = Integer.parseInt(binary, 2);
        System.out.println("Integer value of binary '" + binary 
                + "' is " + original + ".");
    }
    
}

Below is output...

Binary value of 127 is 1111111.
Integer value of binary '1111111' is 127.


How do I read entries in a zip / compressed file in Java?


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

public class ZipFileSample
{
    public static void main(String[] args)
    {
        try
        {
            // Create an instance of ZipFile to read a zip file
            // called sample.zip
            ZipFile zip = new ZipFile(new File("sample.zip"));

            // Here we start to iterate each entries inside
            // sample.zip
            for (Enumeration e = zip.entries(); e.hasMoreElements();)
            {
                // Get ZipEntry which is a file or a directory
                ZipEntry entry = (ZipEntry) e.nextElement();
                // Get some information about the entry such as
                // file name, its size.
                System.out.println("File name: " + entry.getName()
                        + "; size: " + entry.getSize() 
                        + "; compressed size: "
                        + entry.getCompressedSize());

                // Now we want to get the content of this entry.
                // Get the InputStream, we read through the input
                // stream until all the content is read.
                InputStream is = zip.getInputStream(entry);
                InputStreamReader isr = new InputStreamReader(is);

                char[] buffer = new char[1024];
                while (isr.read(buffer, 0, buffer.length) != -1)
                {
                    String s = new String(buffer);
                    // Here we just print out what is inside the
                    // buffer.
                    System.out.println(s.trim());
                }
            }
        } catch (ZipException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

How do I get path / classpath separator?


OS platform have different symbol used for path separator. Path separator is a symbol that separate one path element from the other. In Windows you have something like:

.;something.jar;d:/libs/commons.jar

While on Linux operating system it looks like:

.:something.jar:/libs/commons.jar

To obtain the path separator you can use the following code.

import java.util.Properties;

public class SystemProperties {
    public static void main(String[] args) {
        //
        // Get System properties
        //
        Properties properties = System.getProperties();

        //
        // Get the path separator which is unfortunatelly
        // using a different symbol in different OS platform.
        //
        String pathSeparator =
                properties.getProperty("path.separator");
        System.out.println("pathSeparator = " + pathSeparator);
    }
}

How do I get Environment Variables in java?


Environment variables are sets of dynamic values that can affect a running process, such as our Java program. Each process usually have there own copy of these variables.
Now we'd like to obtain the available variables in our environment or operating system, how do I do this in Java? Here is a code example of it.

import java.util.Map;
import java.util.Set;
import java.util.Iterator;
 
public class SystemEnv
{
    public static void main(String[] args)
    {
        // We get the environment information from the System class. 
        // The getenv method (why shouldn't it called getEnv()?) 
        // returns a map that will never have null keys or values 
        // returned.
        Map map = System.getenv();
 
        // For this purpose of example we will interate the keys and 
        // values in it so we create an iterator object from it.
        Set keys = map.keySet();
        Iterator iterator = keys.iterator();
        while (iterator.hasNext())
        {
            // Here we iterate based on the keys inside the map, and 
            // with the key in hand we can get it values.
            String key = (String) iterator.next();
            String value = (String) map.get(key);
 
            System.out.println(key + " = " + value);
        }
    }
}

Below is output..

ANT_HOME = D:\Development\apache-ant-1.6.5
CATALINA_HOME = D:\Development\apache-tomcat-5.5.15
ANT_OPS = -Djava.util.logging.config.file=logging.properties
CLASSPATH = .;C:\Program Files\Java\jre1.5.0_09\lib\ext\QTJava.zip
OC4J_HOME = D:\Development\oc4j-extended-101310
JAVA_HOME = D:\Development\Java\jdk1.5.0_09
GERONIMO_HOME = D:\Development\geronimo-1.0

Monday, March 5, 2012

How do I get direct superclass and interfaces of a class in Java?


Java reflection also dealing with inheritance concepts. You can get the direct interfaces and direct superclass of a class by using method getInterfaces() and getSuperclass() ofjava.lang.Class object.
    1.getInterfaces() will returns an array of Class objects that represent the direct super interfaces of the target Class object
    2.getSuperclass() will returns the Class object representing the direct super class of the targetClass object or null if the target represents Object class, an interface, a primitive type, or void.

    import javax.swing.*;
    import java.util.Date;
    
    public class GetSuperClassDemo {
        public static void main(String[] args) {
            GetSuperClassDemo.get(String.class);
            GetSuperClassDemo.get(Date.class);
            GetSuperClassDemo.get(JButton.class);
            GetSuperClassDemo.get(Timer.class);
        }
    
        public static void get(Class clazz) {
            //
            // Gets array of direct interface of clazz object
            //
            Class[] interfaces = clazz.getInterfaces();
    
            System.out.format("Direct Interfaces of %s:%n",
                    clazz.getName());
            for (Class clz : interfaces) {
                System.out.println(clz.getName());
            }
    
            //
            // Gets direct superclass of clazz object
            //
            Class superclz = clazz.getSuperclass();
            System.out.format("Direct Superclass of %s: is %s %n",
                    clazz.getName(), superclz.getName());
            System.out.println("====================================");
        }
    }
Below is the output...
    Direct Interfaces of java.lang.String:
    java.io.Serializable
    java.lang.Comparable
    java.lang.CharSequence
    Direct Superclass of java.lang.String: is java.lang.Object 
    ====================================
    Direct Interfaces of java.util.Date:
    java.io.Serializable
    java.lang.Cloneable
    java.lang.Comparable
    Direct Superclass of java.util.Date: is java.lang.Object 
    ====================================
    Direct Interfaces of javax.swing.JButton:
    javax.accessibility.Accessible
    Direct Superclass of javax.swing.JButton: is javax.swing.AbstractButton 
    ====================================
    Direct Interfaces of javax.swing.Timer:
    java.io.Serializable
    Direct Superclass of javax.swing.Timer: is java.lang.Object 
    ====================================

How do I check if a class represent an interface type in Java?



public class IsInterfaceDemo {
    public static void main(String[] args) {
        IsInterfaceDemo.get(Serializable.class);
        IsInterfaceDemo.get(Long.class);
    }

    private static void get(Class clazz) {
        if (clazz.isInterface()) {
            System.out.println(clazz.getName() +
                    " is an interface type.");
        } else {
            System.out.println(clazz.getName() +
                    " is not an interface type.");
        }
    }
}
Below is the output...

java.io.Serializable is an interface type.
java.lang.Long is not an interface type.

How do I check if a class represent a primitive type in Java?


Java uses class objects to represent all eight primitive types. A class object that represents a primitive type can be identified using the isPrimitive() method call.void is not a type in Java, but theisPrimitive() method returns true for void.class.

public class IsPrimitiveDemo {
    public static void main(String[] args) {
        IsPrimitiveDemo.get(int.class);
        IsPrimitiveDemo.get(String.class);
        IsPrimitiveDemo.get(double.class);
        IsPrimitiveDemo.get(void.class);
    }

    private static void get(Class clazz) {
        if (clazz.isPrimitive()) {
            System.out.println(clazz.getName() +
                    " is a primitive type.");
        } else {
            System.out.println(clazz.getName() +
                    " is not a primitive type.");            
        }
    }
}

Below is the output...

int is a primitive type.
java.lang.String is not a primitive type.
double is a primitive type.
void is a primitive type.



How do I get information regarding class name in Java?


import java.util.Date;

public class ClassNameDemo {
    public static void main(String[] args) {
        Date date = new Date();

        //
        // Gets the Class of the date instance.
        //
        Class clazz = date.getClass();

        //
        // Gets the name of the class.
        //
        String name = clazz.getName();
        System.out.println("Class name     : " + name);

        //
        // Gets the canonical name of the class.
        //
        String canonical = clazz.getCanonicalName();
        System.out.println("Canonical name : " + canonical);

        //
        // Gets the simple name of the class.
        //
        String simple = clazz.getSimpleName();
        System.out.println("Simple name    : " + simple);
    }
}

Below is the output...

Class name     : java.util.Date
Canonical name : java.util.Date
Simple name    : Date

How do I get the component type of an array in Java?


The Class.getComponentType() method call returns the Class representing the component type of an array. If this class does not represent an array class this method returns null reference instead.

public class ComponentTypeDemo {
    public static void main(String[] args) {
        String[] words = {"and", "the"};
        int[][] matrix = {{1, 1}, {2, 1}};
        Double number = 10.0;

        Class clazz = words.getClass();
        Class cls = matrix.getClass();
        Class clz = number.getClass();

        //
        // Gets the type of an array component.
        //
        Class type = clazz.getComponentType();
        System.out.println("Words type: " +
                type.getCanonicalName());

        //
        // Gets the type of an array component.
        //
        Class matrixType = cls.getComponentType();
        System.out.println("Matrix type: " +
                matrixType.getCanonicalName());

        //
        // It will return null if the class doesn't represent
        // an array.
        //
        Class numberType = clz.getComponentType();
        if (numberType != null) {
            System.out.println("Number type: " +
                    numberType.getCanonicalName());
        } else {
            System.out.println(number.getClass().getName() +
                    " class is not an array");
        }
    }
}

How do I determine if a class object represents an array class in Java?


For checking if a class object is representing an array class we can use the isArray() method call of the Class object. This method returns true if the checked object represents an array class and falseotherwise.

public class IsArrayDemo {
    public static void main(String[] args) {
        int[][] matrix = {{1, 1}, {2, 1}};
        Class clazz = matrix.getClass();

        //
        // Check if the class object represents an array class
        //
        if (clazz.isArray()) {
            System.out.println(clazz.getSimpleName() +
                    " is an array class.");
        } else {
            System.out.println(clazz.getSimpleName() +
                    " is not an array class.");
        }
    }
}

How do I capitalize each word in a string in android?


This examples show you how to capitalize a string. We use methods from WordUtils class provided by the Apache commons-lang. We can use the WordUtils.capitalize(str) orWordUtils.capitalizeFully(str).

import org.apache.commons.lang.WordUtils;

public class WordCapitalize {
    public static void main(String[] args) {
        //
        // Capitalizes all the whitespace separated words in a string,
        // only the first letter of each word is capitalized.
        //
        String str = WordUtils.capitalize(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);

        //
        // Capitalizes all the whitespace separated words in a string
        // and the rest string to lowercase.
        //
        str = WordUtils.capitalizeFully(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);
    }
}

Below is the output...

str = The Quick Brown Fox JUMPS OVER The Lazy Dog.
str = The Quick Brown Fox Jumps Over The Lazy Dog.

How do I use string in switch statement in Java?


Starting from Java 7 release you can now use a string in the switch statement. On the previous version we can only use number or enum in the switch statement. The code below give you a simple example on it.

public class StringSwitchDemo {
    public static void main(String[] args) {
        StringSwitchDemo demo = new StringSwitchDemo();
        String day = "Sunday";

        switch (day) {
            case "Sunday":
                demo.doSomething();
                break;
            case "Monday":
                demo.doSomethingElse();
                break;
            case "Tuesday":
            case "Wednesday":
                demo.doSomeOtherThings();
                break;
            default:
                demo.doDefault();
                break;
        }
    }

    private void doSomething() {
        System.out.println("StringSwitchDemo.doSomething");
    }

    private void doSomethingElse() {
        System.out.println("StringSwitchDemo.doSomethingElse");
    }

    private void doSomeOtherThings() {
        System.out.println("StringSwitchDemo.doSomeOtherThings");
    }

    private void doDefault() {
        System.out.println("StringSwitchDemo.doDefault");
    }
}

How do I use multi-catch statement in java?


The multi-catch is a language enhancement feature introduces in the Java 7. This allow us to use a single catch block to handle multiple exceptions. Each exception is separated by the pipe symbol (|).
Using the multi-catch simplify our exception handling and also reduce code duplicates in the catchblock. Let's see an example below:

import java.io.IOException;
import java.sql.SQLException;

public class MultiCatchDemo {
    public static void main(String[] args) {
        MultiCatchDemo demo = new MultiCatchDemo();
        try {
            demo.callA();
            demo.callB();
            demo.callC();
        } catch (IOException | SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void callA() throws IOException {
        throw new IOException("IOException");
    }

    private void callB() throws SQLException {
        throw new SQLException("SQLException");
    }

    private void callC() throws ClassNotFoundException {
        throw new ClassNotFoundException("ClassNotFoundException");
    }
}


How do I create a zip file in Java?



import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZippingFileExample {
        public static void main(String[] args) {
                try {
                        String source = "dummy-1.txt";
                        String target = "data-1.zip";

     ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(target));
                        FileInputStream fis = new FileInputStream(source);

                        // put a new ZipEntry in the ZipOutputStream
                        zos.putNextEntry(new ZipEntry(source));

                        int size = 0;
                        byte[] buffer = new byte[1024];

          // read data to the end of the source file and write it to the zip
          // output stream.
                        while ((size = fis.read(buffer, 0, buffer.length)) > 0) {
                                zos.write(buffer, 0, size);
                        }

                        zos.closeEntry();
                        fis.close();

                        // Finish zip process
                        zos.close();
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }
}