Sample JAVA Programs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

http://www.cs.uvm.

edu/~xwu/Java/SamplePr
ograms.shtml
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>

https://www2.cs.uic.edu/~sloan/CLASSES/java/

Java Example Program


The following two web pages are important. They contain nearly all of the
information a Java programmer might need about the various Java library classes.

 Main Java Sun Web Page


 Alphabetical Listing of Java Library Classes
 (See Java Sun API Specification Page for other versions, etc.)

Compiling and running a java program

 To create a Java program, you must ensure that the name of the class in the
file is the same as the name of the file (and that the file has the extension
.java).
 To compile the program use the command javac as in:
 javac HelloWorld.java

This will take the source code in the file HelloWorld.java (which better contain
the class HelloWorld) and create the Java ByteCode in a file HelloWorld.class.

 To run the compiled program use the command java as in:


 java HelloWorld

Note that you do not use the any file extension in this command.

Very Simple Java Example Programs

 HelloWorld.java
 HelloDate.java
 FunctionCall.java

Array usage in Java

 A tutorial on using arrays in java


 ArrayDemo.java

Class Usage in Java

 Point2d.java
 Test jig for Point2d class (PointTester.java)
 Point3d.java

I/O and files in Java

 KeyboardIntegerReader.java
 KeyboardReader.java
 MyFileReader.java
 MyFileReader.txt
 MyFileWriter.java
 MyFileWriter.txt

Exception examples in Java

 HelloWorldException.java
 KeyboardReaderError.java
 DivBy0.java

On Going Help and Assistance

Contact the UIC Student Chapter of the ACM for additional help. The ACM Office is in 1309
SEO and you can set up some tutoring by sending email to [email protected] or by
going to the ACM Tutoring Web Page

You might also like