Showing posts with label J2SE. Show all posts

Autoboxing and unboxing conversions in Java

Autoboxing and unboxing in java

Autoboxing and Unboxing
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called Unboxing.

Autoboxing
Converting primitive values (int, long, float, double...) into an object of the corresponding wrapper class (Integer, Long, Float, Double...) is called autoboxing. The compiler applies autoboxing when a primitive value is:

  • Passed as a parameter to a method that expects an object of the corresponding wrapper class.
  • Assigned to a variable of the corresponding wrapper class.

Autoboxing Example
The given code
/* Passed as a parameter to a method that expects an object of the corresponding wrapper class. */
List<Integer> listIntegers = new ArrayList<>();
for (int i = 1; i < 10; i++){
 listIntegers.add(i); 
}
=====
/* Assigned to a variable of the corresponding wrapper class. */
int x = 10;
Integer y = x;
will be converted by compiler as follow, Here i is autoboxed by Integer.valueOf(i).
List<Integer> listIntegers = new ArrayList<>();
for (int i = 1; i < 10; i++){
 listIntegers.add(Integer.valueOf(i));
}
=====
int x = 10;
Integer y = Interger.valueOf(x);

Unboxing
Converting an object of a wrapper type (Integer, Long, Float, Double...) to its corresponding primitive (int, long, float, double...) value is called unboxing. The compilere applied unboxing when an object of a wrapper class is:

  • Passed as a parameter to a method that expects a value of the corresponding primitive type.
  • Assigned to a variable of the corresponding primitive type.

Unboxing Example
The given code
/* Assigned to a variable of the corresponding primitive type. */
int sum = 0;
for (Integer i : listIntegers){
 if (i % 2 == 0){
  sum += i;
 }    
}
=====
/* Passed as a parameter to a method that expects a value of the corresponding primitive type. */
Integer a = new Integer(10);
Integer b = new Integer(10);

int summation = sum(a, b);

public int sum(int x, int y){
  return x + y;
}
will be converted by compiler as follow because remainder (%) and unary plus (+=) don't apply on wrapper class Integer. Here i % 2 unboxed by i.intValue() % 2 and sum += i unboxed by sum += i.intValue().
int sum = 0;
for (Integer i : listIntegers){
 if (i.intValue() % 2 == 0){
  sum += i.intValue();
 }    
}
=====
Integer a = new Integer(10);
Integer b = new Integer(10);

int summation = sum(a.intValue(), b.intValue());

public int sum(int x, int y){
  return x + y;
}

What is difference between method Overloading and Overriding in Java?

Its one of the popular Interview question asked to Java developer with 0 - 1 year experience. We'll understand method overloading followed by method overriding.

Method Overloading
Same method name but different parameters in class.

Source code (MethodOverload.java)
/**
 * Example of method overloading
 *
 * @author javaQuery
 * @date 5th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class MethodOverload {

    public int x = 0;

    /**
     * Method overloading - Same method name(getAndIncrement) with no parameter.
     * Increment x by 1.
     *
     * @return
     */
    public int getAndIncrement() {
        x = x + 1; // you can also use like x = getAndIncrement(1);
        return x;
    }

    /**
     * Method overloading - Same method name(getAndIncrement) with parameter.
     * Increment x by given count(value).
     *
     * @param add
     * @return
     */
    public int getAndIncrement(int add) {
        x = x + add;
        return x;
    }

    public static void main(String[] args) {
        MethodOverload methodOverload = new MethodOverload();
        System.out.println("calling 'getAndIncrement()': " + methodOverload.getAndIncrement());
        System.out.println("calling 'getAndIncrement(int add)': " + methodOverload.getAndIncrement(2));
    }
}
Output
calling 'getAndIncrement()': 1
calling 'getAndIncrement(int add)': 3

Method Overriding
In case of class(sub-class: AddAndDisplay) extends/implements other class/interface (super-class: Addition).
Method with same name and parameter created in sub-class.
Note: Overriding is used when you don't want to use default implementation provided by parent class and will write your own piece of implementation in overridden method.

Source code (Addition.java)
/**
 * Example of method overriding.
 *
 * @author javaQuery
 * @date 6th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class Addition {

    /**
     * Add two numbers and return the result.
     * @param x
     * @param y
     * @return 
     */
    public int add(int x, int y) {
        return x + y;
    }
}

Source code (AddAndDisplay.java)
/**
 * Example of method overriding.
 *
 * @author javaQuery
 * @date 6th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class AddAndDisplay extends Addition {

    /**
     * Method override of class Addition.
     * We're overriding 'add' method because we want to print
     * values of 'x' and 'y' to console along with the 'result'.
     * @param x
     * @param y
     * @return
     */
    @Override
    public int add(int x, int y) {
        int result = x + y;
        System.out.println("(x:" + x + ",y:" + y + ")");
        System.out.println("result: " + result);
        return result;
    }
}

Source code (MethodOverride.java)
/**
 * Example of method overriding.
 *
 * @author javaQuery
 * @date 6th October, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class MethodOverride {
    public static void main(String[] args) {
        /* Add two number using super class Addition's add method */
        Addition addition1 = new Addition();
        int result = addition1.add(20, 30);
        System.out.println("calling Addition.add(int x, int y)");
        System.out.println("result: " + result);
        System.out.println("********************************************");
        
        System.out.println("calling AddAndDisplay.add(int x, int y)");
        Addition addition2 = new AddAndDisplay();
        /**
         * Notice: We created object of 'Addition' using 'AddAndDisplay'.
         * 
         * So when we call Addition.add(int x, int y) method it'll execute
         * AddAndDisplay.add(int x, int y) method because 'add' is 
         * overridden. 
         * 
         * It'll hide the superclass Addition's add method and execute
         * subclass AddAndDisplay's method.
         */
        addition2.add(10, 20);
    }
}
Output
calling Addition.add(int x, int y)
result: 50
********************************************
calling AddAndDisplay.add(int x, int y)
(x:10,y:20)
result: 30

Examples of Java 8

Java 8
Using IntStream over for loop in Java 8

How to iterate over stream and increment index value in Lambda Expression?
Many of you having trouble for increment index value inside Lambda expression because of Local variable index defined in an enclosing scope must be final or effectively final. There is an alternative for that...

How to get(collect) List of Properties (String, Double, Integer) from List of beans in Java 8?
This little excerpt shows How you can fetch List<String>, List<Double>, List<Integer>, List<Object>, etc... from List<Beans>. And it also explains the use of map method in stream.

How to convert List to Map in Java 8 using Stream API?
Code snippet demonstrate converting List<T> to Map<K,V>.

Example of Collectors minBy in Lambda expression
This static method from package java.util.stream and class Collectors used to find maximum value from given Collection. This method takes Comparator as an argument.

Example of Collectors maxBy in Lambda expression
This static method from package java.util.stream and class Collectors used to find maximum value from given Collection. This method takes Comparator as an argument.

Example of distinct in Java 8
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.

How flatMap works in Java 8 with Example
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.)



Example of mapToInt in Java 8
Returns an IntStream consisting of the results of applying the given function to the elements of this stream.

Example of mapToLong in Java 8
Returns a LongStream consisting of the results of applying the given function to the elements of this stream.

Example of mapToDouble in Java 8
Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream.

How to sum values from List, Set and Map using stream in Java 8?

How to assign same value to multiple variables in Java?

Following excerpt shows assignment of same value to multiple variables in Java.

Source code
/**
 * Example: Assign same value to multiple variable.
 *
 * @author javaQuery
 * @date 2nd January, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class AssignSameValue {

    public static void main(String[] args) {
        int red = 0, green = 0, blue = 0;

        String color = "white"; // args[0]

        if ("white".equalsIgnoreCase(color)) {
            /* assign same value to red, green, blue */
            red = green = blue = 255;
        } else if ("black".equalsIgnoreCase(color)) {
            /* assign same value to red, green, blue */
            red = green = blue = 0;
        } else {
            /* other else if...else for more color combinations */
        }

        System.out.println("Color code:");
        System.out.println("red = " + red + ", green = " + green + ", blue = " + blue);
    }
}

Output
Color code:
red = 255, green = 255, blue = 255

Perform Divide by zero on different data types of Java



60% - 70% Java developer thinks that if you divide any number with zero '0' gives you java.lang.ArithmeticException: / by zero

short / Short / int / Integer / long / Long
When you perform divide by zero (0) on mentioned data types then it will give you java.lang.ArithmeticException: / by zero irrespective of Positive Number, Negative Number or even Zero(0).


float / Float / double / Double
When you perform divide by zero (0 or 0.0) on mentioned data type then it will give you different result based on Positive Number, Negative Number and Zero(0).
  • Positive Number / 0 or Positive Number / 0.0 - Gives Infinity
  • Negative Number / 0 or Negative Number / 0.0 - Gives -Infinity
  • 0 / 0.0 or 0.0 / 0 - Gives Nan (Not A Number)

Source code
public class DivideByZeroExample {
    public static void main(String[] args) {
        try {
            /**
             * All below operation will give you
             * 'java.lang.ArithmeticException: / by zero'
             */
            short a = 111;
            short a1 = 0;
            
            System.out.println(a/0);
            //System.out.println(a1/0);
            
            Short x = 123;
            Short x1 = 0;
            
            //System.out.println(x/0);
            //System.out.println(x1/0);
            
            int b = 222;
            int b1 = 0;
            
            //System.out.println(b/0);
            //System.out.println(b1/0);
            
            Integer y = 234;
            Integer y1 = 0;
            
            //System.out.println(y/0);
            //System.out.println(y1/0);
            
            long c = 333;
            long c1 = 0;
            
            //System.out.println(c/0);
            //System.out.println(c1/0);
            
            Long z = 345L;
            Long z1 = 0L;
            
            //System.out.println(z/0);
            //System.out.println(z1/0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
        
        /* Performing Divide by zero on floating data types */
        float d = 111;
        float d1 = 0;
        
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++");
        System.out.println(d + "/0" + " , " + -d +"/0 [float(Positive/(-)Negative) Divide by zero gives (Infinity/-Infinity)]: " + d/0 + " , " + -d/0);
        System.out.println(d1 + "/0" + " [float '0.0' Divide by zero gives 'Nan' (Not A Number)]: " + d1/0);
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++");
        
        Float e = 123F;
        Float e1 = 0F;
        
        System.out.println(e + "/0" + " , " + -e +"/0 [Float(Positive/(-)Negative) Divide by zero gives (Infinity/-Infinity)]: " + e/0 + " , " + -e/0);
        System.out.println(e1 + "/0" + " [Float '0.0' Divide by zero gives 'Nan' (Not A Number)]: " + e1/0);
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++");
        
        double m = 111;
        double m1 = 0;
        
        System.out.println(m + "/0" + " , " + -m +"/0 [double(Positive/(-)Negative) Divide by zero gives (Infinity/-Infinity)]: " + m/0 + " , " + -m/0);
        System.out.println(m1 + "/0" + " [double '0.0' Divide by zero gives 'Nan' (Not A Number)]: " + m1/0);
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++");
        
        Double n = 123D;
        Double n1 = 0D;
        
        System.out.println(n + "/0" + " , " + -n +"/0 [Double(Positive/(-)Negative) Divide by zero gives (Infinity/-Infinity)]: " + n/0 + " , " + -n/0);
        System.out.println(n1 + "/0" + " [Double '0.0' Divide by zero gives 'Nan' (Not A Number)]: " + n1/0);
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++");
    }
}

Output
java.lang.ArithmeticException: / by zero
 at com.javaquery.math.DivideByZeroExample.main(DivideByZeroExample.java:22)
+++++++++++++++++++++++++++++++++++++++++++++
111.0/0 , -111.0/0 [float(Positive/(-)Negative) Divide by zero gives (Infinity/-Infinity)]: Infinity , -Infinity
0.0/0 [float '0.0' Divide by zero gives 'Nan' (Not A Number)]: NaN
+++++++++++++++++++++++++++++++++++++++++++++
123.0/0 , -123.0/0 [Float(Positive/(-)Negative) Divide by zero gives (Infinity/-Infinity)]: Infinity , -Infinity
0.0/0 [Float '0.0' Divide by zero gives 'Nan' (Not A Number)]: NaN
+++++++++++++++++++++++++++++++++++++++++++++
111.0/0 , -111.0/0 [double(Positive/(-)Negative) Divide by zero gives (Infinity/-Infinity)]: Infinity , -Infinity
0.0/0 [double '0.0' Divide by zero gives 'Nan' (Not A Number)]: NaN
+++++++++++++++++++++++++++++++++++++++++++++
123.0/0 , -123.0/0 [Double(Positive/(-)Negative) Divide by zero gives (Infinity/-Infinity)]: Infinity , -Infinity
0.0/0 [Double '0.0' Divide by zero gives 'Nan' (Not A Number)]: NaN
+++++++++++++++++++++++++++++++++++++++++++++

What is the difference between final and effectively final?

Lambda Expression Java 8

effectively final introduced in Java 8 with Lambda Expression. Technically there is no difference between final and effectively final.

What is final?
Any variable marked with final can't be modified.


What is effectively final?
Any variable outside of Lambda Expression, initialized only once in scope of variable(in method) then it is called effectively final variable and can be used in Lambda Expression. Its similar to final variable, the difference is you don't have to specify(use) final keyword in front of variable(initialized only once) when you want to use it in Lambda Expression.


Source code
import java.util.ArrayList;
import java.util.List;

public class EffectiveFinal {

    public static void main(String[] args) {
        /* String marked with `final` that you can't change once initialized */
        final String Firstname = "Vicky";

        /* Using `final` String in Runnable interface or any anonymous class */
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println("Thread: " + Firstname);
            }
        });
        /* Start the thread to display value of Firstname */
        thread.start();

        /* Code for Lambda Expression */
        /* Create List of Strings */
        List>String> listStrings = new ArrayList>String>();
        listStrings.add("Vicky");
        listStrings.add("Chirag");

        /**
         * Any variable outside of Lambda Expression, initialized only once in scope of variable(in whole program) then its `effectively final` variable.
         * 
         * In this program `Lastname` is effectively final variable as it is initialized only once and can be used in Lambda Expression.
         * Note: You can also mark `Lastname` as final and then you can use it in Lambda Expression. 
         */
        String Lastname = "Thakor";

        /**
         * If you re-initialize or modify value of `Lastname` then you can't use it in Lambda Expression.
         * Lastname = "Stark"; OR Lastname = ""; OR Lastname += " ";
         */
        //Lastname += " "; 
       
        /* Lastname is used in following Lambda Expression */
        listStrings.stream()
                   .forEach(str -> System.out.println("Lambda Expression: " + str + " " + Lastname));

Code Explanation
Part 1: We all used Runnable interface. And as you know the rule for anonymous class in Java, that variable declared outside the scope of Runnable interface should be final. If you try to use non-final variable declared outside the scope of Runnable then compiler will throw an error Cannot refer to a non-final variable Firstname inside an inner class defined in a different method

Part 2: To use Lambda Expression we created List of String. We've variable Lastname that is initialized only once in program so it is called effectively final variable and can be used inside Lambda Expression.
- If you uncomment the line Lastname += " "; then compiler will throw an error local variables referenced from a lambda expression must be final or effectively final


Output
Thread: Vicky
Lambda Expression: Vicky Thakor
Lambda Expression: Chirag Thakor

What is the difference between Class and Object in Java?


Developer always gets confuse, when they face this question. They creates class and object in their day to day life. However, they don't know the concept behind it. Lets understand the difference between them.

Class
A Class defines a new data type and it is template for an Object (A Class is data type and can be used to create an Object of that data type.). A class can be declared using class keyword.


Book (An example of Class)
Following class defines common template(class) for Book. That can be used to create an Object of Book.
public class Book{
   String name;
   String author;
}

Object
Object is instance of Class. You can create Object using new keyword. When you create an Object using new keyword then it allocates memory for an object at runtime and returns reference to it.


Example of Object
You can create as many Objects of Book. Each Object hold its own copy of variables defined in Class Book.
Book objBook = new Book();

Book objJavaBlackBook = new Book();
objJavaBlackBook.name = "Java Black Book";
objJavaBlackBook.author = "James Gosling";

Book objFiftyShadesofGrey = new Book();
objFiftyShadesofGrey.name = "Fifty Shades of Grey";
objFiftyShadesofGrey.author = "E. L. James";

Book objBriefHistoryofTime = new Book();
objBriefHistoryofTime.name = "A Brief History of Time";
objBriefHistoryofTime.author = "Stephen Hawking";
As you can see in above example we have three different objects of Book and each hold different values for name and author. Here Class Book used as a template for different types of Book.

Difference between static and non-static method in Java


There is significant difference between static and non-static methods in Java. We'll understand each difference with example.

Accessing static and non-static methods
  • static method can be accessed without creating instance of class. It is attached with class itself.
  • To access non-static method you have to create instance of class.
public class ExampleStaticMethod {
 
 /* static method `add` */
 public static int add(int x, int y){
    return x + y;
 }
 
 /* non-static method `subtract` */
 public int subtract(int x, int y){
    return x - y;
 }
 
 public static void main(String[] args) {
    int x = 10;
    int y = 20;
  
    /* Accessing static method without creating instance */
    System.out.println("Addition: "+ add(x, y));

    /* Accessing non-static method */
    ExampleStaticMethod objExampleStaticMethod = new ExampleStaticMethod();
    System.out.println("Subtraction: "+ objExampleStaticMethod.subtract(x, y));
 }
}

Accessing variables in static and non-static methods
  • You can't access non static variables inside static methods.
  • You can access static and non-static variables inside non-static methods.
public class ExampleStaticMethod {
 
 public int k = 40;
 public static int z = 30;
 
 /* static method `add` */
 public static int add(int x, int y){
    /* You can access `z` but you can't access `k` */
    return x + y + z;
 }
 
 /* non-static method `subtract` */
 public int subtract(int x, int y){
    /* You can access `z` and `k` */
    return x - y - z - k;
 }
 
 public static void main(String[] args) {
    int x = 10;
    int y = 20;
  
    /* Accessing static method without creating instance */
    System.out.println("Addition: "+ add(x, y));

    /* Accessing non-static method */
    ExampleStaticMethod objExampleStaticMethod = new ExampleStaticMethod();
    System.out.println("Subtraction: "+ objExampleStaticMethod.subtract(x, y));
 }
}

Method Override
  • You can't @Override static methods.
  • You can @Override non-static methods.
public class ExampleStaticMethod2 extends ExampleStaticMethod{
 
 /**
  * Can't Override static method `add`
  * Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  *  The method add(int, int) of type ExampleStaticMethod2 must override or implement a supertype method 
  */
 //@Override
 //public static int add(int x, int y){
 // return x + y;
 //}
 
 /**
  * Can't Override static method `add`
  * Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  *  Cannot make a static reference to the non-static method add(int, int) from the type ExampleStaticMethod2
  */
 //@Override
 //public int add(int x, int y){
 // return x + y;
 //}
 
 /* Override non-static method `subtract` */
 @Override
 public int subtract(int x, int y){
    return x - y;
 }
}

Method Overload
  • static and non-static methods have same behavior for method overloading.


Understanding basics java.awt.Desktop

I was finding some good topic to write an article. So looking all around my projects. I used java.awt.Desktop class in my program. Lets discuss all about the Desktop class of java.

What is java.awt.Desktop?
          java.awt.Desktop class designed to interact with system programs. It executes the system command to handle the operation of file and sometime URL(s). So now lets take a look at the methods of Desktop class. All methods throws IOException so use try-catch.

Desktop.getDesktop().browse(URI uri)
This function is used to open URL Uniform (or universal) Resource Locator. This will open the URL in system's default web browser client.
Desktop.getDesktop().browse(URI.create("http://www.javaquery.com"));

Desktop.getDesktop().edit(File file)
It'll open file specified in parameter with system related editor. Say your file is .txt, .docx, etc... Be careful with this because if there ain't any editor related to that file type it'll throws error  java.io.IOException: Failed to edit file:/c:/1.pdf. Error message: Unspecified error. I'm trying to edit .pdf file which is not supported by my system.
Desktop.getDesktop().edit(new File("c:\\1.txt"));

Desktop.getDesktop().isSupported(Action action)
This method designed to check that system user has enough privileges to do operation. System admin can set  file open, edit, print, browse and mail permission of other users. It'll return true and false based on permission.
Desktop.getDesktop().isSupported(Desktop.Action.OPEN);
Desktop.getDesktop().isSupported(Desktop.Action.EDIT);
Desktop.getDesktop().isSupported(Desktop.Action.PRINT);
Desktop.getDesktop().isSupported(Desktop.Action.BROWSE);
Desktop.getDesktop().isSupported(Desktop.Action.MAIL);

Desktop.getDesktop().mail()
It'll open the default mail client program of system.

Desktop.getDesktop().mail(URI uri)
Helps to set email, subject, message, cc and bcc on system default mail client. Predefined subject of mail and To so user don't need to remember your mail id or support mail id.
// To set space use "%20"
Desktop.getDesktop().mail(URI.create("mailto:vkijust4u@javaquery.com?subject=Hello%20World&body=This%20is%20sample%20mail&cc=example@gmail.com&bcc=example@yahoo.com"));

Desktop.getDesktop().open(File file)
Open the specified file in system's default program.
Desktop.getDesktop().open(new File("c:\\1.pdf"));

Desktop.getDesktop().print(File file)
Print the specified file in system's default printer.
Desktop.getDesktop().print(new File("c:\\1.pdf"));

Desktop.isDesktopSupported()
Tests whether this class is supported on the current platform. If it's supported, use Desktop.getDesktop() to retrieve an instance.

How to get .java file from .class file?


Some of us having question like. "Is it possible to get .java file from .class file?" , "Extract real code from .class file?".

Hello folks i wondered that this is possible to get .java (file real source code) from .class file. I don't know about this thing, on facebook MJVM club one of our Java lover asked this question. Join us on facebook for more java based question answer.

This is very bad thing about java i came through about this. Now i'll show you how to do this thing.

Download the software from below links.

The first tool is easy to use. Second tool is command based so once you have copied file to bin folder of jdk.

command to extract the .java file is
jad -sjava filename.class" 


How to write Windows Registry using Java code/program?

I searched so many site to write Windows Registry using java code/program but there is not any good information available on internet. I came with new API javaQueryAPI that will help you to write windows Registry using java code.

Important notice for existing user ( javaQueryAPI 7.0 or less ) : 
Thanks for using javaQueryAPI bundle. I've made major changes in javaQueryAPI 8.0 so don't import this bundle if you don't want to change the code of your code. Many classes exist in javaQueryAPI 7.0 will no longer available in javaQueryAPI 8.0. I'm going to give you code snippet for existing and new javaQueryAPI.

/*
* javaQueryAPI 7.0 or less
* method : (RKey,path,keyType,Name,Value);
* RKey : Root key (folder) to create the registry. (i.e : HKEY_CURRENT_USER )
* path : Folder path of your software or existing folder that must starts with (\\). (i.e : \\software\\microsoft)
* keyType : Its a keyType that you want to create DWORD,String,Binary.
* Name : Name of key.
* Value: Value of key.
*/
import javaQuery.core.Rkey;
import javaQuery.core.keyType;
public class jqRegDemo {
    public static void main(String[] args) {
        jqReg _jr = new jqReg();
        String message = _jr.jqReg(RKey.HKEY_CURRENT_USER, "\\jqReg",keyType.Dword, "test","00000320");
        System.out.println("Response: "+message);
    }
}

The above code works for javaQueryAPI 7.0 or less. For new javaQueryAPI 8.0 check out the below code snippet.

/*
* javaQueryAPI 8.0 or above
* method : (RegistryKey,path,keyType,Name,Value);
* RegistryKey : Root key (folder) to create the registry. (i.e : HKEY_CURRENT_USER )
* path : Folder path of your software or existing folder that must starts with (\\). (i.e : \\software\\microsoft)
* keyType : Its a keyType that you want to create DWORD,String,Binary.
* Name : Name of key.
* Value: Value of key.
* javaQueryBundle.createRegistry() is new class created for better use. That allows you to overcome from creating object of class. 
* I prefer you to use IDE so it'll give you better idea of class covered in javaQueryBundle.
*/
import javaQuery.core.Registry;
import javaQuery.importClass.javaQueryBundle;

public class Demo {
    public static void main(String[] args) {
        String response = javaQueryBundle.createRegistry().createKey(Registry.HKEY_CURRENT_USER, "\\jqreg", Registry.key_String_Value, "Software", "javaQueryAPI");
        System.out.println(response);
    }
}

You must follow rules to create new - for existing Registry key:
  1. When you want to change (Default) value give key name as (Default). It'll change default value.
  2. String value = "\\\"javaw.exe\\\" \\\"-jar\\\" \\\"c:\\\\jqEditor\\\\jqEditor.jar\\\" \\\"%1\\\"" this will set value as "javaw.exe" "-jar" "c:\jqEditor\jqEditor.jar" "%1"
  3. If Registry value contains double quote ( " ) then you have to use ( \ ). for example check rule 2.
  4. If Registry value contains forward slash ( \ ) then also you have to use ( \ ). for example check rule 2.
  5. You must have admin rights of system to create Registry.

Check out the http://www.javaquery.com/p/downloads.html for download.

How to execute multiple command in single line in/using Java?

Interacting with shell is essential in certain situation. Say if you want to scan file(s) using antivirus you have to use shell command in java program.

public class cmdtest {
    public static void main(String[] args) {
        try {
            String[] command = new String[3];
            command[0] = "cmd";
            command[1] = "/c";
            command[2] = "f: && dir && cd snap";

            Process p = Runtime.getRuntime().exec(command);

            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            String Error;
            while ((Error = stdError.readLine()) != null) {
                System.out.println(Error);
            }
            while ((Error = stdInput.readLine()) != null) {
                System.out.println(Error);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

command[2] = "f: && dir && cd snap"; will execute three command.

  • - Move cursor in F:\ drive
  • - List all directory of drive
  • - Move cursor in snap directory

Use && in string to use multiple command.

Update
Thanks to @Suri(http://www.javaquery.com/2011/03/how-to-execute-multiple-command-in.html#comment-1524448304) for pointing out the command line execution part that I didn't cover. There are few commands requires user input. Following code demonstrate user input.
public class cmdtest {
    public static void main(String[] args) {
        try {
            /* String array to execute commands */
            String[] command = new String[3];
            command[0] = "cmd";
            command[1] = "/c";
            /* Command you want to execute */
            command[2] = "c: && date && date";

            /* Create process */
            Process p = Runtime.getRuntime().exec(command);

            /* Get OuputStream */
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
            
            /* Read the output of command prompt */
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = reader.readLine();
            /* Read upto end of execution */
            while (line != null) {
                /* Pass the value to command prompt/user input */
                writer.println("08-08-2014");
                System.out.println(line);
                line = reader.readLine();
            }
            /* The stream obtains data from the standard output stream of the process represented by this Process object. */
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            /* The stream obtains data from the error output stream of the process represented by this Process object. */
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            
            String Input;
            while ((Input = stdInput.readLine()) != null) {
                System.out.println(Input);
            }            
            
            String Error;
            while ((Error = stdError.readLine()) != null) {
                System.out.println(Error);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

You need to change the user input depending on your command at writer.println("08-08-2014");. In this example "date" command required date in (mm-dd-yy) format.

How to execute Microsft windows's shell command using/in Java?

Interacting with shell is essential in certain situation. Lets see how you can execute single command using Java program.

public class cmd {
    public static void main(String[] args) {
       try {
                String[] command = new String[3];
                command[0] = "cmd";
                command[1] = "/c";
                command[2] = "msg * www.javaquery.com";

                Process p = Runtime.getRuntime().exec(command);
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                String Error;

                while ((Error = stdError.readLine()) != null) {
                    System.out.println(Error);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }       
    }
}
This is how you can use the java to execute the Shell command. To execute your command change the value in command[2] this will executed in shell and give the output.

Related articles:

How to create zip file of directory using/in Java?

zip
Creating compressed zip using command line. I'm going to demonstrate creating zip using java based windows application.

JFileChooser open = new JFileChooser(); //File chooser
open.setCurrentDirectory(new java.io.File("."));
open.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // Allow to select on directory
option = open.showOpenDialog(ch.getParent());
filename = open.getSelectedFile().toString(); // getting the selected directory path

System.out.println("folder" + filename);
path = filename.replace("\\", "\\\\"); // Replace single / with //
String current_dir_name = open.getSelectedFile().getName(); // getting the selected directory path

try {
      String[] command = new String[3];
      command[0] = "cmd";
      command[1] = "/c";
      command[2] = "zip -r c:\\" + current_dir_name + ".zip " + path;
      /*
       * c:\\current_dir_name.zip is output file
       * path is original dir path
       **/

      Process p = Runtime.getRuntime().exec(command); //it'll execute above array on command line
      /* Standard input reader */
      BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
      /* Standard error reader */
      BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      String Error;

      while ((Error = stdError.readLine()) != null) {
          System.out.println(Error); // It'll print the error if any
      }

      filename = current_dir_name + ".zip";
      path = "c:\\" + filename;
} catch (Exception e) {
      e.printStackTrace();
}
Read further about executing multiple command using java program: How to execute multiple command in single line in/using Java?

How to Open file by double clicking on it in our .jar file?

This article helps desktop application developer in java. If you have application which saves its own file format. You always wanted to handle that file in your application. We use windows registry to handle the request. Let me write the topic that users searches over internet so it'll help them too.

  • How to open my file format in .jar file?
  • How to open file by double clicking on it in our .jar file?
  • Open file in .jar file?
  • Setup our file format extension with our .jar file?

One can have their own file format created through JAVA application but the major challenge is “How to open that file by double clicking on that and it’ll open in our application or in jar file?” Here we comes with the solution follow the below steps and your problem solved.
            So first of all you have decided your file format like we are using (.beta). This is my Personal editor application file format.Now setting up that format. We are working in Windows machine.

Step 1: Open Run. Start>Run or Window key + R

Step 2: Type “regedit” (without double quote).

Create New Key under HKEY_CLASSES_ROOT.

   
Name it with your file format extension. (.beta)
Now Double click on (Default) and change the value to Your_File_FormatFile


Now Create another key under the same path HKEY_CLASSES_ROOT. And name it same as given above Your_File_FormatFile and create other key in hierarchy shown in below image.


To setup your file Icon click on DefaultIcon and setup the icon path check the below image.


Now click on the command and setup your file path (.jar file). Check below image.

   
In image you can see the command as : “javaw.exe” “-jar” “Your .jar file location” “%1”

Don’t change anything else %1 pass your file path to your main method. In public static void main(String args[]) you'll have your file name in args[0].

Now you have to handle your file in main method. In main method do some work that handle your file like open it in text area or something as like you open it from the file open.

Difference between logical operators in Java.

We all using logical operators in programming language but still some of you don't know difference between " | "(Single OR) and " || "(Double OR) like wise for " & ". Lets take a look on below code.

package com.javaquery.examples;
public class logical_opr {
     public static void main(String[] args) {
        int x = 2, y = 5;
        if(++x > 2 | ++y > 3){
            System.out.println("Value of X:"+x +" Value of Y:" +y);
        }
        x = 2 ;
        y = 5 ;
        if(++x > 2 || ++y > 3){
            System.out.println("Value of X:"+x +" Value of Y:" +y);
        }
    }
}
/*
Output:
Value of X:3 Value of Y:6
Value of X:3 Value of Y:5 //Value of Y is not changed in " || ".
*/

When we use "|" in program it'll check both the condition where in "||" the program checks for the first condition and if it satisfy the logic for "||" it'll not waste time to check next condition and go to next code.

- Use of " & " and  " && " is same like above. When we use " && " if first condition is FALSE then it'll not check second condition and save time.

Alternative of 'for loop' in Java

This is something out of the box from regular programming taught in our colleges. I don't know about other countries but in India colleges don't teach programming like this.

Alternative of for loop is called for-each. Lets checkout program...

public class forEach{
 public static void main(String args[]){
  String array[] = {"Vicky","Chirag","Heer"};
  for(String Name : array){
   System.out.println(":"+Name);
  }
 }
}
/** 
  * Output:
  * :Vicky
  * :Chirag
  * :Heer
  */

It will iterate any array till it gets data. Its helps when array generated with dynamic size. Its simple as that. Happy coding...

Difference between creating object of class and extending class?

Java
Lets understand the difference between creating object of class and extending class. It'll be much better if I explain this logic with real codes.

Creating object of class
class superclass{
 private void display(){
  System.out.println("Super Class");
 }
}
public class subclass{
 public static void main(String args[]){
  superclass sup = new superclass();
  sup.display();
 }
}
Creating object of any class holds definition of its inner methods. Whether its public, private or any other identifier.

When you try to compile above code using command line. It'll show error as follow. If you are working in some IDE like netbeans or eclipse. IDE it self shows the error before compile.
subclass.java:9: display() has private access in superclass
  sup.display();
     ^
1 error

Extending class
class superclass{
  private void display(){
    System.out.println("Super Class");
  }
}
public class subclass1 extends superclass{
  public static void main(String args[]){
    display();
  }
}

When you extend any class it can't find definition of its inner methods. It'll show error as follow.
subclass1.java:8: cannot find symbol
symbol  : method display()
location: class subclass1
    display();
    ^
1 error

How to compile and execute java package program?


What is Package?
Phenomenon behind creating package is very good for developer. In a simple language we can say that "Package" helps us to categorize our code in different folders. Lets say if you are creating some application and it has two different logic for code.

  • Validate inputs of program
  • Database transaction

Place validation code in package called "myApp.validate" and the code that work around database transaction put it in "myApp.Database". It makes easy to find your program when you want to modify. All major companies follow the package staructure that helps all developer to work faster.


Checklist
  • package package_name must be first line of program as written in below code.
    eg. package com.javaquery.examples;

package com.javaquery.examples;

public class HelloWorld{
    public static void main(String args[]){
       System.out.println("Hello World!");
    }
} 

Compile and Run

  • Compile using : javac -d . Helloworld.java. While compiling . dot followed by -d is required.
  • Execute using : java com.javaquery.examples.Helloworld>
Note: Here -d argument generates directory as per the package declared

What is public static void main(String args[]) in Java?

Transparent Java Logo

What is Java?
Java is most reliable programming language in IT sector. Java is now used by wide range of devices like Samsung, Nokia, etc... The best example of Java is Android. Android is Mobile Operating system built in Java(UI). Dr. James Gosling and his team invented Java in Sun Microsystem.

Why "public static void main" in Java Program?
If you are beginner then you must know. If any program has  "public static void main(String args[])" in program then its executable program. Lets understand why we write it. Assume below scenario and lets have class "demo".
class demo{
    public static void main( String args[]){
         System.out.println("Hello, World!");
    }
}
// Output - Hello, World!
Now lets use the above program without "public"
/* Code will compile but will give you runtime error. */
class demo{
    static void main( String args[]){
         System.out.println("Hello, World!");
    }
} 
// Error: Main method not public

Reason to declare main method as a public
  • javac demo.java command generates the demo.class file.
  • java demo (when user run this command JVM find the "main" method in demo.class file but as we didn't declare it as a public. It means main method is not allowed to access publically.) Declaring any method as public allow other method to call it inside and outside of class as well.

Reason to declare main method as a static
As you know to access any method you must have an object of that method. "static" keyword allows JVM to access method without creating object. Below example shows how static used.
class x{
    static int temp=10;
}
class demo{
    public static void main( String args[]){
         System.out.println("Hello, World!");
         x.temp=20;
         System.out.println(x.temp);
    }
}      
/* We are using "temp" variable of class "x" without creating object of class. */

void
void keyword tell that main method doesn't return any value.

main(String args[])
Program starts execution from here. Main method have argument in String array. So you can pass values in program at run time.