1.
public static String removeBlankAndDot(String target) {
if (target != null) {
StringBuffer buf = new StringBuffer();
for (int ii=0;ii<target.length();ii++) {
char c = target.charAt(ii);
if (c != ' ' && c != '.') buf.append(c);
}
return buf.toString();
}
return null;
}
2.
public class DataLogger {
private static PrintStream err = System.err;
private static String filePath = "log";
private static String fileName = "my.data";
private static PrintWriter log;
public static void logData(String logInfo) {
try {
if (log == null) {
File file = new File(filePath + System.getProperty("file.separator") + fileName);
log = new PrintWriter(new FileOutputStream(file));
}
if (!logInfo.equals("")) {
log.println(logInfo);
log.flush();
}
}
catch (Exception e) {
e.printStackTrace(err);
System.exit(1);
}
}
3.
public class Hello {
public static void main(String[] args) {
String name = "John";
char[] numbers = { '1', '0' };
System.out.println(name + " is the number " + numbers);
}
}
4.
public class Hello {
public static void main(String[] args) {
Date d1 = new Date("1 Apr 98");
nextDateUpdate(d1);
System.out.println("NextDay: " + d1);
}
private static void nextDateUpdate(Date arg) {
arg = new Date(arg.getYear(), arg.getMonth(), arg.getDate() + 1);
}
}
5.
// double values[100] initialized here
double getValueForPeriod(int periodNumber) {
try {
return values[periodNumber];
} catch (ArrayIndexOutOfBoundException e) {
return 0.0;
}
}
6.
static void copy(String src, String dest) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
} finally {
if (in != null) in.close();
if (out != null) out.close();
}
}
7.
public class Timer {
public static final Timer INSTANCE = new Timer();
private final int diffTime;
private static final int CURRENT_YEAR =
Calendar.getInstance().get(Calendar.YEAR);
private Timer() {
diffTime = CURRENT_YEAR - 1949;
}
public int diffTime() {
return diffTime;
}
public static void main(String[] args) {
System.out.println("diff Time is " + INSTANCE.diffTime());
}
}
8.
public String getStrTrim () {
String string = new String(" 14 units ");
string.trim();
return string;
}
9.
public class PingPong {
public static synchronized void main(String[] a) {
Thread t = new Thread() {
public void run() { pong(); }
};
t.run();
System.out.print("Ping");
}
static synchronized void pong() {
System.out.print("Pong");
}
}
10.
public class Stack {
private Object[] elements;
private int size = 0;
public Stack(int initialCapacity) {
this.elements = new Object[initialCapacity];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0) throw new EmptyStackException();
return elements[--size];
}
}
11.
public boolean isYourTime(Date d) {
Date d1 = new Date("1 Apr 98");
Date d2 = new Date("1 Apr 99");
return d.compareTo(d1) >= 0 &&
d.compareTo(d2) < 0;
}
12.
public final class Period {
private final Date start;
private final Date end;
public Period(Date start, Date end) {
this.start = start;
this.end = end;
// verify start >= end
}
public Date getStart() {
return start;
}
}
13.
publish Hashtable test(Hashtable ht) {
// ...
Hashtable newHt = new Hashtable();
// ...
return newHt;
}
14.
public abstract class A {
public abstract void process();
}
public class DB extends A {
public void process() {
// retrieve data from database
}
}
public class SAX extends A {
public void process() {
// processing the data from SAXparser
}
}
15.
private List cheesesInStock = ...
public Cheese[] getCheeses() {
if (cheesesInStock.size() == 0) {
return null;
}
}
16.
public abstract class WorkQueue {
private final List queue = new LinkedList();
protected WorkQueue() { new WorkerThread().start(); }
public final void enqueue(Object workItem) {
synchronized(queue) {
queue.add(workItem);
queue.notify();
}
}
protected abstract void processItem(Object workItem)
throws InterruptedException;
private class WorkerThread extends Thread {
public void run() {
while (true) {
synchronized(queue) {
// ...
Object workItem = queue.remove(0);
try {
processItem(workItem);
} catch (InterruptedException e) {
return;
}
}
}
}
}
}
class UseQueue extends WorkQueue {
protected void processItem(Object workItem)
throws InterruptedException {
Thread child = new Thread() {
public void run() { enqueue(workItem); }
};
child.start();
child.join();
}
}
17.
public abstract class Asset {
abstract protected powerDown();
// ...
}
public class ComputerAsset extends Asset {
// ...
protected void powerDown() {
}
}
public class ComputerServer extends ComputerAsset {
// ...
public powerDown() {
// empty
}
}
public class BuildingAsset extends Asset {
// ...
protected void powerDown() {
}
}
public class BuildingLight extends BuildingAsset {
// ...
protected void powerDown() {
}
}
public class EmergencyLight extends BuildingLight {
// ...
public powerDown() {
// empty
}
}
public class ComputerMonitor extends ComputerAsset {
// ...
public powerDown() {
// need do something
}
}
public class RoomLights extends BuildingLight {
// ...
public powerDown() {
// need do something
}
}
public class BuildingManagement {
Asset things[] = new Asset[24];
int numItems = 0;
public void goodNight() {
for (int i = 0; i < things.length; i++) {
things[i].powerDown();
}
}
public void add(Asset thing) {
// ...
}
}
public static void main(String[] args) {
BuildingManagement b1 = new BuildingManagement();
b1.add(new RoomLights(101));
b1.add(new EmergencyLight(100));
// ...
b1.add(new ComputerMonitor(200));
b1.goodNight();
}
18.
public int loadData(Connection conn, String sql) throws SQLException {
// ...
ResultSet rs = null;
Object[] record = null;
this.data = new ArrayList();
try {
// ...
while (rs.next()) {
record = new Object[columnCount];
for (int i = 0; i < columnCount; i++) {
record[i] = rs.getObject(i);
}
data.add(record);
}
} finally {
// ...
}
}
19.
public void printMetaData(Connection conn) {
// ...
DatabaseMetaData dmd = conn.getMetaData();
ResultSet rs = dmd.getTable(null,null,null,tabletypes);
while (rs.next()) {
// ...
String table = rs.getString("TABLE_NAME");
ResultSet rs2 = dmd.getColumns(null,null,table,null);
while (rs2.next()) {
// ...
}
rs2.close();
}
rs.close();
}
20.
public void add1000(Vector v, String s) {
for (int i = 0; i < 1000; i++) {
v.add(s);
}
}
21.
public void test() {
// ...
Hashtable ht = new Hashtable();
...
if (!ht.containsKey(key)) {
return ht.get(key);
}
if (!ht.containsKey(key)) {
ht.put(key, value);
}
}
22.
String s = "info";
String p = null;
public void func() {
Vector v = new Vector();
v.addElement(s);
// ...
p = (String) v.elementAt(0);
Vector v1 = new Vector();
// do other thing
}
23.
BufferedWriter fw =
new BufferedWriter(
new FileWriter("stock.dat"));
String s = buy.toString();
fw.write(s, ...);
24.
public void callManyTimes() {
for (Iterator i = myList.iterator(); i.hasNext();)
{
Node node = (Node) i.next();
// ...
}
25.
Map first = new ...
Map second = new ...
boolean isSubmap = true;
for (Iterator i = sencond.keySet().iterator(); i.hasNext();) {
Object key = i.next();
Object valueInFirst = first.get(key);
Object valueInSecond = second.get(key);
if (valueInSecond == null) {
if (valueInFirst != null) {
// ...
}
} else if (!valueInSecond.equals(valueInFirst)) {
// ...
}
}
26.
public class test {
public static void main(String[] args) {
// ...
try{
Connection con = DriveManager. ...
new TablePrinter(con, "Names").walk();
} catch (SQLException e) {
// ...
}
}
}
abstract class TableWalker {
Connection con;
String tableName;
public TableWalker(Connection c, String tablename) {
this.con = c;
// ...
}
public void walk() throw SQLException {
// ...
ResultSet rs = stm.executeQuery(queryString);
while(rs.next()) {
execute(rs);
}
con.close(); // this is wrong place to stay
}
public abstract void execute(ResultSet rs) throws SQLException;
}
public class TablePrinter extends TableWalker {
public TablePrinter(Connection c, String tablename) {
super(c, tablename);
}
public void execute(ResultSet rs) throws SQLException {
// ...
}
}
27.
public class Work {
private Hashtable ht = new Hashtable();
// ...
public final void enHt(Object key, Object value) {
synchronized(ht) {
ht.put(key, value);
}
}
}
28.
public class A {
private static String fileName = "myfile.txt";
...
public FileOutputStream writer = new FileOutputStream(fileName);
public void write(int b) throws IOException {
writer.write((byte)b);
}
...
}
29.
public ManyMethodsCallThisFun () {
...
for (int i = 0; i < size; i++) {
Map<String, Record> map =
Collections.synchronizedMap(
new HashMap<String, Record>(states[i]);
db.add(states[i], map);
}
...
}
30.
public class A {
public static void main (String[] args) {
C c = new C();
c = null;
System.gc();
}
class C implements aListener {
private D d = null;
public C() {
d = D.getInstance();
d.addaListener(this);
}
...
}
class D { // D is Singleton
...
public void removeaListener(aListener a) {
...
}
}
}
31.
String x = "Hello ";
x += name;
32.
private Node getNode(String key, Map map) {
Nodekey nodekey = new Nodekey(key);
Node n = (Node) map.get(nodekey);
...
return n
}
33.
public class A {
private String name = "foo";
...
public A() {
setName("foo");
...
}
public void setName(String s) {
this.name = s;
}
...
}
34.
public void readName() throws IOException {
name = in.read();
}
35.
interface Info {
int PINK = 1;
int BLUE = 2;
...
}
public class Graph implements Info {
...
switch (color) {
case PINK:
...
}
}
36.
public void func(String str) {
Runnable r = new Runnable() {
public void run() {
System.out.println(str);
}
};
Thread t = new Thread(r);
t.start();
}
37.
public class FileCopier {
public FileCopier(String source, String dest) throws FileCopierEx {
// catch IOException and throw FileCopierEx
}
}
try {
FileCopier fc = new filecopier(s, d);
} catch (FilecopierEx fce) {
...
}
fc.docopy();
38.
BufferedOutputStream fos =
new BufferedOutputStream(
new FileOutputStream("stock.dat"));
fos.write(buy.toBytes());
fos.flush();
fos.write(sell.toBytes());
fos.flush();
39.
if (s.startWith("a")) {...}
if (s.startWith("cd")) {...}
40.
try {
...
System.out.write(somethings);
} catch (IOException e) {...}
41.
public class A {
public static void main(String[] args) {
...
StringBuffer word = null;
switch(item) {
case 1:
word = new StringBuffer('M');
break;
...
}
word.append('e');
...
}
}
42. EJB2 JNDI
Object obj = context.lookup("java:comp/env/AccountHome");
43. EJB2
public class Mysession implements SessionBean {
SessionContext ctx;
...
public Myfuc() throws mysessionException {
try {
withdraw(...);
deposit(...);
} catch (mysessionException e) {
throw e;
}
}
...
}