Java code examples from Introduction to Programming in Java
1. HelloWorld.java
Below is the syntax highlighted version of HelloWorld.java from §1.1 Hello World.
/*************************************************************************
* Compilation: javac HelloWorld.java
* Execution: java HelloWorld
*
* Prints "Hello, World". By tradition, this is everyone's first program.
*
* % java HelloWorld
* Hello, World
*
* These 17 lines of text are comments. They are not part of the program;
* they serve to remind us about its properties. The first two lines tell
* us what to type to compile and test the program. The next line describes
* the purpose of the program. The next few lines give a sample execution
* of the program and the resulting output. We will always include such
* lines in our programs and encourage you to do the same.
*
*************************************************************************/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
UseArgument.java
Below is the syntax highlighted version of UseArgument.java from §1.1 Hello World.
/*************************************************************************
* Compilation: javac UseArgument.java
* Execution: java UseArgument yourname
*
* Prints "Hi, Bob. How are you?" where "Bob" is replaced by the
* command-line argument.
*
* % java UseArgument Bob
* Hi, Bob. How are you?
2. *
* % java UseArgument Alice
* Hi, Alice. How are you?
*
*************************************************************************/
public class UseArgument {
public static void main(String[] args) {
System.out.print("Hi, ");
System.out.print(args[0]);
System.out.println(". How are you?");
}
}
3. IntOps.java
/*************************************************************************
* Compilation: javac IntOps.java
* Execution: java IntOps a b
*
* Illustrates the integer operations a * b, a / b, and a % b.
*
* % java IntOps 1234 99
* 1234 + 99 = 1333
* 1234 * 99 = 122166
* 1234 / 99 = 12
* 1234 % 99 = 46
* 1234 = 12 * 99 + 46
*
* % java IntOps 10 -3
* 10 + -3 = 7
* 10 * -3 = -30
* 10 / -3 = -3
* 10 % -3 = 1
* 10 = -3 * -3 + 1
*
*************************************************************************/
public class IntOps {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
int prod = a * b;
int quot = a / b;
int rem = a % b;
System.out.println(a + " + " + b + " = " + sum);
System.out.println(a + " * " + b + " = " + prod);
System.out.println(a + " / " + b + " = " + quot);
System.out.println(a + " % " + b + " = " + rem);
System.out.println(a + " = " + quot + " * " + b + " + " + rem);
}
}
4. Quadratic.java
Below is the syntax highlighted version of Quadratic.java from §1.2 Built-in Types of Data.
/*************************************************************************
* Compilation: javac Quadratic.java
* Execution: java Quadatic b c
*
* Given b and c, solves for the roots of x*x + b*x + c.
* Assumes both roots are real valued.
*
* % java Quadratic -3.0 2.0
* 2.0
* 1.0
*
* % java Quadratic -1.0 -1.0
* 1.618033988749895
* -0.6180339887498949
*
* Remark: 1.6180339... is the golden ratio.
*
* % java Quadratic 1.0 1.0
* NaN
* NaN
*
*
*************************************************************************/
public class Quadratic {
public static void main(String[] args) {
double b = Double.parseDouble(args[0]);
double c = Double.parseDouble(args[1]);
double discriminant = b*b - 4.0*c;
double sqroot = Math.sqrt(discriminant);
double root1 = (-b + sqroot) / 2.0;
double root2 = (-b - sqroot) / 2.0;
System.out.println(root1);
System.out.println(root2);
}
}
5. LeapYear.java
Below is the syntax highlighted version of LeapYear.java from §1.2 Built-in Types of Data.
/*************************************************************************
* Compilation: javac LeapYear.java
* Execution: java LeapYear N
*
* Prints true if N corresponds to a leap year, and false otherwise.
* Assumes N >= 1582, corresponding to a year in the Gregorian calendar.
*
* % java LeapYear 2004
* true
*
* % java LeapYear 1900
* false
*
* % java LeapYear 2000
* true
*
*************************************************************************/
public class LeapYear {
public static void main(String[] args) {
int year = Integer.parseInt(args[0]);
boolean isLeapYear;
// divisible by 4
isLeapYear = (year % 4 == 0);
// divisible by 4 and not 100
isLeapYear = isLeapYear && (year % 100 != 0);
// divisible by 4 and not 100 unless divisible by 400
isLeapYear = isLeapYear || (year % 400 == 0);
System.out.println(isLeapYear);
}
}
6. LeapYear.java
/*************************************************************************
* Compilation: javac LeapYear.java
* Execution: java LeapYear N
*
* Prints true if N corresponds to a leap year, and false otherwise.
* Assumes N >= 1582, corresponding to a year in the Gregorian calendar.
*
* % java LeapYear 2004
* true
*
* % java LeapYear 1900
* false
*
* % java LeapYear 2000
* true
*
*************************************************************************/
public class LeapYear {
public static void main(String[] args) {
int year = Integer.parseInt(args[0]);
boolean isLeapYear;
// divisible by 4
isLeapYear = (year % 4 == 0);
// divisible by 4 and not 100
isLeapYear = isLeapYear && (year % 100 != 0);
// divisible by 4 and not 100 unless divisible by 400
isLeapYear = isLeapYear || (year % 400 == 0);
System.out.println(isLeapYear);
}
}
7. Sqrt.java
/*************************************************************************
* Compilation: javac Sqrt.java
* Execution: java Sqrt c
*
* Computes the square root of a nonnegative number c using
* Newton's method:
* - initialize t = c
* - replace t with the average of c/t and t
* - repeat until desired accuracy reached
*
* % java Sqrt 2
* 1.414213562373095
*
* % java Sqrt 1000000
* 1000.0
*
* % java Sqrt 0.4
* 0.6324555320336759
*
* % java Sqrt 1048575
* 1023.9995117186336
*
* % java Sqrt 16664444
* 4082.2106756021303
*
* % java Sqrt 0
* 0.0
*
* % java Sqrt 1e-50
* 9.999999999999999E-26
*
*
* Remarks
* ----------
* - using Math.abs() is required if c < 1
*
*
* Known bugs
* ----------
* - goes into an infinite loop if the input is negative
*
*************************************************************************/
public class Sqrt {
public static void main(String[] args) {
// read in the command-line argument
double c = Double.parseDouble(args[0]);
8. double epsilon = 1e-15; // relative error tolerance
double t = c; // estimate of the square root of c
// repeatedly apply Newton update step until desired precision is
achieved
while (Math.abs(t - c/t) > epsilon*t) {
t = (c/t + t) / 2.0;
}
// print out the estimate of the square root of c
System.out.println(t);
}
}
9. Average.java
/*************************************************************************
* Compilation: javac Average.java
* Execution: java Average < data.txt
* Dependencies: StdIn.java StdOut.java
*
* Reads in a sequence of real numbers, and computes their average.
*
* % java Average
* 10.0 5.0 6.0
* 3.0 7.0 32.0
* <Ctrl-d>
* Average is 10.5
* Note <Ctrl-d> signifies the end of file on Unix.
* On windows use <Ctrl-z>.
*
*************************************************************************/
public class Average {
public static void main(String[] args) {
int count = 0; // number input values
double sum = 0.0; // sum of input values
// read data and compute statistics
while (!StdIn.isEmpty()) {
double value = StdIn.readDouble();
sum += value;
count++;
}
// compute the average
double average = sum / count;
// print results
StdOut.println("Average is " + average);
}
}
10. ArrayEquals.java
/************************************************************************
* Compilation: javac ArrayEquals.java
* Execution: java ArrayEquals
*
* The function eq() takes two integer array arguments and returns
* true if they have the same length and all corresponding pairs
* of integers are equal.
*
* % java ArrayEquals
* true
* false
* true
* false
*
*************************************************************************/
public class ArrayEquals {
// return true if two integer arrays have same length and all
// corresponding pairs of integers are equal
public static boolean eq(int[] a, int[] b) {
// same length?
if (a.length != b.length) return false;
// check each corresponding pair
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
// all elements must be equal
return true;
}
// test client
public static void main(String[] args) {
int[] a = { 3, 1, 4, 1, 5 };
int[] b = { 3, 1, 4, 1 };
int[] c = { 3, 1, 4, 1, 5 };
int[] d = { 2, 7, 1, 8, 2 };
StdOut.println(eq(a, a));
StdOut.println(eq(a, b));
StdOut.println(eq(a, c));
StdOut.println(eq(a, d));
}
}
11. WordCount.java
/*************************************************************************
* Compilation: javac WordCount.java
* Execution: java WordCount
* [ input required from standard input ]
* [ use Ctrl-d (OS X or Dr. Java) or Ctrl-z (Windows) for EOF ]
*
* Dependencies: StdIn.java StdOut.java
*
* Read in a sequence of strings from standard input and print out
* the number of strings read in.
*
* % java WordCount
* it was the best of times
* it was the worst of times
* number of words = 12
* Ctrl-d
*
* % java WordCount < tale.txt
* number of words = 139043
*
*************************************************************************/
public class WordCount {
public static void main(String[] args) {
int count = 0;
while (!StdIn.isEmpty()) {
String word = StdIn.readString();
count++;
}
// output
StdOut.println("number of words = " + count);
}
}
12. RandomSeq.java
/*************************************************************************
* Compilation: javac RandomSeq.java
* Execution: java RandomSeq N
*
* Prints N numbers between 0 and 1.
*
* % java RandomSeq 5
* 0.1654760343787165
* 0.6212262060326124
* 0.631755596883274
* 0.4165639935584283
* 0.4603525361488371
*
*************************************************************************/
public class RandomSeq {
public static void main(String[] args) {
// command-line argument
int N = Integer.parseInt(args[0]);
// generate and print N numbers between 0 and 1
for (int i = 0; i < N; i++) {
System.out.println(Math.random());
}
}
}