Thursday, March 31, 2016

Execute a java program without a main() method?


Up to and including Java 6 it was possible to do this using the Static Initialization Block 

For instance using the following code:
public class Foo {
    static {
         System.out.println("Message");
         System.exit(0);
    } 
}

The System.exit(0) lets the program exit before the JVM is looking for the main method,
otherwise the following error will be thrown:

Exception in thread "main" java.lang.NoSuchMethodError: main

Sequence is as follows:
·         jvm loads class
·         executes static blocks
·         looks for main method and invokes it

In Java 7, however, this does not work anymore, even though it compiles, the following error will appear when you try to execute it:

The program compiled successfully, but main class was not found. Main class should contain method: public static void main (String[] args).
Here an alternative is to write your own launcher, this way you can define entry points as you want.
In the article JVM Launcher you will find the necessary information to get started:


This article explains how we can create a Java Virtual Machine Launcher (like java.exe or javaw.exe). It explores how the Java Virtual Machine launches a Java application. It gives you more ideas on the JDK or JRE you are using. This launcher is very useful in Cygwin (Linux emulator) with Java Native Interface. This article assumes a basic understanding of JNI.

Sunday, March 20, 2016

Why only String[] as parameters in main() method ?

Why the main method in java is having argument of only String[] . Why can't it be anything else (ex int[], char[]) ?.

I could think of below 5 reasons why String[] arguments and not any other parameters

1) It’s the JVM which calls main() and JVM receives parameters as strings from I/O or frm OS, hence the same signature. By default , JVM support only String.

2) Because that's the way it was designed. Yea, I know that's a circular reason. But the point is that this is the way it is and it ain't going to change. So unless you are planning on designing your own language, the question is moot.

3) Cleanness of design (aka the DRY principle). Don't specify two entry point signatures when one can do the job. And clearly, it can.
A String[] can be represented as Char, Int, Boolean which sounds fair but not vice-versa.

4) Semantic simplicity. Suppose (hypothetically) that Java did support both void main(String[]) and void main() entry points. What would happen if a class defined both methods? Is that an error? If not, which one takes precedence when there is ambiguity? Is this confusing yet?
By only allow void main(String[]), the JLS avoids the problem.


5) This is analogous to the standard C and C++ entrypoint signatures. (Admittedly, some C / C++ runtimes support other non-standard entrypoints as well ... but that's not exactly a good thing ... IMO.)

Feel free to comment below if you think of any other reason.

Wednesday, March 16, 2016

Remove Duplicate Elements from an Array.

Remove Duplicate Elements from Array              

a)     Using unique property of Sets which makes problem quite simple.
It is much better than second approach.

b)    Interviewers are more emphasized on second approach as it requires some tricky coding skills.

public class RemoveDuplicateElements {

static int array[] = new int[] { 10, 20, 30, 10, 15, 40, 30, 10, 20, 90, 50 };

     public static void main(String[] args) {
           // Using In-Build Collection API
           System.out.println("Using Approach 1");
           Approach1(array);

           // Using Code approach. Asked in Flipkart interview...
           System.out.println("Using Approach 2");
           Approach2(array);
     }

       // Prefer LinkedHashSet instead of HashSet so as to maintain order

public static void Approach1(int array[]) {
           Set<Integer> set = new LinkedHashSet<Integer>();

           for (int i = 0; i < array.length; i++)
           set.add(array[i]);
           Object[] objectArray = set.toArray();
          
     for (int i = 0; i < objectArray.length; i++)
           System.out.print(objectArray[i] + "\t");
           System.out.println();
     }

     // Replacing duplicate value with last value and decrement the size

     public static void Approach2(int[] array) {
           int sizeArray = array.length;
           for (int i = 0; i < sizeArray; i++) {
                for (int j = i + 1; j < sizeArray; j++) {
                     if (array[i] == array[j]) {
                           array[j] = array[sizeArray - 1];
                           sizeArray--;
                     }
                }
           }
           int newArray[] = Arrays.copyOf(array, sizeArray);
           for (int i = 0; i < newArray.length; i++)
                System.out.print(newArray[i] + "\t");
     }
}

Wednesday, March 9, 2016

How to Schedule a Job in Java in 3 easy steps.

How to Schedule a Job just like CronJob (in Java) in 3 easy steps ?

1)     Include Quartz dependency in pom.xml
<dependency>
           <groupId>opensymphony</groupId>
           <artifactId>quartz</artifactId>
           <version>1.6.3</version>
</dependency>

2)     Create a Job which needs to be run after fixed interval

import org.quartz.Job;
import org.quartz.JobExecutionContext;

public class TesttJob implements Job {
public void execute(JobExecutionContext context) {
System.out.println("Test Job running successfully");
}
}

3)     Create a CronTrigger which creates job object, trigger object and schedule it at the fixed interval.

public class CrontTriggerJob {
private static JobDetail testJob = null;
private static CronTrigger testTrigger = null;
    
public static void main(String[] args) throws ParseException, SchedulerException {

testJob = new JobDetail("dummyJobName","quartzJobGroup",TesttJob.class);

// Run after every 5 minutes        
testTrigger= new  CronTrigger("dummyCrontName","quartzJobGroup","0/5 * *   * * ?");
          
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(testJob, testTrigger);
}
}

Monday, March 7, 2016

How to run a task Concurrently using Timer Class

How to run a task concurrently?

package com.javaetutorials;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/* Scheduler Task :
 * How to run a task periodically in Java
To execute a method between a regular interval of time.*/

class ScheduledTask extends TimerTask {

     Date now; // to display current time
     // Add your task here
     public void run() {
          now = new Date(); // initialize date
          System.out.println("Time is :" + now);
     }
}

// Run Scheduled task
public class TimerApp {
     public static void main(String[] args) {
          Timer timer=new Timer();
          ScheduledTask sTask= new ScheduledTask();
          timer.schedule(sTask, 0, 2000);
     }
}

Output :

Time is :Tue Mar 08 00:11:15 IST 2016
Time is :Tue Mar 08 00:11:17 IST 2016
Time is :Tue Mar 08 00:11:19 IST 2016
Time is :Tue Mar 08 00:11:21 IST 2016

It keeps running until it comes with a terminate condition like System.exit(0)

Snippet of Timer class:

public class Timer {
     private final TaskQueue queue;
     private final TimerThread thread;
     private final Object threadReaper;
     private static final AtomicInteger nextSerialNumber = new AtomicInteger(0);


Snippet of TimerTask :

abstract class TimerTask implements Runnable {
     final Object lock = new Object();
     int state = 0;
     static final int VIRGIN = 0;
     static final int SCHEDULED = 1;
     static final int EXECUTED = 2;
     static final int CANCELLED = 3;