Sunday, October 17, 2010

Bubble Sort Example using Char (Java)

In this post, I am giving an example about implementing Bubble Sort in Java using characters as data types.

import java.io.* ;


public class BubbleSort {

public static void main (String args[]) {
String stringarray = "fgjhsflsdlkfghdksdkjdgskakdkfkjggkdkgjg";

int i, j;
i = j = 0 ;
char temp ;
int arrsize = 0 ;
int strsize = stringarray.length() ;
char strarray[] = new char[50] ;
System.out.println("Str array length: " + strsize) ;
System.out.println("Str array: " + stringarray) ;
for (int a = 0 ; a < strsize ; a++) {
strarray[a] = stringarray.charAt(a) ;
arrsize++ ;
}
System.out.println("char array length: " + arrsize) ;

//Bubble Sort code

for(i=0; i< (arrsize - 1); ++i) {

for(j = i + 1; j > 0; --j) {
if(strarray[j] < strarray[j-1]) {
//Swaps the values
temp = strarray[j];
strarray[j] = strarray[j - 1];
strarray[j - 1] = temp;
}
}
}
System.out.print("Values: " ) ;
for (int b = 0 ; b < strsize ; b++) {
System.out.print(strarray[b]) ;
}
}

}


Output:

Example for Capturing Transaction Time using currentTimeMillis() method (Java)

In this post, I am giving an example for Capturing Transaction Time using currentTimeMillis() method using Java.

import java.io.* ;

public class CalculateSystemTxTime {

 public static void main (String args[]) {

// Calculate Start time
      double startTime = System.currentTimeMillis();
      System.out.println("Timer is Started") ;

// Performing somekind of transaction.
// Here, 1000 iterations are used as transaction.
    
      int i = 500;

for (int j = 1 ; j <= 1000 ; j++) {
if (j == i)
System.out.println("The number is incremented upto the random number generated.") ;

}

// Calculate Stop Time
      double stopTime = System.currentTimeMillis();


     System.out.println("Timer is Stopped. Total time for incrementing is: " + (stopTime - startTime) + " sec." );

// Calculating average time
      System.out.println("The average time for each increment is: " + (stopTime - startTime)/1000 + " sec.") ;
}
}


Output:

Steps in Installing Android SDK within Eclipse

In this post, I am giving the steps to easily install Android in Windows 7 and hooking it up with Eclipse.
Installing in Windows XP and Vista is more or less the same.


  1. Download Android SDK from here
  2. Extract the files and store them at any location.
  3. Go to start. Right click on My Computer and go to "properties"
  4. go to "advanced" --> "environment variables" and then to "system variables"
  5. now open "PATH" variable in system environment variables. 
  6. Copy the path where Android is stored from "My Computer".
  7. In "Variable Value" at the end of the existing link, put a semicolon ';' and then paste the path of Android here.
  8. Press "OK" thrice to Come out of "System Properties"
  9. Start Eclipse
  10. Go to "Windows" --> "Android SDK and AVD Manager".
  11. If you are getting any error stating that Preferences is not set, then go to "Windows"  --> "Preferences" --> "Android" and at SDK Location give the path to the location of Android in your system and press "Ok" .
  12. In "Android SDK and AVD Manager" go to "Available Packages in the left pane.
  13. There will be a root link in the right pane referring it to Google Android.
  14. Click the root link and make sure all the Child links are the child links are ticked.
  15. Then click "Install Selected" and then a pane named "Choose Packages to Install" appears.
  16. Click "Accept All" and then "Install" and a menu titled "Installing Archives" appears where all the packages get downloaded and installed.
  17. Sometimes, it takes a while to download and install all the Packages.
  18. Then, it asks permission to to restart ADB. Press "Yes" and after a while press "Ok".
  19. Press "Close".
  20. Close the "Android SDK and AVD Manager".
  21. Sometimes, it may ask to restart Eclipse. That should be "Ok".
Now, Android is installed in your system. To test if Android is successfully installed, go to "File" --> "New" 
--> "Project". In the "New Project" menu, you will find "Android" and in it you will find "Android Project" and "Android Test Project". This ensures that Android is successfully installed.

Welcome to Android! Have Fun!

Cheers!

These following books can be referred for Android all though Google Support is better.

Monday, October 11, 2010

Single Linked List Example using Arrays (Java)

The following program is a Single Linked List data structure using Arrays to store data.

import java.io.* ;

public class SingleList {

String item[] = new String[5] ;
int itemSize = 0 ;
int currentLoc ;

public void addItems (String element) {
if (element != null) {
item[itemSize] = element ;
itemSize++ ;
}
}

public void deleteItems (String element) {
int flag = 0 ;
if (itemSize > 0) {
for (int i = 0 ; i < itemSize ; i++) {
if (item[i] == element) {
 flag = 1 ;
 currentLoc = i ;
 break ;
 }
 }
 if (flag == 0)
 System.out.println("No such element to delete such as '" + element + "'") ;
 else if (flag == 1) {
 for (int i = currentLoc + 1 ; i < itemSize ; i++) {
 item[currentLoc] = item[i] ;
 currentLoc++ ;
 }
 itemSize-- ;
 System.out.println("'" +element+ "' element is deleted") ;
 }
 }
 }

 public void viewItems() {
 if (itemSize > 0) {
System.out.println("The elements in the Single Linked List are: ") ;
for (int i = 0 ; i < itemSize ; i++ ) {
System.out.print(item[i] + " ") ;
}
System.out.println() ;
}
}


public static void main (String a[]) {

SingleList s = new SingleList() ;

s.addItems("a") ;
s.addItems("b") ;
s.addItems("c") ;
s.viewItems() ;

s.deleteItems("b") ;
s.viewItems() ;

s.addItems("d") ;

s.addItems("e") ;

s.deleteItems("s") ;
s.viewItems() ;


s.deleteItems("a") ;
s.viewItems() ;

s.addItems("f") ;
s.viewItems() ;

s.deleteItems("a") ;
s.viewItems() ;

s.addItems("g") ;
s.viewItems() ;

s.deleteItems("c") ;
s.viewItems() ;

s.addItems("h") ;
s.viewItems() ;
}

}

Creating and inserting data into a Text File Example (Java)

In this post, I am giving the code for creating a file and inserting text into it.


import java.io.*;;
import java.util.*;

public class InsertDataToFile {

public static void main(String[] args) {
try {
File makefile = new File("sampleFile.txt");
FileWriter fwriter = new FileWriter(makefile);
fwriter.write("The text is ");
fwriter.write("entered and ");
fwriter.write("displayed here.");
fwriter.flush();
fwriter.close();
System.out.println("File is created and text is inserted!");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

String Comparison Methods (Java)

The following determines the functions for comparing Strings in Java

String s = "String_1", t = "String_2";
if (s == t) // it usually will not match
if (s.equals(t)) // this is the right way
if (s.compareTo(t) > 0) // this is also correct>

Iterator Function Example (Java)

The following is an example of using the Iterator function with the help of Array List.

The Iterator function automatically increments each and every element one at a time.


import java.io.* ;
import java.util.* ;
import java.util.Iterator ;
class IteratorExample {

public static void main (String []a) {

// creating an array list and adding elements to it
ArrayList ar = new ArrayList() ;
ar.add("a1") ;
ar.add("a") ;
ar.add("1") ;

//using iterator to display the elements in the array list
Iterator it = ar.iterator() ;
while (it.hasNext()) {
Object elements = it.next() ;
System.out.println(elements) ;

}

}

}

Random function (Java)

To use the random function, we need to import
import java.util.Random ;
or
import java.util.* ;

and then we need to create the constructor as follows:

Random r = new Random() ;

and then we can use the datatype as follows:
int i = r.nextInt(int n) between 0 to n
int i = r.nextInt() all integers
long l = r.nextLong() all long
float f = r.nextFloat() between 0.0 and 1.0
double d = r.nextDouble() between 0.0 and 1.0
boolean b = r.nextBoolean() either true or false

Queue Example using Integers (Java)

The following program contains code, how to write a queue data structure for an integer datatype.


import java.io.*;

class IntegerQueue {

public static void main (String args []) {
QueueOperation q = new QueueOperation() ;
q.insert(10);
q.insert(20);
q.insert(30);
q.insert(40);
q.insert(50);
q.insert(60);
q.insert(70);
q.insert(80);

}

}

class QueueOperation {

static int queueArray [] = new int [5] ;
int i = 0 ;

public void insert (int num) {

if (i < 5 ) {
queueArray[i] = num ;
i++ ;
System.out.println("The queue contains: ");
for (int a = 0 ; a < i ; a++)
System.out.println(queueArray[a]) ;
}
else {
for (int b = 0 ; b < i - 1 ; b++) {
queueArray[b] = queueArray[b + 1] ;
}
queueArray[i - 1] = num ;
System.out.println("The queue contains: ");
for (int a = 0 ; a < i ; a++)
System.out.println(queueArray[a]) ;
}

}

}

Stack Example using Integers (Java)

The following program contains code, how to write a stack data structure for an integer datatype.

public class IntegerStack {

public static void main(String []a) {

Elements e = new Elements () ;

e.push (50) ;
e.push (500) ;
e.push (150) ;
e.pop();
e.push(10);
e.pop();
e.push (100);
e.pop();
e.pop();
e.pop();
e.pop();

}

}


class Elements {

int stackArray[] = new int[5] ;
int i = 0;

public void push (int num) {

if (i < 5) { stackArray[i] = num; i++; System.out.println ("Stack contains :"); for (int a = 0; a < i; a++) System.out.println(stackArray[a]); } else System.out.println("Stack is full."); } public void pop () { if (i > 0) {
int remNum = stackArray[i] ;
i--;
System.out.println ("Stack contains :");
for (int a = 0; a < i; a++)
System.out.println(stackArray[a]);
}
else
System.out.println("Stack is empty.");
}

}

Reading data from file (Java)

In this post, I am explaining about how to read data from the file.


import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class fileDemo {

fileDemo f = new fileDemo() ;

public static void main(String args[]) {
try {
// opening the file and creating a command line argument
FileInputStream fstream = new FileInputStream("file_name.txt") ;
//Creating a object for the data input stream
DataInputStream in = new DataInputStream(fstream) ;
BufferedReader br = new BufferedReader(new InputStreamReader(in)) ;
String sdata = null ;
while ((sdata = br.readLine()) != null) {
System.out.println(sdata) ;
// checking if the line read is the start of the record or not
}
in.close() ;
}
catch (Exception e) {
e.getMessage() ;
}
}

}

The class path can be given at the unless the file that has to be read is present in the same location as the program.

The file format can be of any type that is read by a word editor.

Split Function (Java)

This function is used to break a string into multiple sub strings using a particular special character as a delimiter.

String str = "i-am-a-good-boy";
String[] temp;
String delimiter = "-";
temp = str.split(delimiter);

String Tokenizer Function (Java)

String Tokenizer is a java function which is used to divide a string using space to split the string.

StringTokenizer st = new StringTokenizer(temp) ;
String iRes[] = null ;
for(int o = 0 ; st.hasMoreTokens() ; o++) {
iRes[o] = st.nextToken() ;
iRes[o] = iRes[o].trim() ;
}