Wednesday, 25 May 2011

Odd Even Threads in java

public class Test {

public static void main(String[] args) {
OddEven o1 = new OddEven("Odd Number Thread" , 1);
OddEven o2 = new OddEven("Even Number Thread" , 2);
o1.start();
o2.start();
}
}

====
public class OddEven extends Thread {
/**
* @param string
*/

private int number;

public OddEven(String name, int p_number){
super(name);
this.number = p_number;
}

public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(getName()+ this.number );
this.number +=2;
}
}
}


reverse string in java

public class ReverseStringTest {
  public static void main(String[] args) {
    String str = "What's going on?";
    System.out.println(ReverseString.reverseIt(str));
  }
}

class ReverseString {
  public static String reverseIt(String source) {
    int i, len = source.length();
    StringBuffer dest = new StringBuffer(len);

    for (i = (len - 1); i >= 0; i--)
      dest.append(source.charAt(i));
    return dest.toString();
  }
}
        

public class Main {
   
    /**
     * Converts all lower case characters to upper case
     */
    public void stringToUpperCase() {
       
        String str = "All Lower Case Characters In This String Will Be Converted To Upper Case";
       
        str = str.toUpperCase();
       
        System.out.println(str);
    }
   
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().stringToUpperCase();
    }
}


Output

substring example in java

public class SubstringExample1{
    public static void main(String[] args){
        String string = "sateesh bagadhi";
        System.out.println("String : " + string);
        String substring = string.substring(3);
        System.out.println("String after 3rd index: " + substring);  
        substring = string.substring(1, 2);
        System.out.println("Substring (1,2): " + substring);
    }
}

sorting a given string using java

import java.util.*;
import java.io.*;
import java.lang.String;

public class SortWords{
    public static void main(String args[]){
        String str = "This is my new string";
        char[] content = str.toCharArray();
        java.util.Arrays.sort(content);
        String sorted = new String(content);
        System.out.println(content);
    }
}

output
Teghiiimnnrssstwy

Harmonic Series 1+1/2+1/3+1/4+1/5.....

class HarmonicSeries{

public static void main(String args[]){

int num = Integer.parseInt(args[0]);

double result = 0.0;

while(num > 0){

result = result + (double) 1 / num;

num--;

}

System.out.println("Output of Harmonic Series is "+result);

}

}