- Java Basic Examples
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
Java Sample Programs
Fall 2002
A
Revised Version of Hello World
import
java.io.*;
class
MyFirstProgram {
/** Print a hello message */
public static void main(String[] args) {
BufferedReader in =
new BufferedReader(new
InputStreamReader(System.in));
String name = "Instructor";
System.out.print("Give your name:
");
try {name = in.readLine();}
catch(Exception e) {
System.out.println("Caught an
exception!");
}
System.out.println("Hello " +
name + "!");
}
}
A
Java Program with Looping
class
Fibonacci {
//
Print out the Fibonacci sequence for values < 50
public
static void main(String[] args) {
int lo = 1;
int hi = 1;
System.out.println(lo);
while (hi < 50) {
System.out.print(hi);
hi = lo + hi; // new hi
lo = hi - lo; /* new lo is (sum - old lo)
i.e., the old hi */
}
}
A
Java Class
class
Point {
public double x, y;
public static Point origin = new Point(0,0);
// This always refers to an object at
(0,0)
Point(double x_value, double y_value) {
x = x_value;
y = y_value;
}
public void clear() {
this.x = 0;
this.y = 0;
}
public double distance(Point that) {
double xDiff = x - that.x;
double yDiff = y - that.y;
return Math.sqrt(xDiff * xDiff + yDiff *
yDiff);
}
}
Extending
a Class: Inheritance
class
Pixel extends Point {
Color color;
public void clear() {
super.clear();
color = null;
}
}
Interfaces
interface
Lookup {
/** Return the value associated with the
name, or
* null if there is no such value */
Object find(String name);
}
void
processValues(String[] names, Lookup table) {
for (int i = 0; i ! names.length; i++) {
Object value = table.find(names[i]);
if (value != null)
processValue(names[i], value);
}
}
class
SimpleLookup implements Lookup {
private String[] Names;
private Object[] Values;
public Object find(String name) {
for (int i = 0; i < Names.length; i++)
{
if (Names[i].equals(name))
return Values[i];
}
return null; // not found
}
// ...
}
Creating
Threads in Java
public
class PingPONG extends Thread {
private String word; // What word to
print
private int delay; // how long to
pause
public PingPONG(String whatToSay, int
delayTime) {
word = whatToSay;
delay = delayTime;
}
public void run() {
try {
for (;;) {
System.out.print(word + "
");
sleep(delay); // wait until
next time
}
} catch (InterruptedException e) {
return; // end this thread;
}
}
public static void main(String[] args) {
new PingPONG("Ping",
33).start(); // 1/30 second
new
PingPONG("PONG",100).start(); // 1/10 second
}
}
Two
Synchronization Methods
class
Account {
private double balance;
Public Account(double initialDeposit) {
balance = initialDeposit;
}
public synchronized double getBalance() {
return balance;
}
public synchronized viod deposit(double
amount) {
balance += amont;
}
}
/**
make all elements in the array non-negative */
public
static void abs(int[] values) {
synchronized (values) {
for (int i = 0; i < values.length;
i++) {
if (values[i] < 0)
values[i] = -values[i];
}
}
}
HTML
Applet Tags
<APPLETT
CODE=classFileName // .class
HEIGHT=height // in pixels
WIDTH=width? // Only these 3 are
required.
[CODEBASE=classFileDirectory]
// if different from the HTML file
[NAME=appletName]
// so that applets can refer to
each other
[ALT=alternateText]
[ALIGN=alignment]
[HSPACE=spaceInPixels]
[VSPACE=spaceInPixels]
[<PARAM NAME=parameterName
VALUE=parameterValue>]
[<PARAM...>]
</APPLET>
Java
Coding Samples
Various Java programs to illustrate various concepts
·
A Hello
World! Java program.
·
Calling
Methods. A sample of how to call methods in the same class.
·
For
loop. A simple example of using for loops to calculate factorial. Uses the
built in int data type so only good to 13!
·
Value
Parameters: An example that shows the behavior of value parameters. In Java
all parameters are passed by value.
·
String
Example. A few brief examples of String manipulations.
·
BinaryConverter.
A program with examples of various Java syntax that converts a base 10 int to
base 2 String.
·
PrimeEx
A program with various approaches to determine if an int is prime or not.
Used to demonstrate Java syntax. You need the Stopwatch
class, a non standard Java class, as well.
·
2D
array Example. A simplified version of filtering a picture represented by
ints.
·
2D
array example. Very simple version of the Conway's Game of Life.
·
Program
to create ASCII frequency table from file and url. Demonstration of try /
catch blocks. The CIA 2008 Factbook may be downloaded from Project Gutenberg.
·
IntListVer1
First version of the IntList class developed in class. Developing class to
illustrate various class design and implementation issues in Java.
·
IntListVer2
Added default add method, equals method, and toString methods. Includes
versions of toString using String concatenation and StringBuffer to illustarte
performance differences.
·
IntListVer3.
Added insert and remove methods.
·
SortedIntList.
Inherits from InListVer3 to create a SortedIntList. Class is "broken"
because random insertions still allowed.
·
GenericList.
Altered the list to store anything, not just ints.
·
Die
class. A class that models a playing die.
·
DemoClass:
This illustrates some of the more confusing concepts in class syntax and
mechanics such as constructors, static vs. instance methods, and method
overloading.
·
Stopwatch
class. A class for measuring how long it takes for a program to run.
·
Create
a Set. A method that using polymorphism to create a set from an array.
·
Recursion
examples. Includes examples on finding space taken up by files in a
directory including all files in all subdirectories, recursive factorial,
recursive power, recursive Fibonacci numbers, and a simple knapsack problem.
·
Eight
Queens example. Code to find a a solution to an N queens problem. Note the
queensAreSafe method has not been completed.
·
Airlines
example. Determine if airlines can be moved from airline to another based
on network of airline partners. Here is a sample
input file.
·
Minesweeper.
Another example of recursion from the game minesweeper.
·
GenericListVersion2.
Changed the GenericList class so that it implements the Iterable
interface in order to demonstrate how to implement an iterator
using an inner class.
·
GenericListVersion3.
Changed GenericList so it is generic based on Java generics syntax instead of
relying on Object.
·
ListNode.
A singly linked node class used to build linked lists
·
IList.
A simple list interface
·
LinkedList.
Similar to the LinkedList developed in class. Does not contain all the methods
you would expect of a LinkedList. Also implements the iterator remove method in
O(N) time. An O(1) time remove method is possible.
·
UnsortedHashSet
- An unsorted set that uses a hashtable with closed address hashing to store
values. Currently only the add method is implemented.
·
UnsortedSetTest
- A method to compare Java's TreeSet and HashSet to the BianrySearchTree,
UnsortedSet, and UnsortedHashSet classes developed in class. Note you need a
lot of other files for this to work.
·
SimpleWordCount
- Program demonstrating use of a map to count the frequency of words in a
file.
·
WordCount
- Program that compares counting words in files using an ArrayList
and a Map.
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment