skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Showing posts with label Java Class Examples. Show all posts
Showing posts with label Java Class Examples. Show all posts
Tuesday, January 31, 2012

To demonstrate the difference between public and private

Posted by Admin at 5:27 AM – 0 comments
 

Here is a Java Program demonstrates the difference between public and private.

class Test {
  int a; // default access
  public int b; // public access
  private int c; // private access

  // methods to access c
  void setc(int i) { // set c's value
    c = i;
  }
  int getc() { // get c's value
    return c;
  }
}

Here is a Main Class to run above Class

class AccessTest {
  public static void main(String args[]) {
    Test ob = new Test();

    // These are OK, a and b may be accessed directly
    ob.a = 10;
    ob.b = 20;

    // This is not OK and will cause an error
//  ob.c = 100; // Error!

    // You must access c through its methods
    ob.setc(100); // OK
   
    System.out.println("a, b, and c: " + ob.a + " " +
                       ob.b + " " + ob.getc());
  }
}

Output of Above Java Program
a, b, and c: 10 20 100
[ Read More ]
Read more...

To Demonstrate the Simple Recursion

Posted by Admin at 5:17 AM – 0 comments
 

Here is a Java Program to Demonstrate the Simple Recursion

class RecTest {
  int values[];

  RecTest(int i) {
    values = new int[i];
  }

  // display arrary -- recursively
  void printArray(int i) {
    if(i==0) return;
    else printArray(i-1);
    System.out.println("[" + (i-1) + "] " + values[i-1]);
  }
}

Here is a Main Class to Run above Class

class Recursion {
  public static void main(String args[]) {
    RecTest ob = new RecTest(10);
    int i;

    for(i=0; i<10; i++) ob.values[i] = i;
    
    ob.printArray(10);
  }
}

Output of Above Java Program
[0] 0
[1] 1
[2] 2
[3] 3
[4] 4
[5] 5
[6] 6
[7] 7
[8] 8
[9] 9





[ Read More ]
Read more...

To find the Factorial of a number Using Recursion

Posted by Admin at 5:13 AM – 0 comments
 

Here is a Java Program to find the Factorial of a number Using Recursion

class Factorial {
  // this is a recusive function
  int fact(int n) {
    int result;

    if(n==1) return 1;
    result = fact(n-1) * n;
    return result;
  }
}

Here is a Main Class to Run the Above Java Class

class Recursion {
  public static void main(String args[]) {
    Factorial f = new Factorial();

    System.out.println("Factorial of 3 is " + f.fact(3));
    System.out.println("Factorial of 4 is " + f.fact(4));
    System.out.println("Factorial of 5 is " + f.fact(5));
  }
}

Output of Above Java Program
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120



[ Read More ]
Read more...

Java Program to Demonstrate the Passed by Value

Posted by Admin at 4:52 AM – 0 comments
 

Here is a Java Program to Demonstrate the Passed by Value

class Test {
  void meth(int i, int j) {
    i *= 2;
    j /= 2;
  }
}


This is a Main Class to run Above Java Class.

class CallByValue {
  public static void main(String args[]) {
    Test ob = new Test();
    int a = 15, b = 20;
    
    System.out.println("a and b before call: " +
                       a + " " + b);

    ob.meth(a, b); 

    System.out.println("a and b after call: " +
                       a + " " + b);
  }
}


Output of Above Java Program
a and b before call: 15 20
a and b after call: 15 20


[ Read More ]
Read more...

To Demonstrate that Objects may be passed to methods

Posted by Admin at 4:45 AM – 0 comments
 
Here is a Java Program to Demonstrate that Objects may be passed to methods.

class Test {
  int a, b;

  Test(int i, int j) {
    a = i;
    b = j;
  }

  // return true if o is equal to the invoking object
  boolean equals(Test o) {
    if(o.a == a && o.b == b) return true;
    else return false;
  }
}


Here is a Java Program to Execute Above Java Class

class PassOb {
  public static void main(String args[]) {
    Test ob1 = new Test(100, 22);
    Test ob2 = new Test(100, 22);
    Test ob3 = new Test(-1, -1);
    
    System.out.println("ob1 == ob2: " + ob1.equals(ob2));

    System.out.println("ob1 == ob3: " + ob1.equals(ob3));
  }
}


Output of Above Java Program
ob1 == ob2: true
ob1 == ob3: false

[ Read More ]
Read more...

To Automatic type conversions apply to overloading

Posted by Admin at 4:39 AM – 0 comments
 

Here is a Java Program to Automatic type conversions apply to overloading.

class OverloadDemo {
  void test() {
    System.out.println("No parameters");
  }

  // Overload test for two integer parameters.
  void test(int a, int b) {
    System.out.println("a and b: " + a + " " + b);
  }

  // overload test for a double parameter and return type
  void test(double a) {
    System.out.println("Inside test(double) a: " + a);
  }
}


Here is a Main Program to Run above Java Class

class Overload {
  public static void main(String args[]) {
    OverloadDemo ob = new OverloadDemo();
    int i = 88;

    ob.test(); 
    ob.test(10, 20);

    ob.test(i); // this will invoke test(double)
    ob.test(123.2); // this will invoke test(double)
  }
}


Output of Above Java Program
No parameters
a and b: 10 20
Inside test(double) a: 88.0
Inside test(double) a: 123.2

[ Read More ]
Read more...
Monday, January 30, 2012

Java Class to Calculate the Volume of Box

Posted by Admin at 8:06 AM – 0 comments
 
Here is a Java Class to Calculate the Volume of Box.


class Box {
  double width;
  double height;
  double depth;

  // This is the constructor for Box.
  Box(double w, double h, double d) {
    width = w;
    height = h;
    depth = d;
  }

  // compute and return volume
  double volume() {
    return width * height * depth;
  }
}

This is a  Main Class to run the Above Java Class

class BoxDemo {
  public static void main(String args[]) {
    // declare, allocate, and initialize Box objects
    Box mybox1 = new Box(10, 20, 15);
    Box mybox2 = new Box(3, 6, 9);

    double vol;

    // get volume of first box
    vol = mybox1.volume();
    System.out.println("Volume is " + vol);

    // get volume of second box
    vol = mybox2.volume();
    System.out.println("Volume is " + vol);
  }
}


Output of Above Java Program
Volume is 3000.0
Volume is 162.0

[ Read More ]
Read more...
Tuesday, January 17, 2012

Demonstrate the operation of Stack implementation

Posted by Admin at 4:48 AM – 0 comments
 
Define a generic Stack<> type with a method push() that adds the object that is passed as an argument to the top of the stack, and with a method pop() that removes and returns the object that is currently at the top of the stack. The pop() method should return null when the stack is empty. Demonstrate the operation of your Stack<> implementation by storing and retrieving 10 strings and 10 Double objects in stacks of a suitable type.

 A stack is a container that stores objects in a manner indicated by its name in a vertical stack where only the object at the top of the stack is accessible. It works rather like a sprung stack of plates in a cafeteria. Only the top plate is at counter level and, therefore, is the only one you can access. When you add a plate to the stack, the existing plates are pushed down so the new plate is now the one that you can access.

public class Stack<T> {
  public Stack() {
    items = new Object[initialCapacity];
  }

  // Push an item onto the stack
  public void push(T item) {
    if(itemCount==items.length) {
      Object[] newItems = new Object[items.length + increment];
      for(int i = 0 ; i < items.length ; ++i) {
        newItems[i] = items[i];
      }
      items = newItems;
    }
    items[itemCount++] = item;
  }

  // Pop an item off the top of the stack
  @SuppressWarnings("unchecked")
  public T pop() {
    if(itemCount == 0) {
      return null;
    }
    // Note: the annotation ensures this cast to type T will not result
    // in a warning from the compiler.
    T item = (T)items[--itemCount];
    items[itemCount] = null;                                           // Erase the object from the stack
    return item;
  }

  // Test for empty stack
  public boolean isEmpty() {
    return itemCount == 0;
  }

  // You cannot define an array of a parametric type T.
  // To store items in the stack of an arbitrary you can use type Object[]
  private Object[] items;                                              // Array to store items in the stack
  private int itemCount;                                               // Number of items in the stack

  private final static int initialCapacity = 10;                       // Initial stack capacity
  private final static int increment = 5;                              // Capacity increment when full
}


This is main Class to Test Above Java Class "Stack".


public class TryStack {
  public static void main(String[] args) {
    // Values to be stored in stack and then retrieved
    double[] values = { 1.0, 1.4142 , 1.732 , 2.0, 2.236, 2.449, 2.646, 2.828, 3.0, 3.162 };

    Stack<Double> data = new Stack<Double>();

    // Store the values on the stack
    System.out.println("Data pushed onto the stack in sequence is:");
    for(double v : values) {
      System.out.println(v);
      data.push(v);
    }

    double back = 0;
    System.out.println("\nData retrieved from the stack in sequence is:");
    while(!data.isEmpty()) {
      System.out.println(data.pop());
    }

    System.out.println("The stack should now be empty. Popping an item produces: " + data.pop());
  }
}


Output of Above Java Program
Data pushed onto the stack in sequence is:
1.0
1.4142
1.732
2.0
2.236
2.449
2.646
2.828
3.0
3.162

Data retrieved from the stack in sequence is:
3.162
3.0
2.828
2.646
2.449
2.236
2.0
1.732
1.4142
1.0
The stack should now be empty. Popping an item produces: null

[ Read More ]
Read more...
Monday, January 16, 2012

Create a Class defining an Object that Parses Each line of Input

Posted by Admin at 9:07 AM – 0 comments
 
Create a class defining an object that parses each line of input from the keyboard that contains items separated by an arbitrary delimiter (for example, a colon, or a comma, or a forward slash, and so on) and return the items as an array of type String[]. For example, the input might be

1/one/2/two

The output would be returned as an array of type String[] containing "1", "one", "2", "two".

import java.io.StreamTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class ParseInput {
  private StreamTokenizer tokenizer;
  private char separator;

  // Constructor requires the separator character as the argument
  public ParseInput(char separator){
    this.separator = separator;
    tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
    setTokenizerState();
  }

  // Sets the tokenizer to accept anyhing except the separator and end-of-line as
  // part of a word
  private void setTokenizerState() {
    tokenizer.resetSyntax();
    tokenizer.wordChars('\u0000', (char)(separator - 1));                 // Everything is a word character
    tokenizer.wordChars((char)(separator + 1), '\u00ff');                 // except for the separator
    tokenizer.whitespaceChars('\n', '\n');                                // Make end-of-line whitespace(and therefore a word delimiter)
    tokenizer.whitespaceChars(separator, separator);                      // Delimiter passed to constructor seaparates words
    tokenizer.eolIsSignificant(true);                                     // End-of-line to be reported as TT_EOL

  }

  // Read tokens from the input
  public String[] readTokens() {
    int type = 0;                                                         // Store the value returned by nextToken()
    int strCount = 5;                                                     // String capacity increment
    String[] tokens = new String[strCount];                               // Will store the tokens that we find
    int nTokens = 0;                                                      // Number of tokens stored
    try {
      while((type = tokenizer.nextToken()) != StreamTokenizer.TT_EOL) {   // As long as we don'y have EOL
        // Verify we have space in the tokens array
        if(nTokens == tokens.length) {
          String[] newTokens = new String[tokens.length+strCount];        // tokens array is full so create a larger array

          // Copy old array contents to new array
          for(int i = 0 ; i < nTokens ; ++i) {
            newTokens[i] = tokens[i];
          }
          tokens = newTokens;                                             // Replace old array by new array
        }
        if(type == StreamTokenizer.TT_WORD) {                             // Check for a word
          tokens[nTokens++] = tokenizer.sval;                             // and save it in the vector
        } else {
          assert false;                                                   // We only expect words
        }

      }
      // Store tokens in array of exactly the right size
      if(nTokens < tokens.length) {
        String[] newTokens = new String[nTokens];
        // Copy old array contents to new array
        for(int i = 0 ; i < nTokens ; ++i) {
          newTokens[i] = tokens[i];
        }
        tokens = newTokens;                                               // Replace old array by new array
      }
    } catch(IOException e) {
      e.printStackTrace();
      System.exit(1);
    }

    return tokens;
  }

  // Convenience method to change the separator
  public void setSeparator(char separator) {
    this.separator = separator;
    setTokenizerState();
  }
}

This is the main Class to Test Above Java Class ' ParseInput '.

public class TestParseInput {
  public static void main(String[] args) {
    char separator = ',';
    ParseInput tokenizer = new ParseInput(separator);
    parseInputLine(tokenizer, separator);

    // Try a different separator
    separator = '/';
    tokenizer.setSeparator(separator);
    parseInputLine(tokenizer, separator);
  }

  // Reusable parse input operation
  static void parseInputLine(ParseInput tokenizer, char separator) {
    System.out.println("\nEnter items separated by " + separator + ":");
    String[] inputs = tokenizer.readTokens();

    if(inputs.length != 0) {
      System.out.println("The items that you entered are:");
      for( String input : inputs) {
        System.out.print("  " + input);
      }
    }
  }
}


Output of Above Java Program
Enter items separated by ,:
java, programs, and, examples, blog
The items that you entered are:
java programs and examples blog
Enter items separated by /:
java/programs/and/example/blog
The items that you entered are:
java programs and example blog

[ Read More ]
Read more...

A Java Program that Calls a Method that Throws an Exception of type ArithmeticException

Posted by Admin at 8:49 AM – 0 comments
 
Write a program that calls a method that throws an exception of type ArithmeticException at a random iteration in a for loop. Catch the exception in the method and pass the iteration count when the exception occurred to the calling method by using an object of an exception class you define.

public class IteratedArithmeticException extends Throwable {

  // Default Constructor:
  public IteratedArithmeticException(){}

  // Standard constructor:
  public IteratedArithmeticException(String s, Throwable cause) {
    super(s, cause);                                                   // Call the base constructor.
  }

  public IteratedArithmeticException(int iteration, Throwable cause) {
    super(cause);                                                      // Call the base constructor.

    this.iteration = iteration;                                        // Set the iteration number.

  }

  public int getIteration() {                                          // Get the array index value for the error.
    return iteration;                                                  // Return the iteration number.
  }

  // The default value of -1 can be used to check whether an iteration number was stored
  private int iteration = -1;                                          // Iteration number at which exception occurred.
}

This is the Main to Test the Above Java  IteratedArithmeticException Class which Extends Throwable class. 

public class TestIterated {
  public static void main(String args[]) {
    try {
      loopy();                                                         // Call the method that will throw the exception.
    } catch(IteratedArithmeticException e) {
      System.out.println("Originating exception was: " + e.getCause());
      int iteration = e.getIteration();
      if(iteration < 0) {
      System.out.println("Iteration count not recorded");
      } else {
        System.out.println("Iteration count when exception occurred: " + iteration);
      }
    }
  }

  // This method throws an exception - eventually:
  static void loopy() throws IteratedArithmeticException {
    int iteration = 0;                                                 // Iteration counter.
    int result = 0;                                                    // Stores a result.
    int divisor = 0;                                                   // Random divisor.

    // Loop will continue until an exception is thrown:
    for(iteration = 0 ; ; ++iteration)
      try {
        divisor = (int)(100*Math.random());                            // Generate a random divisor.
        result = 1000/divisor;                                         // If we hit zero - bingo!
      } catch(ArithmeticException e) {
        throw new IteratedArithmeticException(iteration, e);
      }
  }
}



Output of Above Java Program
Originating exception was: java.lang.ArithmeticException: / by zero
Iteration count when exception occurred: 18

[ Read More ]
Read more...

A Java Example to Create your own Exception.

Posted by Admin at 7:11 AM – 0 comments
 
Add an exception class to the last example that differentiates between the index-out-of-bounds error possibilities, rethrows an appropriate object of this exception class in divide(), and handles the exception in main().

This is an Example to define your own Exception we will use this Class in Main Class to Catch Divided by Zero Error.

public class ZeroDivideException extends Exception {
  private int index = -1;                                              // Index of array element causing error

  // Default Constructor
  public ZeroDivideException(){ }

  // Constructor that can be chained
  public ZeroDivideException(String s, Throwable cause) {
    super(s, cause);                                                   // Call the base constructor
  }

  // Contructor recording an index value & can be chained
  public ZeroDivideException(int index, Throwable cause) {
    super(cause);                                                      // Call the base constructor
    this.index = index;                                                // Set the index value
  }

  // Get the array index value for the error
  public int getIndex() {
    return index;                                                      // Return the index value
  }
}

This is an another Example to define your own Exception we will use this Class in Main Class to indentify  'IndexOutOfBounds'  Exception.

public class IdentifyIndexOutOfBoundsException extends Exception {
  // Default Constructor
  public IdentifyIndexOutOfBoundsException(){ }

  // Constructor that can be chained
  public IdentifyIndexOutOfBoundsException(String s, Throwable cause) {
    super(s, cause);                                                   // Call the base constructor
  }

  // Contructor recording an index value & can be chained
  public IdentifyIndexOutOfBoundsException(int index, Throwable cause) {
    super(cause);                                                      // Call the base constructor
    this.index = index;                                                // Set the index value
    gotIndex = true;                                                   // Set index flag
  }

  // Text for when an index value is available
  boolean hasIndex() {
    return gotIndex;
  }
  // Get the array index value for the error
  public int getIndex() {
    return index;                                                      // Return the index value
  }

  private boolean gotIndex = false;                                    // True indicates an index value is available
  private int index = 0;                                               // In index in error
}

This is the main Class to Test Above Classese

public class TryChainedExceptions {

  public static void main(String[] args) {
    int[] x = {10, 5, 0, 3, 12, 0, 6};                                 // Array of  integers
    System.out.print("Values: ");
    for(int xValue : x) {
      System.out.print("  " + xValue);
    }
    System.out.println();

    for(int i = 0 ; i < x.length ; ++i) {
      // This block only throws an exception if method divide() does
      try {
        System.out.println("First try block in main()entered");
        System.out.println("result = " + divide(x,i));
      } catch(ZeroDivideException e) {
        System.out.println("\nZeroDivideException caught in main()");
        int index = e.getIndex();                                      // Get the index for the error
        if(index > 0) {                                                // Verify it is valid and now fix the array
          x[index] = 1;                                                // ...set the divisor to 1...
          x[index + 1] = x[index - 1];                                 // ...and set the result
          e.printStackTrace();
          System.err.println("Zero divisor at x[" + index + "] corrected to " + x[index]);
        }
      } catch(ArithmeticException e) {
        System.out.println("Arithmetic exception caught in main()");
      } catch(IdentifyIndexOutOfBoundsException e) {
        System.out.println("Precise-index-out-of-bounds exception caught in main()");

        Throwable original = e.getCause();
        if(original != null) {
          System.out.println("Original exception was: " + original);
        }

        if(e.hasIndex()){
        System.out.println("Index value out of bounds is: " + e.getIndex());
        }
      }
      System.out.println("Outside first try block in main()");
    }
    System.out.print("Values: ");
    for(int xValue : x) {
      System.out.print("  " + xValue);
    }
    System.out.println();
  }

  public static int divide(int[] array, int index) throws ZeroDivideException, IdentifyIndexOutOfBoundsException {
    try {
      System.out.println("\nFirst try block in divide() entered");
      array[index] = array[index+2]/array[index + 1];
      System.out.println("Code at end of first try block in divide()");
      return array[index + 2];

    } catch(ArithmeticException e) {
      System.out.println("Arithmetic exception caught in divide()");
      ZeroDivideException zde = new ZeroDivideException(index + 1, e);
      System.out.println("Throwing ZeroDivideException");
      throw zde;                                                       // Throw the new exception
    } catch(ArrayIndexOutOfBoundsException e) {
      System.out.println("Index-out-of-bounds index exception caught in divide()");

      // We need to figure which of the three index values caused the problem
      int errorIndex = 0;                                              // Record the index value in error
      if(index < 0 || index >= array.length) {                         // Check for negative index or index greater than array length
        errorIndex = index;
      } else {
        // Two possibilities remain. The error index value was either
        // index+1 or index+2
        errorIndex = index + 1 > array.length ? index + 1 : index + 2;
      }
      throw new IdentifyIndexOutOfBoundsException(errorIndex, e);
    }
    // Because we now throw an exception in the previous catch block,
    // the following code annot be reached so it is commented out.
//    System.out.println("Executing code after try block in divide()");
//    return array[index];
  }
}

Output of Above Java Program
Values: 10 5 0 3 12 0 6
First try block in main()entered

First try block in divide() entered
Code at end of first try block in divide()
result = 0
Outside first try block in main()
First try block in main()entered

First try block in divide() entered
Arithmetic exception caught in divide()
Throwing ZeroDivideException

ZeroDivideException caught in main()
ZeroDivideException: java.lang.ArithmeticException: / by zero
at test.divide(test.java:109)
at test.main(test.java:67)
Caused by: java.lang.ArithmeticException: / by zero
at test.divide(test.java:103)
... 1 more
Zero divisor at x[2] corrected to 1
Outside first try block in main()
First try block in main()entered

First try block in divide() entered
Code at end of first try block in divide()
result = 12
Outside first try block in main()
First try block in main()entered

First try block in divide() entered
Code at end of first try block in divide()
result = 0
Outside first try block in main()
First try block in main()entered

First try block in divide() entered
Arithmetic exception caught in divide()
Throwing ZeroDivideException

ZeroDivideException caught in main()
ZeroDivideException: java.lang.ArithmeticException: / by zero
at test.divide(test.java:109)
at test.main(test.java:67)
Caused by: java.lang.ArithmeticException: / by zero
at test.divide(test.java:103)
... 1 more
Zero divisor at x[5] corrected to 1
Outside first try block in main()
First try block in main()entered

First try block in divide() entered
Index-out-of-bounds index exception caught in divide()
Precise-index-out-of-bounds exception caught in main()
Original exception was: java.lang.ArrayIndexOutOfBoundsException: 7
Index value out of bounds is: 7
Outside first try block in main()
First try block in main()entered

First try block in divide() entered
Index-out-of-bounds index exception caught in divide()
Precise-index-out-of-bounds exception caught in main()
Original exception was: java.lang.ArrayIndexOutOfBoundsException: 8

Index value out of bounds is: 8
Outside first try block in main()
Values: 0 5 2 0 12 1 12

[ 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...
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

  • 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 ...
  • 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) { /...
  • Reading large excel files
    By using this we can read excel sheets having large size package com.excel.reader; import java.io.File; import java.io.FileOutputStream;...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • 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; ...
  • 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...
  • 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...
  • Sudoku Puzzle Game in Java
    import java.io.*; import java.util.*; public class SudokuSolver { public static void main(String[] args) throws Exception { /...
  • 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...
  • Java Program to Generate the Lottery Number between 1 to 49
     A lottery requires that you select six different numbers from the integers 1 to 49. Write a program to do this for you and generate five s...
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; ...
  • 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...
  • 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) { /...
  • 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...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • Java Program to Generate the Lottery Number between 1 to 49
     A lottery requires that you select six different numbers from the integers 1 to 49. Write a program to do this for you and generate five s...
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger