Tuesday, December 16, 2008
How to Search Open Source Code
Monday, May 05, 2008
Methods
Introduction
A method is a named block that can be called, and where program execution can continue. Other names for methods in non-object-oriented languages are functions and procedures. But unlike functions and procedures, methods are also members of a class.
Program
1 package sharingjava; 2 3 public class Example { 4 5 public static void main(String[] args) { 6 System.out.println("Hello World!"); 7 } 8 9 }
Discussion
In the example program, the main method starts at line 5. The main method is a method that serves as a starting point for program execution. The main method is called automatically when program execution begins. You will get a runtime error if this method is missing.
One more thing... It's impossible to know that your program need the main method just by examining the grammar. You will not find it there.
Here is the Java grammar for writing methods:
Tuesday, April 22, 2008
Old Table of Contents
- Introduction to Programs and Programming
- Keywords
- The Shortest Java Program Ever
- The Keyword 'class'
- The 'main' Method
- Explicit and Implicit Code
- Syntax Decoration
- Values, Operators, Expressions, Types and Variables
- More about Types
- Conversions
- Control Structures
- Sequence
- Conditional
- Iteration
- Jump Statements
- The 'break' Statement
- The 'continue' Statement
- The 'return' Statement
- Branching Statements
- The 'if' Statement
- The 'else' Statement
- The 'switch' Statement
- The 'break', 'continue' and 'return' statements are not Branching Statements
- Recursion
- Escape Sequence
- Classes
- Class Body
- Parameters and Arguments
- The 'equals' Method
- Objects
- Not Everything is an Object
- Static Import
- static Fields
- Access Control
- Static Factory Methods
- The java.lang Package
- The String Class
- indexOf()
- endsWith()
- compareTo()
- The Object Class
- The Math Class
- The random Method
- Bugs
- Memoization
- Binary Numbers
- Language Extensions
- J2SE 1.4.0 (Merlin)
- J2SE 5.0 (1.5.0) (Tiger)
- Generics
- Enhanced 'for' Loop
- Autoboxing/Unboxing
- Typesafe Enums
- Varargs
- Static Import
- Metadata (Annotations)
- J2SE 6.0 (1.6.0) (Mustang)
- J2SE 7.0 (1.7.0) (Dolphin)
- Swing Applications
- The Main Parts of a Swing Application
- HOWTOs
- Downloading and Installing Java
- How to Write, Compile and Run Java Programs
- How to Write, Compile and Run an Application
- How to Write, Compile and Run an Applet
- How to Write, Compile and Run a Swing Application
- How to Write, Compile and Run a Swing Applet
- How to Write, Compile and Run a GCJ Application
- Types
- Performance
- Swing
- How to Use java.io.StreamTokenizer
- How to Copy Arrays Fast
- Source Code
- Applications
- The HelloWorld Application
- 99 Bottles of Beer on the Wall
- Binomial Coefficient
- How to Read a String from the Keyboard
- Temperature Conversion
- Computing Pi using BigDecimal
- Swing
- Design Patterns
- History
- Grammars
- The BCPL Grammar
- The Java Language Specification, First Edition
- The Java Language Specification, Second Edition
- The Java Language Specification, Third Edition
- References
- Java Tutorials on the Web
- Lykkenborg BSD License for Java Source Code
- Tutorial Standards and Conventions
Monday, October 22, 2007
How to Write, Compile and Run a GCJ Application
How to Write GCJ Application
Writing an GCJ application is similar to writing any application.
How to compile a GCJ Application
This is how to compile and link with gcj in one step (Gao 2003):
[user]$ gcj --main=HelloWorld -o HelloWorld HelloWorld.java
How to run a GCJ Application
This is how to run a GCJ Application:
[user]$ ./HelloWorld Hello World!
References
- Gao, Weiqi. (2003). GCJ---The GNU Compiler for Java St. Louis, MO: Object Computing, Inc. Retrieved Monday, April 11, 2005 from http://www.ociweb.com/jnb/jnbJan2003.html.
- GCJ: The GNU Compiler for Java
- Compiling Java with GCJ
Friday, September 14, 2007
Computing Factorial using BigDecimal
This demonstration program computes the factorial using BigDecimal. However, there exists more efficient algorithms, see http://www.luschny.de/math/factorial/FastFactorialFunctions.htm
import java.math.BigInteger; public class FactorialTest { public static void main(String[] args) { long l = 10000; BigInteger bi = factorial(l); System.out.println(bi); System.out.println(bi.toString().length()); } /* ordinary factorial code */ public static long factorial(int n) { long f = 1; while (n > 1) { f *= n--; } return f; } /* BigInteger factorial code */ public static BigInteger factorial(long n) { BigInteger f = BigInteger.ONE; // long f = 1; BigInteger g = BigInteger.valueOf(n); // int n while (g.compareTo(BigInteger.ONE) == 1) { // while (n > 1) { f = f.multiply(g); // f *= n; g = g.subtract(BigInteger.ONE); // n--; } return f; } }
Tuesday, May 22, 2007
Star Trek
Introduction
Star Trek is a classic computer game written by Mike Mayfield, 20 October 1972. The game is based on the Star Trek television show. This program is a direct port to Java from the original BASIC program, and does not use object-oriented programming (OOP).
* * * Star Trek * * *
Do you want instructions (they're long!): no
You must destroy 13 Klingons in 30 stardates with 2 starbases.
Combat Area Condition Red
Shields dangerously low
Short Range Sensor Scan
1 2 3 4 5 6 7 8
---------------------------------
1 *
2 Stardate: 2486
3 * * Condition: Red
4 +++ * * Quadrant: 2, 6
5 <*> Sector: 5, 2
6 Energy: 3000.0
7 * Photon Torpedoes: 10
8 Shields: 0.0
---------------------------------
Command:
Download the Star Trek Java port
How to compile the Star Trek Java port
Write the following in a Linux terminal window or MS-DOS window:
javac StarTrek.java
How to run the Star Trek Java port
Write the following in a Linux terminal window or MS-DOS window:
java StarTrek
References
The original Star Trek BASIC program can be found here:
Resources
Star Trek Instructions
The Galaxy
The galaxy is divided into an [8, 8] quadrant grid which is in turn divided into an [8, 8] sector grid. The cast of characters is as follows:
<*> = Enterprise +++ = Klingon >!< = Starbase * = Star
Commands
Command 0 = Warp Engine Control (WEC)
4 3 2
\ ^ /
\^/
5 ----- 1
/^\
/ ^ \
6 7 8
Course
Course is in a Circular Numerical Vector Arrangement (CNVA) as shown. Integer and real values may be used. Therefore course 1.5 is half way between 1 and 2. A vector of 9 is undefined, but values may approach 9. One Warp Factor (WF) is the size of one quadrant. Therefore to get from quadrant [6, 5] to [5, 5] you would use course 3, warp factor 1.
Command 1 = Short Range Sensor Scan (SRSS)
Prints the quadrant you are currently in, including stars, Klingons, starbases, and the Enterprise; along with other pertinate information.
Command 2 = Long Range Sensor Scan (LRSS)
Shows conditions in space for one quadrant on each side of the Enterprise in the middle of the scan. The scan is coded in the form XXX, where the units digit is the number of stars, the tens digit is the number of starbases and the hundreds digit is the number of Klingons.
Command 3 = Phaser Control (PC)
Allows you to destroy the Klingons by hitting him with suitably large numbers of energy units to deplete his shield power. Keep in mind that when you shoot at him, he gonna shoot at you too.
Command 4 = Photon Torpedo Control (PTC)
Course is the same as used in Warp Engine Control (WEC). If you hit the Klingon, he is destroyed and cannot fire back at you. If you miss, he will fire phasers at you.
Note: The Library Computer (command 7) has an option to compute torpedo trajectory for you (option 2).
Command 5 = Shield Control (SC)
Defines number of energy units to be assigned to shields energy is taken from total ship's energy.
Note: Total energy includes shield energy.
Command 6 = Damage Control Report (DCR)
Gives state of repairs of all devices. A state of repair less than zero shows that the device is temporarily damaged.
Command 7 = Library Computer (LC)
The Library Computer contains three options:
Option 0 = Cumulative Galactic Record (CGR)
Shows computer memory of the results of all previous Long Range Sensor Scans.
Option 1 = Status Report (SR)
Shows number of Klingons, stardates and starbases left.
Option 2 = Photon Torpedo Data (PTD)
Gives trajectory and distance between the Enterprise and all Klingons in your quadrant.
Tuesday, April 24, 2007
Expressions
A running program should be able to do calculations, much like a calculator. For example:
public class Main { public static void main(String[] args) { System.out.println(2 + 2 + 2); } }
A calculation that produces a value, such as 6 * 9, is called an expression.
Monday, April 23, 2007
Fibonacci Numbers
import java.math.BigInteger; public class Main { public static void main(String[] args) { int n = Integer.parseInt(args[0]); System.out.println("iterativeFib: " + iterativeFib(n)); System.out.println("recursiveFib: " + recursiveFib(n)); System.out.println("iterativeBigFib: " + iterativeBigFib(n)); System.out.println("recursiveBigFib: " + recursiveBigFib(n)); System.out.println("memoizedBigFib: " + memoizedBigFib(null, n)); System.out.println("dynamicBigFib: " + dynamicBigFib(n)); } // Iterative Programming public static long iterativeFib(final int n) { long prev1 = 1, prev2 = 1, current = 1; for (int i = 3; i <= n; i++) { current += prev2; prev2 = prev1; prev1 = current; } return current; } // Recursive Programming public static long recursiveFib(final int n) { if (n <= 2) { return 1; } else { return recursiveFib(n - 1) + recursiveFib(n - 2); } } // Arbitrary-Precision Math // Iterative Programming public static BigInteger iterativeBigFib(final int n) { BigInteger prev1 = BigInteger.ONE, prev2 = BigInteger.ONE, current = BigInteger.ONE; for (int i = 3; i <= n; i++) { current = current.add(prev2); prev2 = prev1; prev1 = current; } return current; } // Recursive Programming public static BigInteger recursiveBigFib(final int n) { if (n <= 2) { return BigInteger.ONE; } else { return recursiveBigFib(n - 1).add(recursiveBigFib(n - 2)); } } // Memoization public static BigInteger memoizedBigFib(BigInteger[] fibarray, final int n) { if (fibarray == null) fibarray = new BigInteger[n + 1]; if (n <= 2) { return BigInteger.ONE; } else { return fibarray[n] == null ? fibarray[n] = memoizedBigFib(fibarray, n - 1).add(memoizedBigFib(fibarray, n - 2)) : fibarray[n]; } } // Dynamic Programming public static BigInteger dynamicBigFib(final int n) { BigInteger[] fibarray = new BigInteger[n + 1]; if (n <= 2) { return BigInteger.ONE; } else { fibarray[1] = BigInteger.ONE; fibarray[2] = BigInteger.ONE; for (int i = 3; i <= n; i++) { fibarray[i] = fibarray[i - 1].add(fibarray[i - 2]); } return fibarray[n]; } } }
[user]$ javac Fib.java [user]$ java Fib 45 iterativeFib: 1134903170 recursiveFib: 1134903170 iterativeBigFib: 1134903170 recursiveBigFib: 1134903170 memoizedBigFib: 1134903170 dynamicBigFib: 1134903170
The first run went OK, but the recursive methods took a long time to finish.
[user]$ javac Fib.java [user]$ java Fib 95 iterativeFib: -4953053512429003327 recursiveFib: -4953053512429003327 iterativeBigFib: 31940434634990099905 recursiveBigFib: 31940434634990099905 memoizedBigFib: 31940434634990099905 dynamicBigFib: 31940434634990099905
The recursive methods are very slow. I didn't have the time to wait — so I fudged the answers... Also, the two first answers are clearly wrong, because the largest value a long variable can hold is 9223372036854775807.
Friday, April 20, 2007
Power of 2
Program
public class Main { public static void main(String[] args) { for (int i = 0; i <= 62; i++) { System.out.println(i + ": " + (long) Math.pow(2, i)); } } }
Output
0: 1 1: 2 2: 4 3: 8 4: 16 5: 32 6: 64 7: 128 8: 256 9: 512 10: 1024 11: 2048 12: 4096 13: 8192 14: 16384 15: 32768 16: 65536 17: 131072 18: 262144 19: 524288 20: 1048576 21: 2097152 22: 4194304 23: 8388608 24: 16777216 25: 33554432 26: 67108864 27: 134217728 28: 268435456 29: 536870912 30: 1073741824 31: 2147483648 32: 4294967296 33: 8589934592 34: 17179869184 35: 34359738368 36: 68719476736 37: 137438953472 38: 274877906944 39: 549755813888 40: 1099511627776 41: 2199023255552 42: 4398046511104 43: 8796093022208 44: 17592186044416 45: 35184372088832 46: 70368744177664 47: 140737488355328 48: 281474976710656 49: 562949953421312 50: 1125899906842624 51: 2251799813685248 52: 4503599627370496 53: 9007199254740992 54: 18014398509481984 55: 36028797018963968 56: 72057594037927936 57: 144115188075855872 58: 288230376151711744 59: 576460752303423488 60: 1152921504606846976 61: 2305843009213693952 62: 4611686018427387904