skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Monday, January 16, 2012

Java Example that generates General exceptions Like NullPointerException etc.

Posted by Admin at 6:59 AM – 0 comments
 
Write a program that generates exceptions of type NullPointerException, NegativeArraySizeException, and IndexOutOfBoundsException. Record the catching of each exception by displaying the message stored in the exception object and the stack trace record.

public class TestSimple {

  public static void main(String args[]) {
    int result = 0;                                                    // Somewhere to store a result.
    int arraySize = 3;
    int badSize = -1;                                                  // A negative size to generate NegativeArraySizeException.
    int[] array = null;                                                // Define an integer array variable.

    for(int choice = 0; choice<3 ; ++choice)
    try {
      switch(choice) {
        case 0:
         result = array[0];                                            // Generates a NullPointerException.
         break;
        case 1:
         array = new int[badSize];                                     // Generates a NegativeArraySizeException.
         break;
        case 2:
         array = new int[arraySize];
         result = array[arraySize];                                    // Generates an ArrayIndexOutOfBoundsException.
         break;
      }
    } catch(NullPointerException e) {                                  // Catch the NullPointerException:
      System.out.println("\nNullPointerException Exception caught. " +
                         "Message in NullPointerException is:\n" +
                         "\n" + e + "\n");
      System.out.println("The contents of the stack trace are:\n");
      e.printStackTrace();
    } catch(NegativeArraySizeException e) {                            // Catch the NegativeArraySizeException:
      System.out.println("\nNegativeArraySizeException Exception caught. " +
                         "Message in NegativeArraySizeException is:\n" +
                         "\n" + e + "\n");
      System.out.println("The contents of the stack trace are:\n");
      e.printStackTrace();
    } catch(ArrayIndexOutOfBoundsException e) {                        // Catch the ArrayIndexOutOfBoundsException:
      System.out.println("\nArrayIndexOutOfBoundsException Exception caught. " +
                         "Message in ArrayIndexOutOfBoundsException is:\n" +
                         "\n" + e + "\n");
      System.out.println("The contents of the stack trace are:\n");
      e.printStackTrace();
    }
  }
}


Output of Above Java Program
NullPointerException Exception caught. Message in NullPointerException is:

java.lang.NullPointerException

The contents of the stack trace are:

java.lang.NullPointerException
at  TestSimple.main( TestSimple.java:13)

NegativeArraySizeException Exception caught. Message in NegativeArraySizeException is:

java.lang.NegativeArraySizeException

The contents of the stack trace are:

java.lang.NegativeArraySizeException
at  TestSimple.main( TestSimple.java:16)

ArrayIndexOutOfBoundsException Exception caught. Message in ArrayIndexOutOfBoundsException is:

java.lang.ArrayIndexOutOfBoundsException: 3

The contents of the stack trace are:

java.lang.ArrayIndexOutOfBoundsException: 3
at  TestSimple.main( TestSimple.java:20)

[ Read More ]
Read more...

Java Example to Demonstrate the use of Package.

Posted by Admin at 6:40 AM – 0 comments
 
Put both the Following Examples classes in a package called Measures.
Define a class to represent a weight in tons, kilograms, and grams
Define a class to represent a length measured in meters, centimeters, and millimeters

Import this package into a program that calculates and displays the total weight of the following:
200 carpets—size: 4 meters by 2 meters 9 centimeters, that weigh 1.25 kilograms per square meter;
and 60 carpets—size: 3 meters 57 centimeters by 5 meters, that weigh 1.05 kilograms per square meter.

Make sure that the source and class files for mcmLength and tkgWeight Are not in the same directory as this file. Otherwise those classes will beused rather than the ones in the Measures package

To compile this program the compiler needs to know where the Measures packages is. If the current directory contains Carpets.java and Measures is a subdirectory of this, you can compile Carpets by using the -classpath option like this:

javac -classpath . Carpets.java

If Measures is not a subdirectory of the current directory, you just need to add the path to the directory that contains Measures to -classpath. Note that you still need the period in the classpath, otherwise the compiler will not be able to find Carpets.java.

import Measures.tkgWeight;
import Measures.mcmLength;

public class Carpets {
  public static void main(String args[]) {
    mcmLength[] carpetLengths = { new mcmLength(4,0,0), new mcmLength(3,57,0) };
    mcmLength[] carpetWidths = { new mcmLength(2,9,0), new mcmLength(5,0,0) };
    double[] carpetWtPerSqM = { 1.25, 1.05 };                          // Weight per sq m of carpets
    int[] carpetCounts = { 200, 60 };


    tkgWeight carpetWeight = null;                                    // Store for reference to weight of a carpet
    double carpetArea = 0.0;                                          // Store for area of a carpet


    for(int i = 0 ; i < carpetLengths.length ; ++i) {
      // Since we want areas in square meters it is easiest to calculate them directly
      carpetArea = carpetLengths[i].toMeters()*carpetWidths[i].toMeters();

      carpetWeight = new tkgWeight(carpetWtPerSqM[i]*carpetArea);

      System.out.println("\nCarpet " + (i + 1) + ": Size = " + carpetLengths[i] + " by "+ carpetWidths[i]);
      System.out.println("        " + "  Weight per sq. m. = " + carpetWtPerSqM[i]);
      System.out.println("        " + "  Area = " + carpetArea + " sq. m.");
      System.out.println("        " + "  Weight = " + carpetWeight);

      System.out.println("        " + "  Weight of " + carpetCounts[i] + " carpets = " + carpetWeight.multiply(carpetCounts[i]));

    }
  }
}

[ Read More ]
Read more...

Define a class to represent a weight in tons, kilograms, and grams | Java Program

Posted by Admin at 6:30 AM – 0 comments
 
Define a class, tkgWeight, to represent a weight in tons, kilograms, and grams and Demonstrate this class by creating and combining some class objects.

public class tkgWeight {
  public static final int KG_PER_TON = 1000;
  public static final int GRAMS_PER_KG = 1000;
  public static final int GRAMS_PER_TON = GRAMS_PER_KG*KG_PER_TON;

  // private member variables
  private int tons = 0;
  private int kilograms = 0;
  private int grams = 0;

  // Constructors:
  public tkgWeight(double kg) {
    this((int)Math.round(kg*GRAMS_PER_KG));
  }

  public tkgWeight(int g) {
    tons = g/GRAMS_PER_TON;
    kilograms = (g - tons*GRAMS_PER_TON)/GRAMS_PER_KG;
    grams = g - tons*GRAMS_PER_TON - kilograms*GRAMS_PER_KG;
  }

  public tkgWeight(int t, int kg, int g) {
    this(t*GRAMS_PER_TON + kg*GRAMS_PER_KG + g);
  }

  public tkgWeight(){}

  // Methods
  public String toString()  {
    return Integer.toString(tons) + "t " + kilograms + "kg " + grams + "g";
  }

  public int toGrams() {
    return tons*GRAMS_PER_TON + kilograms*GRAMS_PER_KG + grams;
  }

  public double toKilograms() {
    return ((double)toGrams())/GRAMS_PER_KG;
  }

  public tkgWeight add(tkgWeight weight) {
    return new tkgWeight(toGrams() + weight.toGrams());
  }

  public tkgWeight subtract(tkgWeight weight) {
    return new tkgWeight(toGrams() - weight.toGrams());
  }

  public tkgWeight multiply(int n) {
    return new tkgWeight(n*toGrams());
  }

  public tkgWeight divide(int n) {
    return new tkgWeight(toGrams()/n);
  }

  // Compare two weights
  // Return value is 1 if current greater than arg
  //                 0 if current equal to arg
  //                -1 if current less than arg
  public int compare(tkgWeight weight) {
    return greaterThan(weight) ? 1 : (equals(weight) ? 0 : -1);
  }

  public boolean equals(tkgWeight weight) {
    return toGrams() == weight.toGrams();
  }

  public boolean lessThan(tkgWeight weight) {
    return toGrams() < weight.toGrams();
  }

  public boolean greaterThan(tkgWeight weight) {
    return toGrams() > weight.toGrams();
  }
}

This is Main Class to Test above  tkgWeight Class. 

public class TestWeights {

  public static void main(String args[]) {
   // Test the constructors
    tkgWeight[] weights = {
                             new tkgWeight(274.65) , new tkgWeight(274),
                             new tkgWeight(274,2,3), new tkgWeight()
                          };

    //Display the weights
    for(int i = 0 ; i < weights.length ; ++i)
    System.out.println("Weight " + i + " is " + weights[i]);

   // Test the operations
    System.out.println("Addition: " + weights[0] + " plus " + weights[1] + " is " + weights[0].add(weights[1]));
    System.out.println("Subtraction: " + weights[0] + " minus " + weights[1] + " is " + weights[0].subtract(weights[1]));
    System.out.println("Multiplication: "+ weights[0] + " times 10 is " + weights[0].multiply(10));
    System.out.println("Division: " + weights[0] + " divided by 10 is " + weights[0].divide(10));

    // Test comparison methods
    if(weights[0].greaterThan(weights[1])) {
      System.out.println("Weight "+ weights[0] + " is greater than length " + weights[1]);
    } else if(weights[0].lessThan(weights[1])) {
      System.out.println("Weight "+ weights[0] + " is less than length " + weights[1]);
    } else {
      System.out.println("Weight "+ weights[0] + " is the same length as length " + weights[1]);
    }

    // Compare successive weights using compare() method
    String compareStr = null;
    for(int i = 0 ; i < weights.length - 1 ; ++i) {
      switch(weights[i].compare(weights[i+1])) {
     case -1:
         compareStr = " is less than length ";
         break;
     case 0:
         compareStr = " is equal to length ";
         break;
     case 1:
         compareStr = " is greater than length ";
         break;
      }
      System.out.println("Weight " + weights[i] + compareStr + weights[i+1]);
    }
  }
}


Output of Above Java Program
Weight 0 is 0t 274kg 650g
Weight 1 is 0t 0kg 274g
Weight 2 is 274t 2kg 3g
Weight 3 is 0t 0kg 0g
Addition: 0t 274kg 650g plus 0t 0kg 274g is 0t 274kg 924g
Subtraction: 0t 274kg 650g minus 0t 0kg 274g is 0t 274kg 376g
Multiplication: 0t 274kg 650g times 10 is 2t 746kg 500g
Division: 0t 274kg 650g divided by 10 is 0t 27kg 465g
Weight 0t 274kg 650g is greater than length 0t 0kg 274g
Weight 0t 274kg 650g is greater than length 0t 0kg 274g
Weight 0t 0kg 274g is less than length 274t 2kg 3g
Weight 274t 2kg 3g is greater than length 0t 0kg 0g
[ Read More ]
Read more...

Define a class to represent a length measured in meters, centimeters, and millimeters | Java Program

Posted by Admin at 6:25 AM – 0 comments
 
Define a class, mcmLength, to represent a length measured in meters, centimeters, and millimeters, each stored as integers. Include methods to add and subtract objects, to multiply and divide an object by an integer value, to calculate an area resulting from the product of two objects, and to compare objects.  Include constructors that accept three arguments—meters, centimeters, and millimeters; one integer argument in millimeters; one double argument in centimeters; and no arguments, which creates an object with the length set to zero. Check the class by creating some objects and testing the class operations.

public class mcmLength {

  public static final int CM_PER_M = 100;
  public static final int MM_PER_CM = 10;
  public static final int MM_PER_M = MM_PER_CM*CM_PER_M;

  // Private member variables:
  private int meters = 0;
  private int centimeters = 0;
  private int millimeters = 0;

  // Constructors:
  public mcmLength(double cm) {
    this((int)Math.round(cm*MM_PER_CM));
  }

  public mcmLength(int mm) {
    meters = mm/MM_PER_M;
    centimeters = (mm - meters*MM_PER_M)/MM_PER_CM;
    millimeters = mm - meters*MM_PER_M - centimeters*MM_PER_CM;
  }

  // If we were to just store the argument values, we could
  // end up with invalid mm and cm values in the object if the
  // values passed as arguments are not valid.
  // With the approach here we guarantee all values are valid
  // in the object that is created.
  public mcmLength(int m, int cm, int mm) {
    this(m*MM_PER_M + cm*MM_PER_CM + mm);
  }

  public mcmLength(){}

  // Methods
  // Replaces the default toString method in Object:
  public String toString() {
    return Integer.toString(meters) + "m " + centimeters + "cm " + millimeters + "mm";
  }

  public int toMM() {
    return meters*MM_PER_M + centimeters*MM_PER_CM + millimeters;
  }


  public double toMeters() {
    return meters + ((double)(centimeters))/CM_PER_M + ((double)(millimeters))/MM_PER_M;
  }

  // All of the following methods use the toMM():
  public mcmLength add(mcmLength length)
  {
    return new mcmLength(toMM()+length.toMM());
  }

  public mcmLength subtract(mcmLength length)
  {
    return new mcmLength(toMM()-length.toMM());
  }

  public mcmLength multiply(int n)
  {
    return new mcmLength(n*toMM());
  }

  public mcmLength divide(int y)
  {
    return new mcmLength(toMM()/y);
  }

  //Calculate area in square mm
  public long area(mcmLength length) {
    return (toMM()*length.toMM());
  }

  // Compare two lengths
  // Return value is 1 if current greater than arg
  //                 0 if current equal to arg
  //                -1 if current less than arg
  public int compare(mcmLength length) {
    return greaterThan(length) ? 1 : (equals(length) ? 0 : -1);
  }

  public boolean equals(mcmLength length) {
   return toMM() == length.toMM();
  }

  public boolean lessThan(mcmLength length) {
   return toMM() < length.toMM();
  }

  public boolean greaterThan(mcmLength length) {
   return toMM() > length.toMM();
  }
}

This is the main Class to test mcmLength Class.

public class TestLengths {
  public static void main(String args[]) {
    mcmLength[] lengths = new mcmLength[4];

    // Test the constructors:
    lengths[0] = new mcmLength(274.65);
    lengths[1] = new mcmLength(274);
    lengths[2] = new mcmLength(274,2,3);
    lengths[3] = new mcmLength();

    //Display the figures:
    for(int i = 0 ; i < lengths.length ; ++i) {
      System.out.println("Length " + i + " is " + lengths[i]);
    }

    // Test the arithmetic and area operations
    System.out.println("Addition: " + lengths[0] + " plus " + lengths[1] + " is " + lengths[0].add(lengths[1]));
    System.out.println("Subtraction: " + lengths[0] + " minus " + lengths[1]+ " is " + lengths[0].subtract(lengths[1]));
    System.out.println("Multiplication: " + lengths[0] + " times 10 is " + lengths[0].multiply(10));
    System.out.println("Division: " + lengths[0] + " divided by 10 is " + lengths[0].divide(10));
    System.out.println("Area: "  + lengths[0] + " by " + lengths[1] + " is " + lengths[0].area(lengths[1]) + " square mm");

    // Test comparison methods
    if(lengths[0].greaterThan(lengths[1])) {
      System.out.println("Length "+ lengths[0] + " is greater than length " + lengths[1]);
    } else if(lengths[0].lessThan(lengths[1])) {
      System.out.println("Length "+ lengths[0] + " is less than length " + lengths[1]);
    } else {
      System.out.println("Length "+ lengths[0] + " is the same length as length " + lengths[1]);
    }

    // Compare successive lengths using compare() method
    String compareStr = null;
    for(int i = 0 ; i < lengths.length-1 ; ++i) {
      switch(lengths[i].compare(lengths[i+1])) {
        case -1:
         compareStr = " is less than length ";
         break;
        case 0:
         compareStr = " is equal to length ";
         break;
        case 1:
         compareStr = " is greater than length ";
         break;
      }
      System.out.println("Length " + lengths[i] + compareStr + lengths[i+1]);
    }
  }
}


Output of Above Java Program
Length 0 is 2m 74cm 7mm
Length 1 is 0m 27cm 4mm
Length 2 is 274m 2cm 3mm
Length 3 is 0m 0cm 0mm
Addition: 2m 74cm 7mm plus 0m 27cm 4mm is 3m 2cm 1mm
Subtraction: 2m 74cm 7mm minus 0m 27cm 4mm is 2m 47cm 3mm
Multiplication: 2m 74cm 7mm times 10 is 27m 47cm 0mm
Division: 2m 74cm 7mm divided by 10 is 0m 27cm 4mm
Area: 2m 74cm 7mm by 0m 27cm 4mm is 752678 square mm
Length 2m 74cm 7mm is greater than length 0m 27cm 4mm
Length 2m 74cm 7mm is greater than length 0m 27cm 4mm
Length 0m 27cm 4mm is less than length 274m 2cm 3mm
Length 274m 2cm 3mm is greater than length 0m 0cm 0mm

[ Read More ]
Read more...

Program to Create a Rectangle objects defined by Two Points

Posted by Admin at 6:05 AM – 0 comments
 
Define a class for rectangle objects defined by two points, the top-left and bottom-right corners of the rectangle. Include a constructor to copy a rectangle, a method to return a rectangle object that encloses the current object and the rectangle passed as an argument, and a method to display the defining points of a rectangle. Test the class by creating four rectangles and combining these cumulatively to end up with a rectangle enclosing them all. Output the defining points of all the rectangles you create.

This is the Point class definition. It is used by the Rectangle class


public class Point {
  // Create a Point object from a coordinate pair
  public Point(double x, double y) {
    this.x = x;
    this.y = y;
  }

  // Create a Point object from another Point
  public Point(Point p) {
    x = p.x;
    y = p.y;
  }

  // Get the value of the x coordinate
  double getX() {
    return x;
  }

  // Get the value of the y coordinate
  double getY() {
    return y;
  }

  public String toString(){
    return x +","+y;
  }

  // Fields store the point coordinates
  private double x;
  private double y;
}

This is the Rectangle class definition. It makes use of the Point class definition that is in the same directory as this file.

public class Rectangle {
  private Point topLeft;
  private Point bottomRight;

  // Constructors
  public Rectangle(double x1, double y1, double x2, double y2) {
    // Ensure topleft uses the smaller of x1,x2 and y1,y2
    // and topright uses the larger of x1,x2 and y1,y2
    topLeft = new Point(Math.min(x1,x2),Math.min(y1,y2));
    bottomRight = new Point(Math.max(x1,x2),Math.max(y1,y2));
  }

  public Rectangle(Point tl, Point br) {
    this(tl.getX(), tl.getY(), br.getX(), br.getY());
  }

  public Rectangle(Rectangle rect) {
    topLeft = new Point(rect.topLeft);
    bottomRight = new Point(rect.bottomRight);
  }

  // Methods to create a rectangle enclosing the current rectangle and the argument
  public Rectangle encloses(Rectangle rect) {
    // Return a new rectangle defined by the minimum x,y for to left and the and maximum x,y for bottom right
    return new Rectangle(Math.min(topLeft.getX(), rect.topLeft.getX()),
                         Math.min(topLeft.getY(), rect.topLeft.getY()),
                         Math.max(bottomRight.getX(), rect.bottomRight.getX()),
                         Math.max(bottomRight.getY(), rect.bottomRight.getY()));

  }

  public String toString()  {
    return "Rectangle: " + topLeft + " : " + bottomRight;
  }
}

This is the main Class to Test the Rectangle Class.

public class TestRectangle {
  public static void main(String args[]) {
    Rectangle[] rects = new Rectangle[4];
    Rectangle enclosing;

    // Initialize the rectangles as arbitrary sizes and at arbitrary positions:
    for(int i = 0 ; i < rects.length ; ++i) {
      rects[i] = new Rectangle(Math.random()*100, Math.random()*100, Math.random()*100, Math.random()*100);
      System.out.print("Coords of rectangle " + i + " are: ");
      System.out.println(rects[i]);
    }

    // Initialize the enclosing rectangle to be first rectangle
    enclosing = rects[0];

    // Combine it with each the other rectangles in turn.
    // This will result in the rectangle that encloses them all.
    for(Rectangle rect : rects)  {
      enclosing = enclosing.encloses(rect);
    }

    System.out.println("\nCoords of Enclosing rectangle are ");
    System.out.println(enclosing);
  }
}


Output of Above Java Program
Coords of rectangle 0 are: Rectangle: 0.1903728640358593,58.04643476457927 : 0.2032621709617044,85.8337274416007
Coords of rectangle 1 are: Rectangle: 6.239529478079319,44.58944044246343 : 66.47238823570548,57.983153189860396
Coords of rectangle 2 are: Rectangle: 10.500877688164522,59.35612909169482 : 80.53072142287722,99.35041648038772
Coords of rectangle 3 are: Rectangle: 28.73052501676693,2.2641735796500972 : 44.35555027080914,11.239350082208022

Coords of Enclosing rectangle are
Rectangle: 0.1903728640358593,2.2641735796500972 : 80.53072142287722,99.35041648038772


[ Read More ]
Read more...

To Reverse the Sequence of Letters in Each word of your Chosen Paragraph | Java Example

Posted by Admin at 5:27 AM – 0 comments
 
 Write a program that reverses the sequence of letters in each word of your chosen paragraph.
For instance, "To be or not to be." becomes "oT eb ro ton ot eb."

public class ReverseText {
  public static void main(String args[]) {
    // The String that is to be processed with a few newlines to make the
    // output a little more readable
    String text = "Into the face of the young man who sat on the terrace " +
                  "\nof the Hotel Magnifique at Cannes crept a look of furtive " +
                  "\nshame, the shifty, hangdog look which announces that " +
                  "\nan Englishman is about to talk French." ;

    boolean isWord = false;                                            // Indicates start of a word found
    int start = 0;                                                     // Index of word start
    StringBuffer reversedText = new StringBuffer();
    StringBuffer word = new StringBuffer();
    for(int i = 0 ; i  <text.length() ; ++i) {
      if(!isWord) {                                                    // If we are not in a word...
        if(Character.isLetter(text.charAt(i))) {                       // look for first letter of a word.
          word.append(text.charAt(i));                                 // and append it to word
          isWord = true;                                               // Flag that we are in a word
        } else {
          reversedText.append(text.charAt(i));
        }
      } else {                                                         // We are in a word
        if(Character.isLetter(text.charAt(i)) || text.charAt(i) == '\'') {
          word.append(text.charAt(i));                                 // Append to word
          continue;
        }
        else {                                                         // It is the end of the word
          reversedText.append(word.reverse());                         // so append the reversed word
          reversedText.append(text.charAt(i));                         // Don't forget the current character
          word.delete(0,word.length());                                // Delete the contents of word
          isWord = false;                                              // and reset word indicator
        }
      }
    }
    if(word.length() > 0)                                              // Is there a last word?
      reversedText.append(word.reverse());                             // If so append it - reversed of course.



    // Display the Reversed text
    System.out.println(reversedText);
  }
}


Output of Above Java Program
otnI eht ecaf fo eht gnuoy nam ohw tas no eht ecarret
fo eht letoH euqifingaM ta sennaC tperc a kool fo evitruf
emahs, eht ytfihs, godgnah kool hcihw secnuonna taht
na namhsilgnE si tuoba ot klat hcnerF.

[ Read More ]
Read more...

To Print dates in Formatted Way | Java Example

Posted by Admin at 5:18 AM – 0 comments
 
Define an array of ten String elements each containing an arbitrary string of the form "month/day/year";
for example,"10/29/99" or "12/5/01".
Analyze each element in the array and output the date represented in the form 29th October 1999

public class Dates {
  public static void main(String args[]) {
    String[] dates = new String[10];
    String[] monthNames = {
    "January", "February", "March", "April",
    "May", "June", "July", "August", "September",
    "October", "November", "December"
    };

    int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    String ending = "th";
    String dayStr = null;
    String monthStr = null;
    String yearStr = null;
    char separator = '/';
    int day = 0;
    int month = 0;
    int year = 0;
    int daysIncrement = 0;

    // Generate a set of arbitrary dates:
    for(int i = 0 ; i < dates.length ; ++i) {
      year = (int)(100.0*Math.random());                               // Random year value 00 to 99
      month = (int)(12.0*Math.random()) + 1;                           // Random month value 1 to 12

      // February in a leap year has 29 days in the month so we need to allow for an extra day.
      // Leap years are messy ...
      // A leap year is a year that is divisible by 4 and not by 100, or
      // a leap year is a century and the number of centuries is divisible by 4
      daysIncrement = (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0)) && (month == 2) ? 1 : 0 ;

      day = (int)(Math.random()*(daysInMonth[month-1] + daysIncrement)) + 1;
      dates[i] = "" + day + separator + month + separator + (year<10 ? "0" :"") + year;
      System.out.println("Day is " + dates[i]);
    }

    // Now the set of dates has been generated, we can interpret and output it.
    int start = 0;                                                     // Word start index
    int end = 0;                                                       // Word end index

    System.out.println();
    for(String date : dates) {
      // Extract the day, month and year strings using the familiar method.
      start = 0;
      end = date.indexOf(separator,start);
      dayStr = date.substring(start, end);
      start = end + 1;
      end = date.indexOf(separator,start);
      monthStr = date.substring(start, end);
      start = end + 1;
      yearStr = date.substring(start);

      // Figure out whether "st", "nd", "rd", or "th", should be appended to the day.
      //  Single digit day is "st", "rd", "nd", for "1", "2", "3", and "th" otherwise.
      // Days "11" to "19" are all "th".
      // The remainder are "st", "rd", "nd", for last digit "1", "2", "3",
      // and "th" otherwise.
      if(dayStr.length() == 1)
        switch(dayStr.charAt(0)) {
          case '1':
            ending = "st";
            break;
          case '2':
            ending = "nd";
            break;
          case '3':
            ending = "rd";
            break;
          default:
            ending = "th";
        }
      else if(dayStr.charAt(0) == '1')
        ending = "th";
      else
        switch(dayStr.charAt(1)) {
          case '1':
            ending = "st";
            break;
          case '2':
            ending = "nd";
            break;
          case '3':
            ending = "rd";
            break;
          default:
            ending = "th";
        }

      // We can now output the date in the required format.
      // To output the month name string we must use monthStr to get an index to the monthNames array.
      System.out.println(dayStr + ending + " " +
           monthNames[monthStr.length() == 1 ? monthStr.charAt(0) - '1': 9 + monthStr.charAt(1) - '0'] +
           " " + "19" + yearStr);

      // The preceding would be easier using Integer class methods to convert
      // the day and month strings to integers.
      // We could index the monthNames array with the expression monthNames[Integer.parseInt(monthStr)]
      // The parseInt() method converts the String argument to an int value.
    }
  }
}


Output of Above Java Program
Day is 6/6/87
Day is 30/6/79
Day is 30/4/99
Day is 8/8/68
Day is 30/6/96
Day is 27/5/97
Day is 5/3/76
Day is 4/4/27
Day is 20/11/39
Day is 26/2/23

6th June 1987
30th June 1979
30th April 1999
8th August 1968
30th June 1996
27th May 1997
5th March 1976
4th April 1927
20th November 1939
26th February 1923
[ Read More ]
Read more...
Newer Posts Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

  • Find the Body Mass Index Using AWT and Swing Classes
    Here is a Java Program to Find the Body Mass Index Using AWT and Swing Classes import java.awt.*; import java.awt.event.*; import javax.s...
  • Barcode Generation using iText
    This Program describes the barcode generation in PDF document. Code39 Barcode document.add(new Paragraph("Barcode 3 of 9")); ...
  • Send outlook meeting request using Java Mail API
    This Program is useful to send meeting request to the users using Java mail API.We need to include mail.jar in the classpath. import ja...
  • Parse XML file using DOM
    This code snippet explains about the parsing of the xml file using the DOM parser. import java.io.File; import java.io.IOException...
  • program to retrieve Method names of a class
    import java.lang.reflect.*; public class Refl6 { public static void main(String args[]) throws Exception { Class c=Class.forN...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Function to Check Given Date is Older Than 900 days
    The code snippet will results in a boolean using which we can identify that given date is older than 900 days or not. /** * @param arg...
Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

  • Creating Dynamic Macro Enabled Excel by Java
    We can create a dynamic macro enabled excel by java: We need to create a excel sheet template with macro on server. we can copy the...
  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Printing Table In java using While Loop
    Here is a Java Program to Print the Table public class Table { public static void main(String[] args) { int no = Integer.p...
  • Java Class to Calculate the Volume of Box
    Here is a Java Class to Calculate the Volume of Box. class Box { double width; double height; double depth; // This is the con...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger