Saturday, May 13, 2017

Don't Even Think about a Job Interview without Knowing these Sort Algorithms

Sorting is an essential part of working with data today.  Data access and analysis is much less time consuming if the data itself is sorted first.  Unsorted data is very silent while sorted data can be questioned and fast response is possible.  If you want to find the smallest and largest values from an unsorted data, it might take a very long time ( It might be as bad as O(n^2) ), but asking the same question from a sorted data can be as quick as O(1) since you just have to take the first and last element of the sorted structure.  Yes, it takes time and work to sort the data, but that extra work ahead of time, before the question is asked, is more than worth the effort.  Sorting can be accomplished in many different way with different time complexities.



·        Bubble sort
·        Selection sort
·        Insertion sort
·        Merge sort
·        Quick sort

Performance tests must be performed and studied in order to chose the correct one when the time comes.  It is not the time to test when the job needs to be done.

99
N Time:                                   00:00:00:0002
99
N-quare Time:                         00:00:20:20446
99
BubbleSort based Time:          00:00:26:26496
99
SelectionSort based Time:      00:00:04:4924
99
InsertionSort based Time:       00:00:02:2467
99
MergeSort based Time:          00:00:00:0014
99
QuickSort based Time:          00:00:00:0008

Aiming for your dream job will require you to understand the methodology, code, and operational characteristics or these algorithms.  So, spend lots of time analyzing and studying these algorithms and run the code for performance analysis.  This will be one of your greatest assets and skills that will get you your dream job and will allow you to keep your dream job for a long time.

public class BiggestDifference {
    public static void main(String[] args){

        final int SIZE=10000;
        int myArray[]= new int[SIZE];
        initialize(myArray);
        long time=System.currentTimeMillis();
        System.out.println(diffItN(myArray));
        System.out.printf("N Time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
        time=System.currentTimeMillis();
        System.out.println(diffItNN(myArray));
        System.out.printf("N-quare Time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
        time=System.currentTimeMillis();
        System.out.println(diffItNLogN(myArray,"bubble"));
        System.out.printf("BubbleSort based Time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
        initialize(myArray);
        time=System.currentTimeMillis();
        System.out.println(diffItNLogN(myArray,"selection"));
        System.out.printf("SelectionSort based Time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
        initialize(myArray);
        time=System.currentTimeMillis();
        System.out.println(diffItNLogN(myArray,"insertion"));
        System.out.printf("InsertionSort based Time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
        initialize(myArray);
        time=System.currentTimeMillis();
        System.out.println(diffItNLogN(myArray,"merge"));
        System.out.printf("MergeSort based Time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
        initialize(myArray);
        time=System.currentTimeMillis();
        System.out.println(diffItNLogN(myArray,"quick"));
        System.out.printf("QuickSort based Time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
    }

    private static void initialize(int a[]){       
        java.util.Random ran=new java.util.Random();
        for(int i=0;i<a.length;i++){
            a[i]=ran.nextInt(100);
        }
    }

    private static int diffItN(int a[]){
        int largest=a[0];
        int smallest=a[0];
        for(int i=1;i<a.length;i++){
            if(a[i]>largest)
                largest=a[i];
            if(a[i]<smallest)
                smallest=a[i];
        }
        return largest-smallest;
    }

    private static int diffItNN(int a[]){
        int difference = 0,diff=0;
        for(int n1:a){
            for (int n2:a){
                difference = n1 - n2;
                if(difference > diff)
                    diff = difference;
            }
        }
        return diff;
    }

    private static int diffItNLogN(int a[],String s){
        switch(s){
            case "bubble":
                bubbleSort(a);
                break;
            case "selection":
                selectionSort(a);
                break;
            case "insertion":
                insertionSort(a);
                break;
            case "merge":
                mergeSort(a);
                break;
            case "quick":
                quickSort(a,0,a.length-1);
                break;
        }
        return (a[0]>a[a.length-1])?a[0]-a[a.length-1]:a[a.length-1]-a[0];
    }

    private static void bubbleSort( int [ ] num ) {
        int j;
        boolean flag = true;  
        int temp; 
        while ( flag ){
            flag= false;   
            for( j=0;  j < num.length -1;  j++ ) {
                if ( num[ j ] < num[j+1] )   {
                    temp = num[ j ];               
                    num[ j ] = num[ j+1 ];
                    num[ j+1 ] = temp;
                    flag = true;             
                }
            }
        }
    }

    private static void selectionSort ( int []num ){
        int i, j, first, temp; 
        for ( i = num.length - 1; i > 0; i-- ) {
            first = 0;  
            for(j = 1; j <= i; j ++){
                if( num[ j ] < num[ first ] )        
                    first = j;
            }
            temp = num[ first ];  
            num[ first ] = num[ i ];
            num[ i ] = temp;
        }          
    }

    private static void insertionSort(int array[]) { 
        int n = array.length; 
        for (int j = 1; j < n; j++) { 
            int key = array[j]; 
            int i = j-1; 
            while ( (i > -1) && ( array [i] > key ) ) { 
                array [i+1] = array [i]; 
                i--; 
            } 
            array[i+1] = key; 
        } 
        System.out.println();
    } 

    private static void mergeSort(int [ ] a){
        int[] tmp = new int[a.length];
        mergeSort(a, tmp,  0,  a.length - 1);
    }

    private static void mergeSort(int [ ] a, int [ ] tmp, int left, int right){
        if( left < right ){
            int center = (left + right) / 2;
            mergeSort(a, tmp, left, center);
            mergeSort(a, tmp, center + 1, right);
            merge(a, tmp, left, center + 1, right);
        }
    }

    private static void merge(int[ ] a, int[ ] tmp, int left, int right, int rightEnd ){
        int leftEnd = right - 1;
        int k = left;
        int num = rightEnd - left + 1;

        while(left <= leftEnd && right <= rightEnd)
            if(a[left]<a[right])
                tmp[k++] = a[left++];
            else
                tmp[k++] = a[right++];

        while(left <= leftEnd)  
            tmp[k++] = a[left++];

        while(right <= rightEnd)
            tmp[k++] = a[right++];

        for(int i = 0; i < num; i++, rightEnd--)
            a[rightEnd] = tmp[rightEnd];
    }

    private static void quickSort(int a[], int lowerIndex, int higherIndex) {
        int i = lowerIndex;
        int j = higherIndex;
        int pivot = a[lowerIndex+(higherIndex-lowerIndex)/2];
        while (i <= j) {
            while (a[i] < pivot) {
                i++;
            }
            while (a[j] > pivot) {
                j--;
            }
            if (i <= j) {
                exchangeNumbers(a,i, j);
                i++;
                j--;
            }
        }
        if (lowerIndex < j)
            quickSort(a,lowerIndex, j);
        if (i < higherIndex)
            quickSort(a,i, higherIndex);
    }

    private static void exchangeNumbers(int a[],int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    private static String getTime(long millis){
        long second = (millis / 1000) % 60;
        long minute = (millis / (1000 * 60)) % 60;
        long hour = (millis / (1000 * 60 * 60)) % 24;
        return String.format("%02d:%02d:%02d:%04d", hour, minute, second, millis);
    }
}

Monday, May 8, 2017

BigInteger - Size Matters

As numbers get larger, you need to consider storing those values where a 64 bit data type is not enough.  Working with large numbers are fun even if the operators do not work as excepted with small numbers.

Java provides classes like java.math.BigInteger or java.math.BigDecimal to handle large numbers, but it takes some time getting used to.  

You don't just add values by using the plus operator ( + ) , you call methods like add(), multiply(), divide(), subtract() methods.

Comparing values are also a challenge.  You really need to read the API in order to know what to expect. 

compareTo() method documentation - "Compares this BigInteger with the specified BigInteger. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators."

The code below demonstrates the for loop operations using BigInteger.


public class LargeNumbers{
    public static void main(String args[]){
        final java.math.BigInteger NUM=new java.math.BigInteger("10000000");
        //final java.math.BigInteger NUM=new java.math.BigInteger("100000000");
        //final java.math.BigInteger NUM=new java.math.BigInteger("1000000000");
        //System.out.println(NUM.bitCount());  //check to see how many bits are used in the number
        long time=System.currentTimeMillis();
        System.out.println(calc(NUM));
        System.out.printf("Time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
    }

    //iterative recursion
    public static java.math.BigInteger calc(java.math.BigInteger n) {
        java.math.BigInteger result =new java.math.BigInteger("1");
        for (java.math.BigInteger t=n; t.compareTo(new java.math.BigInteger("1")) != 0; t=t.subtract(new java.math.BigInteger("1")))
             result = result.add(t);

        return result;
    }

    private static String getTime(long millis){
        long second = (millis / 1000) % 60;
        long minute = (millis / (1000 * 60)) % 60;
        long hour = (millis / (1000 * 60 * 60)) % 24;
        return String.format("%02d:%02d:%02d:%04d", hour, minute, second, millis);
    }

}

Sunday, May 7, 2017

Head or Tail, Who the Factorial Cares?

Based on the blog post http://www.drdobbs.com/jvm/tail-call-optimization-and-java/240167044
the obvious question came up to see if the performance really noticeable and worth worrying about.  It seems that Oracle does not really concerned about the issue.  In this case, it is not the speed of the algorithm that is an issue, but the limited size of the stack that needs to be used in an optimized manner in order to avoid stack overflow condition.  Based on the code below, my tests show head recursion performs a little bit better than the suggested tail recursion ( when the StarkOverflowError is thrown ).  Over all, it seems like the glory goes to iterative recursion method and not head or tail argument. 

Note: I know that factorial is not what this code is testing, multiplication rises much too fast, so it was replaced, on purpose, by addition operations.


public class TestUtilization{
    public static void main(String args[]){
        final long NUM=5350;    //tailFactorial becomes unstable around 5250-5300, headFactorial 5300-5350
        long time=System.currentTimeMillis();
        System.out.println(IterativeFactorial(NUM));
        System.out.printf("Iterative implementation  time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
        time=System.currentTimeMillis();
        System.out.println(headFactorial(NUM));
        System.out.printf("Head Factorial  time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));  
        /*time=System.currentTimeMillis();
        System.out.println(tailFactorial(NUM));
        System.out.printf("Tail Call Optimization time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));
         */ 
    }
    //Tail Call Optimization
    public static long tailFactorial (long x){
        if (x == 0)
            return 1;
        return tailFactorial(x,1);
    }
    public static long tailFactorial (long x, long current_factorial){
        if (x == 0)
            return current_factorial;
        return tailFactorial(x - 1, current_factorial + x);
    }
    //head recursion
    public static long headFactorial (long x){
        if (x == 0)
            return 1;
        return x+headFactorial(x-1);
    }
    //iterative implementation
    public static long IterativeFactorial(long n) {
        long result = 1;
        for (long t=n; t > 1; t--)
            result += t;
        return result;
    }
    private static String getTime(long millis){
        long second = (millis / 1000) % 60;
        long minute = (millis / (1000 * 60)) % 60;
        long hour = (millis / (1000 * 60 * 60)) % 24;
        return String.format("%02d:%02d:%02d:%04d", hour, minute, second, millis);
    }
}

Friday, May 5, 2017

ArrayList Processing Performance Test

There are many ways to skin a cat, but only six ways to process an ArrayList.  Thus, let's test the performance of each method.  Run it on your system and let us know about your results. Please, give a basic system info if you post.  Thanks!

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;


public class ArrayListSpeedTest {

    public static void main(String[] args) {
        long time=System.currentTimeMillis();
        ArrayList<String> colors=new ArrayList<>();

        for(int i=0;i<100000;i++){  //create a bunch of items for the list, change the value if needed
            colors.add("Red"+i);
        }

        System.out.printf("Initializing ArrayList time: %20s\n\n",(getTime(System.currentTimeMillis()-time)));   
        time=System.currentTimeMillis();
       
        for(int i=0;i<colors.size();i++);
        //System.out.println(colors.get(i)+" ");
        System.out.printf("Simple for loop: %32s\n",(getTime(System.currentTimeMillis()-time)));   
        time=System.currentTimeMillis();
       
        for(String color:colors);
        //System.out.println(color+" ");
        System.out.printf("Enhanced for loop time: %25s\n",(getTime(System.currentTimeMillis()-time)));   
        time=System.currentTimeMillis();
       
        int i=0;
        while(i++<colors.size());
           //System.out.println(colors.get(i++)+" ");
        System.out.printf("While loop time: %32s\n",(getTime(System.currentTimeMillis()-time)));   
        time=System.currentTimeMillis();
       
        //Iterator - hasNext, next, remove
        Iterator<String> iterator = colors.iterator();
        while(iterator.hasNext())iterator.next();
             //System.out.println(iterator.next()+" ");
        System.out.printf("While loop Iterator time: %23s\n",(getTime(System.currentTimeMillis()-time)));   
        time=System.currentTimeMillis();
       
        //ListIterator - hasNext, next, remove, hasPrevious, previous, add
        ListIterator<String> lIterator = colors.listIterator();
        while(lIterator.hasNext())lIterator.next();
             //System.out.println(lIterator.next()+" ");
        System.out.printf("While loop ListIterator time: %19s\n",(getTime(System.currentTimeMillis()-time)));   
        time=System.currentTimeMillis();
        //Java 8 Stream
        colors.forEach((color)->{});
               //System.out.println(color+" ");});
        System.out.printf("ForEach Stream time: %28s\n",(getTime(System.currentTimeMillis()-time)));   
        time=System.currentTimeMillis();
       
        String name="\n6 Ways to process an ArrayList and speed performance test by Zoltan Szabo";
        name.toUpperCase().chars().forEach(s->{
            System.out.print((char)s);
        });
    }
   
    private static String getTime(long millis){
        long second = (millis / 1000) % 60;
        long minute = (millis / (1000 * 60)) % 60;
        long hour = (millis / (1000 * 60 * 60)) % 24;
        return String.format("%02d:%02d:%02d:%04d", hour, minute, second, millis);
}
}

Saturday, March 25, 2017

Generic - Getting Started

Generic classes can be a challenge to learn for the beginning programmer, so in this post I'll try to help you get started with the concept.

Start with a simple program like every language's favorite first project, "Hello World".

Now, think about the concept of displaying something simple from a class based on a parameter like:
Hello World
Hello 2017
Hello 2017.03
Hello W

As you can see we just need to do something simple and only one part of the output is modified from String to int, float, and finally char data types.  Thus, we would need to write 4 different classes for each data type.  But what if we could create a generic class that would adjust to data type based on the type we'll send to the constructor.  That is exactly why generics are so valuable in programming.

So, Let's get started with a simple object oriented implementation of Hello World.

public class Hello{
    private String message;
    public Hello(String message){
           super();
           this.message=message;
    }
    public String getMessage(){
           return message;
    }
}

public class HelloGeneric{
    public static void main(String[] args){
               Hello myMessage = new Hello("World");
               //imagine it this way, Hello myMessage = new Hello(new String("World"));
               System.out.println("Hello "+myMessage.getMessage());
    }

}

Now, that you have a simple class, you can see that by changing the data type for message will all we need to do in  order to create the same class for the other types.

Integer based class would become:
public class Hello{
     private int message;
     public Hello(int message){
           super();
           this.message=message;
     }
     public int getMessage(){
           return message;
     }
}

Floating point base class would become:

public class Hello{
       private float message;
       public Hello(float message){
           super();
           this.message=message;
      }
      public float getMessage(){
           return message;
      }
}

and Character based class would become:

public class Hello{
      private char message;
      public Hello(char message){
           super();
           this.message=message;
      }
      public char getMessage(){
           return message;
      }
 }

Therefore, we should use a Generic class instead to implement this application.  You just have to think about the primitives as objects, so you will be using their wrapper classes when instantiating.  For int, use Integer; for float use Float, and for char use Character.



/** Generic class 
public class Hello<T>{
     private T message;
    public Hello(T message){
           super();
           this.message=message;
    }
    public  T getMessage(){
           return message;
    }
}


The driver for the Generic class looks like this.  Notice the object instantiations when invoking the constructor with parameter.

public class HelloGeneric{
    public static void main(String[] args){

        System.out.println("Hello "+new Hello<String>("World").getMessage());
        System.out.println("Hello "+new Hello<Integer>(2017).getMessage());
        System.out.println("Hello "+new Hello<Float>(2017.03f).getMessage());
        System.out.println("Hello "+new Hello<Character>('W').getMessage());
    }
}


As you can see, we replaces the data type specific keywords with an element "T" representation instead.

By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
    The most commonly used type parameter names are:
      *    E - Element (used extensively by the Java Collections Framework)
      *    N - Number
      *    T - Type ( As you can see, all occurrences of Object are replaced by T.
            A type variable can be any non-primitive type you specify: any class type,
            any interface type, any array type, or even another type variable. )
      *    V - Value
      *    S,U,V etc. - 2nd, 3rd, 4th types

Many developers use the terms "type parameter" and "type argument" interchangeably, but these terms are not the same. When coding, one provides type arguments in order to create a parameterized type. Therefore, the T in Foo<T> is a type parameter and the String in Foo<String> f is a type argument.

So, play with the above code until you can create it without looking at my code and you understand this simple, but powerful concept.

Now, here is another simple, but more involved example to help you with your journey of learning. et's start with the UML of the example so you can see the basic design concepts.

So, this way, you can see an example that uses generic methods, interface, inheritance, and instantiation of these classes.  I hope, this will help.  Here is the source code.

/**
 * Generic version of Zoltan class.
 * @param <T> the type of value being boxed
 */

public class Zoltan<T> {

    private T value; // T stands for "Type"         
 /**
  * Zoltan class's setter method
  * @param value Is the data type that was invoked when the object was instantiated
  */

    public void set(T value) {
        this.value = value;
    }
 /**
  * Zoltan class's getter method
  * @return Data type is the same that was used when the object was instantiated.
  */

    public T get() {
        return this.value;
    }
}


public class Inherited<K,V> extends OrderedPair<K,V>{
    // instance variables - replace the example below with your own
    private int myValue;
    /**
     * Constructor for objects of class Inherited
     */

    public Inherited(K key,V value){
        super(key,value);
        // initialise instance variables
        myValue = 0;
    }
    public int getMyValue(){
        return myValue;
    }
}


public class OrderedPair<K, V> implements Pair<K, V> {
    protected K key;
    protected V value;
    public OrderedPair(K key, V value) {
    this.key = key;
    this.value = value;
    }
    public K getKey()    { return key; }
    public V getValue() { return value; }
}


 public interface Pair<K, V> {
    public K getKey();
    public V getValue();
}


public class ZoltanDemo {
    public static <U> void addZoltan(U u, java.util.List<Zoltan<U>> boxes) {

        Zoltan<U> box = new Zoltan<>();  //this is allowed now
        box.set(u);
        boxes.add(box);
  }
       public static <U> void outputZoltans(java.util.List<Zoltan<U>> boxes) {
       int counter = 0;
       for (Zoltan<U> box: boxes) {
             U boxContents = box.get();
       System.out.println("Zoltan #" + counter + " contains [" + boxContents.toString() + "]");
       counter++;
    }
  }
      public static void main(String[] args) {
              java.util.ArrayList<Zoltan<Integer>> listOfIntegerZoltans = new java.util.ArrayList<>();
              ZoltanDemo.<Integer>addZoltan(Integer.valueOf(10), listOfIntegerZoltans);
             ZoltanDemo.addZoltan(Integer.valueOf(20), listOfIntegerZoltans);
            ZoltanDemo.addZoltan(Integer.valueOf(30), listOfIntegerZoltans);
            ZoltanDemo.outputZoltans(listOfIntegerZoltans);
            OrderedPair<String,Zoltan<Integer>> p=new OrderedPair<>("primes",new Zoltan<Integer>());
           p.getValue().set(2017);
           System.out.println(p.getKey()+" and "+p.getValue().get());
           Inherited testInherit=new Inherited<String,Integer>("Zoltan",2017);
           System.out.println(testInherit.getKey()+" and "+testInherit.getValue());
  }
}



Friday, March 24, 2017

Start Performance Testing - Array vs. ArrayList

What is you observation after running this code?  Post your results including Operating System, Hardware info, and Java version that you've used.


public class Array_PerformanceTest{
    public static void main(String args[])throws java.io.FileNotFoundException,InterruptedException{
        final int arraySize=Integer.parseInt(args[0]);
        int testArray[]=new int[arraySize];
        System.out.printf("All arrays use size: %,d",arraySize);
        System.out.println("                                hr: m: s:  ms");
        long time=System.currentTimeMillis();
        for(int index=0;index<arraySize;index++)
             testArray[index]=index;
        System.out.printf("Initializing array time: %20s\n",(getTime(System.currentTimeMillis()-time)));    
        time=System.currentTimeMillis();
        int result=sequentialSearch(testArray,arraySize-1);
        System.out.printf(" Sequential search time: %20s\n",(getTime(System.currentTimeMillis()-time)));
       

        time=System.currentTimeMillis();
        binarySearch(testArray,arraySize-1);
        System.out.printf("     Binary search time: %20s\n",(getTime(System.currentTimeMillis()-time)));
       
        java.util.Random rand=new java.util.Random();
       
        for(int index=0;index<arraySize;index++)
             testArray[index]=rand.nextInt(arraySize);
       
        time=System.currentTimeMillis();
        selectionSort(testArray);
        System.out.printf("    Selection sort time: %20s\n",(getTime(System.currentTimeMillis()-time)));
       
        java.util.ArrayList<String> list = new java.util.ArrayList<String>(arraySize);
        time=System.currentTimeMillis();
        for(int index=0;index<arraySize;index++)
               list.add(0, "Mary"+rand.nextInt(arraySize));
        System.out.printf("    Arraylist fill time: %20s\n",(getTime(System.currentTimeMillis()-time)));
       
        System.out.println();   

    }

    private static int sequentialSearch(int[] array, int value){
        int index,element;
        boolean found;  // Flag indicating search results
        index = 0;
        element = -1;
        found = false;
        while (!found && index < array.length) {
            if (array[index] == value) {
                found = true;     // Indicate the value is found.
                element = index;  // Save the subscript of the value.
            }
            index++;
        }
        return element;
    }

    private static void selectionSort(int[] array){
        int startScan, index, minIndex, minValue;
        for (startScan = 0; startScan < (array.length-1); startScan++) {
            minIndex = startScan;
            minValue = array[startScan];
            for(index = startScan + 1; index < array.length; index++) {
                if (array[index] < minValue) {
                    minValue = array[index];
                    minIndex = index;
                }
            }
            array[minIndex] = array[startScan];
            array[startScan] = minValue;
        }
    }

    private static int binarySearch(int[] array, int value){
        int first,last,middle,position;
        boolean found;   // Flag
        first = 0;
        last = array.length - 1;
        position = -1;
        found = false;

        while (!found && first <= last) {
            middle = (first + last) / 2;    // Calculate mid point
            if (array[middle] == value) {
                found = true;
                position = middle;
            }
            else if (array[middle] > value) // If value is in lower half
                last = middle - 1;
            else
                first = middle + 1;          // If value is in upper half
        }
        return position;
    }
   
    private static String getTime(long millis){
            long second = (millis / 1000) % 60;
            long minute = (millis / (1000 * 60)) % 60;
            long hour = (millis / (1000 * 60 * 60)) % 24;
            return String.format("%02d:%02d:%02d:%04d", hour, minute, second, millis);
    }
}

Friday, December 9, 2016

Internal resources in Eclipse

Files can be opened from storage devices, but they need a specific path and drive letter, sometimes.  If you are planning to create a runnable jar file created from your project, it is better to access the resources internally from an internal resource path and include them in the runnable jar file.

This simple example demonstrates the process.

1. Create two images with 600x400 dimensions and name them one.jpg and two.jpg.  Store them on your C drive's temp directory for now.
2. Follow the image below to create a new resource folder (1-8) in your project.
3. Import (9) the two image files into the newly created res resource folder.



import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


@SuppressWarnings("serial")
public class FirstGuiApp extends JPanel{
BufferedImage img;

//First try - load images from your hard drive
//String img1 = "c:\\temp\\one.jpg";
//String img2 = "c:\\temp\\two.jpg";

//Second try - load images from internal resource, comment out first step

/*Add project folder res ( add res path to project properties->Build Path->Source)
 * Then, import two jpg images 600x400 named one.jpg and two.jpg
 * */

String img1 = "one.jpg";
String img2 = "two.jpg";
boolean evenClick = false;

public FirstGuiApp(){
setSize(600,400);
setVisible(true);
loadImage(img1);

this.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent me){
if(evenClick){
    loadImage(img1);
    evenClick=false;
    }
else{
    loadImage(img2);
    evenClick=true;
    }
updateUI();
}

});
}//end of FirstGuiApp

private void loadImage(String str){
try{
       //img=ImageIO.read(FirstGuiApp.class.getResource(str)); //one way to load internal resoure
       img=ImageIO.read(getClass().getResource(str)); //preferred way of loading internal resource
       //img=ImageIO.read(new File(str)); //use this with first step to load image from hard drive
     }
catch(IOException e){   e.printStackTrace();  }
}//end of loadImage method

protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(img, 0, 0, 600, 400, this);

}//end of paintComponent

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
              public void run(){
                         JFrame frm = new JFrame();
                         frm.setSize(620,465);
                         frm.setVisible(true);
                         frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                         frm.add(new FirstGuiApp());
                         frm.setTitle("My GUI Application");
                         }//end of run
              }//end of runnable
          );
     }//end of main
}//end of class

Run the program.  The program window should show your image one.jpg and when you click on the image the image two.jpg is loaded alternating between the images. If it does not work, uncomment

//String img1 = "c:\\temp\\one.jpg";
//String img2 = "c:\\temp\\two.jpg";


and 

//img=ImageIO.read(new File(str)); //use this with first step to load image from hard drive

and comment out the following lines to load the images from your hard drive directly for trouble shooting.

String img1 = "one.jpg";
String img2 = "two.jpg";

img=ImageIO.read(getClass().getResource(str)); //preferred way of loading internal resource
 
After you have tested your application, you can then create the runnable jar file.