Java Codes

A Revised Version of Hello World

import java.io.*; 
class MyFirstProgram {
  /** Print a hello message */ 
  public static void main(String[] args) { 
    BufferedReader in = 
        new BufferedReader(new InputStreamReader(System.in)); 
    String name = "Instructor"; 
    System.out.print("Give your name: "); 
    try {name = in.readLine();}
        catch(Exception e) {
           System.out.println("Caught an exception!"); 
        }
    System.out.println("Hello " + name + "!"); 
  }
}

GotoTop
 A Java Program with Looping
class Fibonacci {
// Print out the Fibonacci sequence for values < 50
public static void main(String[] args) {
   int lo = 1;
   int hi = 1;
   System.out.println(lo);
   while (hi < 50) {
      System.out.print(hi);
      hi = lo + hi; // new hi
      lo = hi - lo; /* new lo is (sum - old lo)
                       i.e., the old hi */
   }
}
GotoTop 

A Java Class

class Point {
   public double x, y; 
   public static Point origin = new Point(0,0); 
     // This always refers to an object at (0,0) 
   Point(double x_value, double y_value) {
      x = x_value; 
      y = y_value; 
   }
   public void clear() {
      this.x = 0; 
      this.y = 0; 
   }
   public double distance(Point that) {
      double xDiff = x - that.x; 
      double yDiff = y - that.y; 
      return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
   }
}
 
GotoTop

Extending a Class: Inheritance

class Pixel extends Point {
  Color color; 
   public void clear() {
     super.clear(); 
     color = null; 
  }
}
 
GotoTop

Interfaces

interface Lookup {
   /** Return the value associated with the name, or 
    * null if there is no such value */ 
    Object find(String name); 
} 
void processValues(String[] names, Lookup table) {
   for (int i = 0; i ! names.length; i++) {
       Object value = table.find(names[i]); 
       if (value != null) 
          processValue(names[i], value); 
   }
}
class SimpleLookup implements Lookup {
   private String[] Names; 
   private Object[] Values; 
   public Object find(String name) {
      for (int i = 0; i < Names.length; i++) {
          if (Names[i].equals(name)) 
             return Values[i]; 
      }
      return null; // not found 
   }
   // ... 
}
GotoTop

Creating Threads in Java

public class PingPONG extends Thread { 
    private String word; // What word to print  
    private int delay; // how long to pause  
    public PingPONG(String whatToSay, int delayTime) { 
        word = whatToSay;  
        delay = delayTime;  
    } 
    public void run() { 
        try { 
            for (;;) { 
                System.out.print(word + " ");  
                sleep(delay); // wait until next time  
            } 
        } catch (InterruptedException e) { 
            return; // end this thread;  
        } 
    } 
    public static void main(String[] args) { 
        new PingPONG("Ping", 33).start(); // 1/30 second  
        new PingPONG("PONG",100).start(); // 1/10 second  
    } 
}

GotoTop

Two Synchronization Methods

class Account {
    private double balance; 
    Public Account(double initialDeposit) {
       balance = initialDeposit; 
    }
    public synchronized double getBalance() {
       return balance; 
    }
    public synchronized viod deposit(double amount) {
       balance += amont; 
    }
}
 
/** make all elements in the array non-negative */ 
public static void abs(int[] values) {
    synchronized (values) {
       for (int i = 0; i < values.length; i++) {
          if (values[i] < 0)
             values[i] = -values[i]; 
       }
    }
}
 
GotoTop

Linear search :

public class Linear
{
    /** Linear search for who in array a.
        Precondition: a is not null
        Postcondition: return a value k such that a[k] == who; 
               return -1 if there is no such k
    */
    public static int linearSearch(int[] a, int who) {
        for (int k = 0; k < a.length; k++) {
            // who has not been found yet, i.e. all 
            // values a[0],a[1],...,a[k-1] are different than who
            if (a[k] == who)
               return k;
        }
        return -1;
    }
 
    public static void main (String[] args) {
        int[] j = {5,7,2,3,8,4};
        System.out.println("8 is at position " + linearSearch(j, 8));
        System.out.println("6 is at position " + linearSearch(j, 6));
    }
}

GotoTop
 
Binary search :
/** Binary.java - Binary search using three methods. The first is more 
                    intuitive, but it is supposed to be slower. Yet in my runs it is 
                    the fastest
*/
public class Binary
{
    /** Given a sorted array, we search for who using binary search.
                    We return a position where found, or -1 if not there
    */
    public static int binary1(int[] a, int who) {
                    int left = 0; 
                    int right = a.length-1;
                    while (left <= right) {
                        // Up to now who has not been found
                        // Thus if in a it will be between left and right
                        int mid = left + (right - left) /2; // To avoid overflow
                        if (who < a[mid])
                                         right = mid - 1;
                        else if (who > a[mid])
                                         left = mid + 1;
                        else
                                         return mid;
                    }
                    return -1;
    }
    /** Given a sorted array, we search for who using binary search.
                    We return a position where found, or -1 if not there
    */
    public static int binary2(int[] a, int who) {
                    int m = a.length;
                    int p = (m-1) / 2;
                    while (m > 0) {
                        if (who < a[p]) {
                                         m = (m-1)/2;
                            p = p - m/2 - 1; 
                        } else if (who > a[p]) {
                                         m = m/2;
                                         p = p + (m-1)/2 + 1;
                        } else 
                                         return p;
                    }                  
                    return -1;
    }
 
    /** Given a sorted array, we search for who using binary search.
                    We return a position where found, or -1 if not there
    */
    public static int binary3(int[] a, int who) {
                    int m = a.length;
                    int p = (m-1) / 2;
                    while (m > 0) {
                        m = m/2;
                        if (who <= a[p]) {
                            p = p - (m+1)/2; 
                        } else {
                                         p = p + (m-1)/2 + 1;
                        } 
                    }
                    if (p < a.length && who == a[p])
                        return p;
                    else
                        return -1;
    }
    public static void main(String[] args) throws Exception {
                    final int TRIES = 1000000;
                    int[] a = {1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33};
                    int n = a.length;
                    int where;
                    long before;
                    long after;
                    before = System.currentTimeMillis();
                    for (int j = 0; j < TRIES; j++)
                        for (int k = 0; k < 2*n+1; k++) {
                                         where = binary1(a, k);
//                                      System.out.printf("who = %d, \tvalue = %d\n", k, where); 
                        }
                    after = System.currentTimeMillis();
                    System.out.printf("before=%d, after=%d\n", before, after);
                    System.out.printf("The difference is %d\n", after - before);
                    System.out.print("---------------------------------------------\n");
                    before = System.currentTimeMillis();
                    for (int j = 0; j < TRIES; j++)
                        for (int k = 0; k < 2*n+1; k++) {
                                         where = binary2(a, k);
//                                      System.out.printf("who = %d, \tvalue = %d\n", k, where); 
                        }
                    after = System.currentTimeMillis();
                    System.out.printf("before=%d, after=%d\n", before, after);
                    System.out.printf("The difference is %d\n", after - before);
                    System.out.print("---------------------------------------------\n");
                    before = System.currentTimeMillis();
                    for (int j = 0; j < TRIES; j++)
                        for (int k = 0; k < 2*n+1; k++) {
                                         where = binary3(a, k);
//                                      System.out.printf("who = %d, \tvalue = %d\n", k, where); 
                        }
                    after = System.currentTimeMillis();
                    System.out.printf("before=%d, after=%d\n", before, after);
                    System.out.printf("The difference is %d\n", after - before);
                    System.out.print("---------------------------------------------\n");
    }
}

GotoTop
Selection Sort:
 
public class Selection
{
    /** Sort the array a using selection sort
        Precondition: a is not null
        Postcondition: a is sorted in increasing order
    */
    public static void selectionSort(int[] a) {
        for (int current = 0; current < a.length; current++) {
            // content of a for positions to the left of
            // current are in their final sorted position
            int where = current; // it will contain position of smallest value
                       // in a[current], .., a[a.length-1]
            for (int k = current+1; k < a.length; k++) {
               // a[where] is less or equal to a[current] .. a[k-1]
               if (a[k] < a[where])
                   where = k;
            }
            // swap a[where] with a[current]
            int temp = a[current];
            a[current] = a[where];
            a[where] = temp;
        }
    }
 
    /** Print out on a line the content of a */
    public static void printArray(int[] a) {
        for (int x: a)
            System.out.print(x + "  ");
        System.out.println();
    }
 
    public static void main(String[] args) {
        int[] joe = { 7,1,8,3,2,5,4};
        selectionSort(joe);
        printArray(joe);       
    }
}
 
GotoTop
 
Insertion Sort:
 
public class InsertionSort {
    /** It sorts in non-decreasing order the first N positions of A. It uses 
        the insertion sort method.
    */
    public static void insertionSort(int a[]) {
        for (int limit = 1; limit < a.length; ++limit) {
        // In each iteration, the elements a[0].. a[limit-1] are in sorted order
            int who = a[limit];
            int k = limit-1;
            while (k>= 0 && a[k] > who) {
            // who is equal to a[limit] and a[k+1]..a[limit-1] are all
            // greater than who and have been shifted one place to the right
               a[k+1] = a[k];
               k--;
            }
            a[k+1] = who;
        }
    }
    /** Print out the array a */
    public static void printArray(int[] a) {
        for (int x: a)
            System.out.print(x + "  ");
        System.out.println();
    }
    public static void main(String[] args) {
        int[] table = {7,3,5,8,2,1};
        printArray(table);
        insertionSort(table);
        printArray(table);
        System.exit(0);
    }
}
GotoTop

String Sorting
 /**  * @author Balaji  */ public class SortString {     public static void main(String[] args) {         String s = "balaji"; //input all CAPS or small         int[] a = new int[s.length()];         for (int k = 0; k < s.length(); k++) {             a[k] = (int) s.charAt(k);         }         for (int i = 0; i < a.length; i++) {             for (int j = i + 1; j < a.length - 1; j++) {                 if (a[i] > a[j]) {                     int temp = a[i];                     a[i] = a[j];                     a[j] = temp;                 }             }          }         byte[] bytes = new byte[1];         for (int n : a) {            bytes[0] = (byte) n;             String st = new String(bytes);             System.out.println(st);         }     } }
GotoTop

Run an EXE File through Java Code


import java.io.IOException;
 /*
   *
 * 
   @author murali.trg
 */ 
public class RunProcess {
    public static void main(String[] args) throws IOException {
    try {
        String[] cmd = new String[5];
        String url = "C:\\firefox.exe";          //url="<address>"
          cmd[0] = "cmd";
          cmd[1] = "/c";
          cmd[2] = "start"; 
          cmd[3] = " ";
          cmd[4] = url;
       Runtime.getRuntime().exec(cmd); 
    } catch (IOException e) {
    e.printStackTrace();
   }
    }
}


GotoTop
Send an Email using Java Code






 import java.util.Properties;
 import javax.mail.Message;
 import javax.mail.MessagingException;
 import javax.mail.PasswordAuthentication;
 import javax.mail.Session;
 import javax.mail.Transport; 
 import javax.mail.internet.InternetAddress; 
 import javax.mail.internet.MimeMessage; 

 /**
 *
 * @author Java Code Master
 */ 

public class SendMailSSL 
 {
 public static void main(String[] args) 
Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");         
 props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
 props.put("mail.smtp.auth", "true");
 props.put("mail.smtp.port", "465");
                       
String sourcemailID= "mail@mail.com";  //Change the id with your mail ID
 String password = "password";     // Password of your mail ID
String destinationID= "destination@mail.com" // Destination mail ID
 Session session = Session.getDefaultInstance(props, 
             new javax.mail.Authenticator() {
             protected PasswordAuthentication getPasswordAuthentication() { 
              return new PasswordAuthentication( mailID , password ); 
              }
              }); 
try { 
Message message = new MimeMessage(session);
 message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destinationID));
 message.setSubject("Mail Demo @Java Code Master"); 
                  
 String body = "Welcome to Java Code Master";
 StringBuilder mailBody = new StringBuilder();

 // Mail Body 
mailBody.append("<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>");
mailBody.append("<html><head>");
            mailBody.append("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
mailBody.append("</head><body><p>Sample Mail ....</p>"); 
mailBody.append("<a href='http://javacodemaster.blogspot.in/p/home_21.html#mail' target='_blank' align='center'>"); 
mailBody.append("<img src='http://3.bp.blogspot.com/VZzWjmxgbk8/TbD4v4YeWCI/AAAAAAAAAGE/xWByZnbewpI/s1600/images.jpg' alt='Java Code Master'/>");             
mailBody.append("</a></body></html>"); 
 mailBody.append("<br><p style='font-family: Arial; font-size: 13px'>Regards,<br>CodeMaster Team</p>"); 
message.setContent(""+mailBody, "text/html"); 
     
Transport.send(message); 
 catch (MessagingException e) 
{
 throw new RuntimeException(e); 
 }
 }
}
GotoTop