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

Saturday, August 14, 2010

Apache Derby - as Embedded Database

The most convenient part for Apache Derby is it can be an embedded database in JVM. When JVM starts, database starts as well, when JVM shutdown database shutdown as well. it's lightweight, portable and easy to embedded to any application.


Following are steps that how you create test application in Eclipse with Apache Derby DB embedded.
Download Apache Derby from web and extract it to folders you prefer.

Create project and include all jar files in derby lib folder.


Copy SimpleApp.java (under demo/program/simple folder) to project src folder and run it. you will get simliar console output, which means derby is successfully installed and executed.

Monday, July 26, 2010

Find Kth smallest in a given integer array java

public int findksmallest(int[] array, int k) throws Exception {
  if (k <= array.length && k > 0) { 
   for( int i =0 ; i < k ;i++){
          for ( int j = i+1 ; j< array.length ; j++){
              if(array[j] < array[i]){
               int tmp = array[i];
               array[i] = array[j];
               array[j] = tmp;
              }
          }
   }
  }else{
   throw new Exception("k is an invalid number");
  }
  return array[k-1];
 }

Sunday, July 25, 2010

Palindrome Checker in Java

public static boolean isPalindrome(String input){
  boolean result = true;
  for(int i = 0 ; i < input.length() / 2 ; i++ ){
   if(input.charAt(i) != input.charAt(input.length()-(i+1))){
    result = false;
   }
  }
  return result;
 }

Saturday, July 24, 2010

Simple Queue Implementatino in Java

public class BoundedIntQueue {
int[] queue;
int startIndex;
int endIndex;
int size;
public BoundedIntQueue(int queueSize) {
queue = new int[queueSize];
startIndex = 0;
endIndex = 0;
size = 0;
}

public int dequeue() throws Exception{
int result = 0;
// check if queue is empty, throw exception if empty
if(size<=0){
throw new Exception("Queue Empty");
}else{
// dequeue element in queue, if queue is not empty
result = queue[startIndex];
adjustStartIndexAfterDequeue();
size--;
}
return result;
}

private void adjustStartIndexAfterDequeue(){
startIndex++;
if(startIndex >= queue.length)
startIndex = 0;
if(startIndex < 0)
startIndex = queue.length -1;
}    

public void enqueue(int x) throws Exception{
// check if queue is full, throw exception if full
if(size >= queue.length){
throw new Exception("Queue Full");            
}else{
// insert element in queue, if queue is not full
queue[endIndex] = x;
adjustEndIndexAfterEnqueue();
size++;
}
}

private void adjustEndIndexAfterEnqueue(){
endIndex++;
if(endIndex < 0)
endIndex = queue.length -1;
if(endIndex >= queue.length)
endIndex = 0;
}
}