Application that reports all command-line arguments #Programming Code Examples #Java/J2EE/J2ME #Basic Java

******************
ShowArgs.java Application that reports all command-line arguments.
******************
 */

public class ShowArgs {
  public static void main(String[] args) {
    for(int i=0; i<args .length; i++) {
      System.out.println("Arg " + i + " is " + args[i]);
    }
  }
}
/*

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10398
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Basic Hello World application #Programming Code Examples #Java/J2EE/J2ME #Basic Java

*******************
HelloWorld.java Basic Hello World application. 
*******************
 */

public class HelloWorld {
 public static void main(String[] args) {
    System.out.println("Hello, world.");
  }
}
/*

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10397
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

DropBall.java Uses a while loop to determine how long it takes a ball to fall from the top of the Washington Monument to the ground #Programming Code Examples #Java/J2EE/J2ME #Basic Java

DropBall.java Uses a while loop to determine how long it takes a ball to fall from the top of the Washington Monument to the ground
************************************************************
/** Simulating dropping a ball from the top of the Washington
 *  Monument. The program outputs the height of the ball each
 *  second until the ball hits the ground.
 *
 *****************************************

public class DropBall {
  public static void main(String[] args) {
    int time = 0;
    double start = 550.0, drop = 0.0;
    double height = start;
    while (height > 0) {
      System.out.println("After " + time + 
                   (time==1 ? " second, " : " seconds,") + 
                   "the ball is at " + height + " feet.");
      time++;                   
      drop = freeFall(time);
      height = start - drop;
    }
    System.out.println("Before " + time + " seconds could " +
                       "expire, the ball hit the ground!");
  }
  
  /** Calculate the distance in feet for an object in 
   *  free fall. 
   */

  public static double freeFall (float time) {
    // Gravitational constant is 32 feet per second squared
    return(16.0 * time * time); // 1/2 gt^2
  }
}
@@@@@@@@@@@@@@@@@@@@

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10386
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:39

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

StringTest.java Demonstrates various methods of the String class. #Programming Code Examples #Java/J2EE/J2ME #Basic Java

/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */


  public class StringTest {
  public static void main (String[] args) {
    String str = "";
    if (args.length > 0) {
        str = args[0];
    }
    if (str.length()>8) {
      System.out.println("String is "" + str + ""n");
      System.out.println("  charAt(3) ------------------ " +
                         str.charAt(3));
      System.out.println("  compareTo(Moscow) ---------- " +
                         str.compareTo("Moscow"));
      System.out.println("  concat(SuFFiX) ------------- " +
                         str.concat("SuFFiX"));
      System.out.println("  endsWith(hic) -------------- " +
                         str.endsWith("hic"));
      System.out.println("  == Geographic -------------- " +
                         (str == "Geographic"));
      System.out.println("  equals(geographic) --------- " +
                         str.equals("geographic"));
      System.out.println("  equalsIgnoreCase(geographic) " +
                         str.equalsIgnoreCase("geographic"));
      System.out.println("  indexOf('o') --------------- " +
                         str.indexOf('o'));
      System.out.println("  indexOf('i',5) ------------- " +
                         str.indexOf('i',5));
      System.out.println("  indexOf('o',5) ------------- " +
                         str.indexOf('o',5));
      System.out.println("  indexOf(rap) --------------- " +
                         str.indexOf("rap"));
      System.out.println("  indexOf(rap, 5) ------------ " +
                         str.indexOf("rap", 5));
      System.out.println("  lastIndexOf('o') ----------- " +
                         str.lastIndexOf('o'));
      System.out.println("  lastIndexOf('i',5) --------- " +
                         str.lastIndexOf('i',5));
      System.out.println("  lastIndexOf('o',5) --------- " +
                         str.lastIndexOf('o',5));
      System.out.println("  lastIndexOf(rap) ----------- " +
                         str.lastIndexOf("rap"));
      System.out.println("  lastIndexOf(rap, 5) -------- " +
                         str.lastIndexOf("rap", 5));
      System.out.println("  length() ------------------- " +
                         str.length());
      System.out.println("  replace('c','k') ----------- " +
                         str.replace('c','k'));
      System.out.println("  startsWith(eog,1) ---------- " +
                         str.startsWith("eog",1));
      System.out.println("  startsWith(eog) ------------ " +
                         str.startsWith("eog"));
      System.out.println("  substring(3) --------------- " +
                         str.substring(3));
      System.out.println("  substring(3,8) ------------- " +
                         str.substring(3,8));
      System.out.println("  toLowerCase() -------------- " +
                         str.toLowerCase());
      System.out.println("  toUpperCase() -------------- " +
                         str.toUpperCase());
      System.out.println("  trim() --------------------- " +
                         str.trim());
      System.out.println("nString is still "" + str + ""n");
    }
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10225
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

NumFormat.java Formats real numbers with DecimalFormat. #Programming Code Examples #Java/J2EE/J2ME #Basic Java

import java.text.*;

/** Formatting real numbers with DecimalFormat.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NumFormat {
  public static void main (String[] args) {
    DecimalFormat science = new DecimalFormat("0.000E0");
    DecimalFormat plain = new DecimalFormat("0.0000");

    for(double d=100.0; d<140.0; d*=1.10) {
      System.out.println("Scientific: " + science.format(d) +
                         " and Plain: " + plain.format(d));
    }
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10224
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

NegativeLengthException.java Illustrates defining and throwing your own exceptions. #Programming Code Examples #Java/J2EE/J2ME #Basic Java


import java.io.*;

/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NegativeLengthException extends Exception {

  /** Test NegativeLengthException */

  public static void main(String[] args) {
    try {
      int lineLength = readLength();
      for(int i=0; i<linelength ; i++) {
        System.out.print("*");
      }
      System.out.println();
    } catch (NegativeLengthException nle) {
      System.out.println("NegativeLengthException: " +
                         nle.getMessage());
    }
  }

  public NegativeLengthException() {
    super("Negative dimensions not permitted.");
  }

  public NegativeLengthException(String message) {
    super(message);
  }

  // readLength catches IOExceptions locally but lets the
  // calling method handle NegativeLengthExceptions.
  private static int readLength() throws NegativeLengthException {
    BufferedReader in = new BufferedReader(
                          new InputStreamReader(System.in));
    System.out.print("Enter length: ");
    System.out.flush();
    int len = 0;
    try {
      String line = in.readLine();
      len = Integer.parseInt(line);
      if (len < 0) {
        throw new NegativeLengthException();
      }
    } catch (IOException ioe) {
      System.out.println("Problem reading from keyboard");
    }
    return(len);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10223
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

ModificationTest.java Demonstrates changing fields of an object. Inherits from ReferenceTest.java. #Programming Code Examples #Java/J2EE/J2ME #Basic Java

/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

import java.awt.Point;

public class ModificationTest extends ReferenceTest {
  public static void main(String[] args) {
    Point p1 = new Point(1, 2); // Assign Point to p1
    Point p2 = p1; // p2 is new reference to *same* Point
    print("p1", p1); // (1, 2)
    print("p2", p2); // (1, 2)
    munge(p2); // Changes fields of the *single* Point
    print("p1", p1); // (5, 10)
    print("p2", p2); // (5, 10)
  }

  public static void munge(Point p) {
    p.x = 5;
    p.y = 10;
  }
}


/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

import java.awt.Point;

public class ReferenceTest {
  public static void main(String[] args) {
    Point p1 = new Point(1, 2); // Assign Point to p1
    Point p2 = p1; // p2 is new reference to *same* Point
    print("p1", p1); // (1, 2)
    print("p2", p2); // (1, 2)
    triple(p2); // Doesn?t change p2
    print("p2", p2); // (1, 2)
    p2 = triple(p2); // Have p2 point to *new* Point
    print("p2", p2); // (3, 6)
    print("p1", p1); // p1 unchanged: (1, 2)
  }

  public static Point triple(Point p) {
    p = new Point(p.x * 3, p.y * 3); // Redirect p
    return(p);
  }

  public static void print(String name, Point p) {
    System.out.println("Point " + name + "= (" +
                       p.x + ", " + p.y + ").");
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10222
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

TreeTest.java Builds a binary tree and prints the contents of the nodes. Uses the following classes: #Programming Code Examples #Java/J2EE/J2ME #Basic Java

Treetest.java
/** A NodeOperator that prints each node.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

class PrintOperator implements NodeOperator {
  public void operateOn(Node node) {
    System.out.println(node.getNodeValue());
  }
}

/** A sample tree representing a parse tree of
 *  the sentence "Java hackers hack Java", using
 *  some simple context-free grammar.
 */

public class TreeTest {
  public static void main(String[] args) {
    Node adjective =
      new Node("  Adjective", new Leaf("   Java"));
    Node noun1 =
      new Node("  Noun", new Leaf("   hackers"));
    Node verb =
      new Node("  TransitiveVerb", new Leaf("   hack"));
    Node noun2 =
      new Node("  Noun", new Leaf("   Java"));
    Node np = new Node(" NounPhrase", adjective, noun1);
    Node vp = new Node(" VerbPhrase", verb, noun2);
    Node sentence = new Node("Sentence", np, vp);
    PrintOperator printOp = new PrintOperator();
    System.out.println("Depth first traversal:");
    sentence.depthFirstSearch(printOp);
    System.out.println("nBreadth first traversal:");
    sentence.breadthFirstSearch(printOp);
  }
}

Leaf.java
A leaf node with no children.
/** Leaf node: a node with no subtrees.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class Leaf extends Node {
  public Leaf(Object value) {
    super(value, null, null);
  }
}

Node.java A data structure representing a node in a binary tree. 


import java.util.Vector;

/** A data structure representing a node in a binary tree.
 *  It contains a node value and a reference (pointer) to
 *  the left and right subtrees.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class Node {
  private Object nodeValue;
  private Node leftChild, rightChild;

 /** Build Node with specified value and subtrees. */

  public Node(Object nodeValue, Node leftChild,
              Node rightChild) {
    this.nodeValue = nodeValue;
    this.leftChild = leftChild;
    this.rightChild = rightChild;
  }

  /** Build Node with specified value and L subtree. R child
   *  will be null. If you want both children to be null, use
   *  the Leaf constructor.
   */

  public Node(Object nodeValue, Node leftChild) {
    this(nodeValue, leftChild, null);
  }

  /** Return the value of this node. */

  public Object getNodeValue() {
    return(nodeValue);
  }

  /** Specify the value of this node. */

  public void setNodeValue(Object nodeValue) {
    this.nodeValue = nodeValue;
  }

 /** Return the L subtree. */

  public Node getLeftChild() {
    return(leftChild);
  }

  /** Specify the L subtree. */

  public void setLeftChild(Node leftChild) {
    this.leftChild = leftChild;
  }

  /** Return the R subtree. */

  public Node getRightChild() {
    return(rightChild);
  }

  /** Specify the R subtree. */

  public void setRightChild(Node rightChild) {
    this.rightChild = rightChild;
  }

  /** Traverse the tree in depth-first order, applying
   *  the specified operation to each node along the way.
   */

  public void depthFirstSearch(NodeOperator op) {
    op.operateOn(this);
    if (leftChild != null) {
      leftChild.depthFirstSearch(op);
    }
    if (rightChild != null) {
      rightChild.depthFirstSearch(op);
    }
  }

  /** Traverse the tree in breadth-first order, applying the
   *  specified operation to each node along the way.
   */

  public void breadthFirstSearch(NodeOperator op) {
    Vector nodeQueue = new Vector();
    nodeQueue.addElement(this);
    Node node;
    while(!nodeQueue.isEmpty()) {
      node = (Node)nodeQueue.elementAt(0);
      nodeQueue.removeElementAt(0);
      op.operateOn(node);
      if (node.getLeftChild() != null) {
        nodeQueue.addElement(node.getLeftChild());
      }
      if (node.getRightChild() != null) {
        nodeQueue.addElement(node.getRightChild());
      }
    }
  }
}

NodeOperator.java An interface used in the Node class to ensure that an object has an operateOn method. 

/** An interface used in the Node class to ensure that
 *  an object has an operateOn method.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public interface NodeOperator {
  void operateOn(Node node);
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10221
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Tests the class type of an object using the isInstance method (preferred over instanceof operator). #Programming Code Examples #Java/J2EE/J2ME #Basic Java


/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

interface Barking {}

class Mammal {}

class Canine extends Mammal {}

class Dog extends Canine implements Barking {}

class Retriever extends Dog {}

public class InstanceOf {
  public static void main(String[] args) {
    Canine wolf = new Canine();
    Retriever rover = new Retriever();

    System.out.println("Testing instanceof:");
    report(wolf, "wolf");
    System.out.println();
    report(rover, "rover");

    System.out.println("nTesting isInstance:");
    Class barkingClass = Barking.class;
    Class dogClass = Dog.class;
    Class retrieverClass = Retriever.class;
    System.out.println("  Does a retriever bark? " +
                       barkingClass.isInstance(rover));
    System.out.println("  Is a retriever a dog? " +
                       dogClass.isInstance(rover));
    System.out.println("  Is a dog necessarily a retriever? " +
                       retrieverClass.isInstance(new Dog()));
  }

  public static void report(Object object, String name) {
    System.out.println("  " + name + " is a mammal: " +
                       (object instanceof Mammal));
    System.out.println("  " + name + " is a canine: " +
                       (object instanceof Canine));
    System.out.println("  " + name + " is a dog: " +
                       (object instanceof Dog));
    System.out.println("  " + name + " is a retriever: " +
                       (object instanceof Retriever));
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10220
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Illustrates the use of arrays #Programming Code Examples #Java/J2EE/J2ME #Basic Java

/** Report on a round of golf at St. Andy?s.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class Golf {
  public static void main(String[] args) {
    int[] pars   = { 4,5,3,4,5,4,4,3,4 };
    int[] scores = { 5,6,3,4,5,3,2,4,3 };
    report(pars, scores);
  }

  /** Reports on a short round of golf. */

  public static void report(int[] pars, int[] scores) {
    for(int i=0; i<scores .length; i++) {
      int hole = i+1;
      int difference = scores[i] - pars[i];
      System.out.println("Hole " + hole + ": " +
                         diffToString(difference));
    }
  }

  /** Convert to English. */

  public static String diffToString(int diff) {
    String[] names = {"Eagle", "Birdie", "Par", "Bogey",
                      "Double Bogey", "Triple Bogey", "Bad"};
    // If diff is -2, return names[0], or "Eagle".
    int offset = 2;
    return(names[offset + diff]);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10219
Categories:Programming Code Examples, Java/J2EE/J2ME, Basic Java
Tags:Java/J2EE/J2MEBasic Java
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada