Java Tips
I'm not a frequent Java programmer, so things presented here may not be 100% correct.
Getting started
Hello, World
- Install Java
- Write some Java code, say Hello.java
- Compile
Hello.java
to Hello.class
, by running command line:
javac Hello.java
- Write a HTML web page
Hello.html
that uses the applet Hello.class
.
At minimum, put one line
<applet code="Hello.class"></applet>
in the web page.
More about HTML.
- Open
Hello.html
with your web browser to view the applet.
Please be aware of a cache problem if you modified the applet.
- Alternatively you can type
appletviewer Hello.html
Note, the argument is the HTML file instead of the applet itself.
Simple 2D graphics
Pitfalls
Several weird rules:
- One public class in a file,
File name = class name + ".java", i.e.,
Hello.java
in the above case.
- When running a java program:
java Hello
is good;
java Hello.class
is bad.
- A cache problem: applets do not appear to be updated in
Firefox after you change the code. This is because Java caches .class files,
and is not clever enough to update them timingly.
Solution:
- Open Java console: in my system Ubuntu Linux, it's in
System → Preference → Sun Java 6 Plugin Control Panel.
- In Advanced tab, expand Java console, choose Show console
- Restart Firefox, now every time you open a web page an applet,
a Java console window pops up,
press the letter x on your keyboard while in that windows to clear the cache.
- Now changes should appear properly, after pressing F5 in Firefox.
- Note, you still need to compile .java files to .class files.
Code snippets
- To use math functions
import static java.lang.Math.*;
, then use sin(x)
;
Note, without static
, you'll have to write Math.sin(x)
.
- To convert string to integer:
Integer.parseInt(s)
(equivalent to C's atoi(s)
, or Python's int(s)
);
to Double
: Double.parseDouble(s)
.
- To format a real number to three decimal places
import java.text.*;
and
NumberFormat df = new DecimalFormat("#0.00");
then
String s = df.format(x);
(equivalent to C's sprintf(s, "%.2f", x);
,
or Python's s = "%.2f" % x
)
- To allocate an array, e.g.
int arr[] = new int[cnt];
allocates an integer array of cnt
elements.
For a two dimensional array: int arr[][] = new int[3][4];
Pros and Cons
Pros:
- Grammar similar to C/C++, translation to/from Java is easy.
- Built-in graphics, convenient for web demonstrations.
- No memory allocation, pointers.
- Largest community, according to Tiobe.
Cons:
- Verbose: method names are long, too much typing is distracting.
- Everything needs to be looked up, or you have to rely on a bulky IDE.
Internet resources
Tutorials