Sunday, August 07, 2005

Java Puzzle

อ่านเจอในเอกสาร presentation ใน javaone 2005
ก็เลยลอกมาให้ดู
public class AnimalFarm{ 
public static void main(String[] args) {
final String pig = "length: 10";
final String dog = "length: " + pig.length();
System.out.println("Animalsare equal: " + pig == dog);
}
}


public class Assignment { 
public static void main(String[] a) throws Exception {
int tricky = 0;
for (int i = 0; i < 3; i++)
tricky += tricky++;
System.out.println(tricky);
}
}


public class Loop {
public static void main(String[] args) {
int[][] tests = { { 6, 5, 4, 3, 2, 1 }, { 1, 2 }, { 1, 2, 3 },
{ 1, 2, 3, 4 }, { 1 } };
int successCount = 0;
try {
int i = 0;
while (true) {
if (thirdElementIsThree(tests[i++]))
successCount++;
}
} catch (ArrayIndexOutOfBoundsException e) {
}
System.out.println(successCount);
}

private static boolean thirdElementIsThree(int[] a) {
return a.length >= 3 & a[2] == 3;
}
}


public class Mod {
public static void main(String[] args) {
final int MODULUS = 3;
int[] histogram = new int[MODULUS];
int i = Integer.MIN_VALUE;
// This loop iterates over all intvalues
do {
histogram[Math.abs(i) % MODULUS]++;
} while (i++ != Integer.MAX_VALUE);
for (int j = 0; j < MODULUS; j++)
System.out.print(histogram[j] + " ");
}
}


อันสุดท้ายนี่งงอยู่ตั้งนาน สุดท้ายเปิด javadoc ดูแล้วค่อยร้อง อ๋อ

Related link from Roti

No comments: