
/* filename: Hello.java
A Simple application program which displays "Hello, world!" to the terminal.
*/
public class Hello
{
public static void main(String[ ] args)
{
System.out.println("Hello, world!"); // message string in ".." in one line
}
}
java.lang
String and Math classes are
in java.langimport java.util.Scanner; //
public class Greetings
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); // sc is a Scanner object/variable,
// connected to keyboard (System.in)
// Prompt the user by print (not println) -- print does not change line (CR/LF).
System.out.print("What is your name? ");
String s = sc.next(); // read in a string from sc (until a white-space)
// Display a personalized greeting message.
System.out.println("Hi, " + s); // + concatenates two strings
}
}
| Data Type | Storage | Min value | Max value | ||
| Numbers | Integral | byte | 1 byte (= 8 bits) | -128 | 127 |
| short | 2 bytes (= 16 bits) | -32,768 | 32,767 | ||
| int | 4 bytes (= 32 bits) | -2,147,483,648 | 2,147,483,647 | ||
| long | 8 bytes (= 64 bits) | < -9 * 1018 | > 9 * 1018 | ||
| Floating- point |
float | 4 bytes (= 32 bits) | < -3.4 * 1038 with 7 significant digits |
> 3.4 * 1038 with 7 significant digits |
|
| double | 8 bytes (= 64 bits) | < -1.7 * 10308 with 15 significant digits |
> 1.7 * 10308 with 15 significant digits |
||
| Characters | char | 2 bytes (= 16 bits) | 'A', 'a', '@', '2', ' ', '\n' etc. Unicode character set | ||
| Boolean | boolean | 1 bit | true, false | ||
int a = 5; // no problem
double b = 3.9; // no problem
double d = 6; // 6.0 -- type promotion (6 (int) is promoted to double)
//int x = 8.57; // ERROR!! Java allows widening type promotion only
int x = (int) 8.57; // 8 -- truncation (where decimal digits are lost)
int y = 2147483647 * 3; // 2147483645 -- overflow
char ch1 = 67; // 'C' (in ascii)
char ch2 = 367; // '?' ('??" is ascii 63) -- overflow
int z = 'F'; // 70 ('F' is ascii 70) -- 0's are padded at significant bits
int x; // variable declaration (but uninitialized) int y = 9; // variable declaration and initialization at the same time final int Z = 4; // constant (indicated by final) must be declared with a value
e.g.
import java.util.Scanner;
public class AddIntAndDouble
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter an int and a double separated by a space: ");
int n;
double d, sum;
n = sc.nextInt(); // read an int
d = sc.nextDouble(); // read a double
sum = n + d;
System.out.println(); // a blank line
System.out.println("The sum of " + n + " and " + d
+ " is " + sum);
}
}
Sample output
Enter an int and a double separated by a space: 4 3.81 The sum of 4 and 3.81 is 7.81
Examples:
int x = 3; int y = x++; // returns 3 (so y is 3), and x becomes 4
int x = 3; int y = ++x; // x becomes 4, and 4 is returned (so y is 4)
int x = 4, y = 1; y += x; // same as y = y + x;
(unary) +, (unary)- |
Highest precedence |
*, /, % |
Higher precedence |
+, - |
Lower precedence |
int x = 3 + 4 * 5; // int y = (3 + 4) * 5; //
import java.util.*;
public class ChangeMaker
{
public static void main(String[] args)
{
final int QUARTER = 25;
final int DIME = 10;
final int NICKEL = 5;
int amount, originalAmount, quarters, dimes, nickels, pennies;
System.out.print("Enter the amount of change to make: ");
Scanner sc = new Scanner(System.in);
amount = sc.nextInt( ); // read the amount as an int
originalAmount = amount; // save the amount in a different variable
quarters = amount / QUARTER; // # of quarters
amount = amount % QUARTER; // update the amount
dimes = amount / DIME; // # of dimes
amount = amount % DIME;
nickels = amount / NICKEL; // # of nickels
amount = amount % NICKEL;
pennies = amount; // remaining become pennies
System.out.println(originalAmount
+ " cents in coins can be given as:");
System.out.println(quarters + " quarters");
System.out.println(dimes + " dimes");
System.out.println(nickels + " nickels and");
System.out.println(pennies + " pennies");
}
}
java.lang.String ClassString s = "CSC 300"; // or new String("...");
int len = s.length(); // length of the string
char ch = s.charAt(2); // char at index 2 (i.e., the 3rd char)
String s2 = s + " Java"; // string concatenation using +
String s3 = s.toLowerCase(); // returns a string in all lower-case chars; "csc 300"
String s4 = s.substring(0, 2); // returns a substring from index 0 (inclusive) to 2 (exclusive);
// here "CSC"
boolean ans;
ans = s.equals("CSC300"); // see if two strings are the same; here false
ans = s.equalsIgnoreCase("csc 300"); // regardless of upper/lower cases; here true
< less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to
&& AND || OR ! NOT
int x = 3;
// If case only. Also one statement in the body, so no { .. }
if (x >= 0)
System.out.println("yes");
// If case only. Multiple statements in the body, so need { .. }
if (x < 0)
{
System.out.println("Negative number. Changing the sign..");
x = -x;
}
// If-else statement
if (x < 0)
x = -x;
else if (x < 2)
x++;
else
{
System.out.println("x is greater than 2. Adding 5..");
x += 5;
}
// Complex tests
int y = 5;
if (x >= 0 && x < y)
...
if (x < 0 || x >= y) // Note: deMorgan's law
...
boolean result = (x == y); // equality test by == (not =) for primitive data types
if (result != true)
system.out.println("x and y are not equal");
// The if-test above is equivalently written as:
// if (result == false) -- which is the same as
// if (!result) -- if the negation of result is true..
char grade = 'B'; switch (grade)
{
case 'A':
System.out.println("good");
break; // break out of this case
case 'B':
System.out.println("ok");
break; // break out of this case
default:
System.out.println("fail");
}
|
String s = "It was "; int code = 3; switch (code)
{
case 1:
s = s + "one";
break;
case 2:
s = s + "two";
break;
case 3:
s = s + "three";
break;
default:
s = s + "something else";
} |
switch (grade)
{
case 'A':
case 'a':
System.out.println("good"); // prints for 'A' or 'a'
break;
case 'B':
case 'b':
System.out.println("ok"); // prints for 'B' or 'b'
break;
default:
System.out.println("fail");
}
int count = 0;
while (count < 5) // 5 here is a sentinel value
{
System.out.println(count);
count++;
}
Similar to while-statement, but quite different in syntax.
for (int count = 0; count < 5; count++) // initialization; testing; update
{
System.out.println(count);
}
Similar to while-statement, except the testing condition is at the end of a loop.
int count = 1;
do
{
System.out.println(count);
count++;
} while (count <= 5); // need ; at the end
Another typical application is when you want to ask the user if he/she wants to continue.
Scanner sc = new Scanner(System.in);
String ans;
do {
...
System.out.print("Do you want to continue (y/n)? ");
ans = sc.next();
} while (ans.equals("y"));
Example: ExamAverager
import java.util.*;
/**
Determines the average of a list of (nonnegative) exam scores.
Repeats for more exams until the user says she/he is finished,
which is indicated by entering a negative number.
*/
public class ExamAverager
{
public static void main(String[] args)
{
System.out.println("This program computes the average of");
System.out.println("a list of (nonnegative) exam scores.");
double sum;
int numberOfStudents;
double next;
String answer;
Scanner keyboard = new Scanner(System.in);
do
{
System.out.println( );
System.out.println("Enter all the scores to be averaged.");
System.out.println("Enter a negative number after");
System.out.println("you have entered all the scores.");
sum = 0;
numberOfStudents = 0;
next = keyboard.nextDouble( );
while (next >= 0)
{
sum = sum + next;
numberOfStudents++;
next = keyboard.nextDouble( );
}
if (numberOfStudents > 0)
System.out.println("The average is "
+ (sum/numberOfStudents));
else
System.out.println("No scores to average.");
System.out.println("Want to average another exam?");
System.out.println("Enter yes or no.");
answer = keyboard.next( );
}while (answer.equalsIgnoreCase("yes"));
}
}
// Example below repeatedly accepts a non-negative integer from the user.
// When a negative integer is entered, the boolean variable is set to false
// and the loop terminates.
int userVal;
boolean flag = true; // initial value(true) needed to get into the loop
// for the first time.
while (flag) // same as (flag == true)
{
userVal = sc.nextInt(); // assume sc is connected to keyboard
if (userVal < 0) // if user enters a negative
flag = false; // set the flag to false
}
Or another way:
boolean done = false; // initially false
while (!done) // same as (!done == true)
{
userVal = sc.nextInt();
if (userVal < 0)
flag = true;
}
returnType methodname(parameters);
e.g. The method pow (for power) in class Math
To use this method, you call the method with with the class name, followed by . and the method name, and appropriate parameters in parentheses. And you receive the returned value in a variable.
double d1 = 1.5, d2 = 2.0;
double result;
result = Math.pow(d1, d2); // call the method with parameters d1 & d2,
// received the returned value in result
double d1 = Math.pow(3.14, 2.0); // 3.14 to the power of 2 double d2 = Math.sqrt(2.0); // square root of 2.0 int num = Math.round(1.51); // returns an int, rounded; 2 in this case
char ch1 = 'F', ch2 = '5'; boolean result; result = Character.isUpperCase(ch1); // 'F' is upper-case, so returns true result = Character.isSpaceChar(ch1); // a space char is ' ', so returns false result = Character.isDigit(ch2); // '5' is a digit, so returns true char ch3; ch3 = Character.toLowerCase(ch1); // method returns 'f', received in ch3 ch3 = Character.toUpperCase(ch1); // ch1 is already upper-case; 'F' is returned (as is) ch3 = Character.toUpperCase(ch2); // '5' doesn't have equivalent upper-case; '5' is returned (as is)
public static <return-type> <name>(<parameter definitions>)
{
<body>
}
// filename: MyProg.java
import java.util.Scanner;
public class MyProg
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter two integers: ");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int max = largerInt(n1, n2); // calls the user-defined method
System.out.println(max + " is larger of the two.");
} // end main
// A user-defined method largerInt.
// This method takes two parameters, both are of type int.
// The method returns an int, which is the larger of the two parameters.
public static int largerInt(int x, int y)
{
int larger;
if (x > y)
larger = x;
else
larger = y;
return larger; // return statement at the end
}
}
public class MyProg2
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter two integers: ");
int n1 = sc.nextInt();
int n2 = sc.nextInt();
printTwoIntegers(n1, n2); // call the method, but not receive returned value
} // end main
// A void method printTwoIntegers.
public static void printTwoIntegers(int x, int y)
{
System.out.println(x + " " + y);
// no return statement in the body
}
} public class MyProg3
{
public static void main(String[] args)
{
for (int i = 0; i < 3; i++)
bark();
} // end main
public static void bark() // no parameters
{
System.out.println("woof!");
}
}import java.util.*;
public class Addition
{
public static void main(String [ ] args)
{
int x, y, sum;
Scanner input = new Scanner(System.in);
System.out.println("Enter 2 integers");
x = input.nextInt();
y = input.nextInt();
// method call
sum = add2Numbers(x,y);
System.out.println(x + " + " + y + " = " + sum); // x, y unchanged
}
public static int add2Numbers(int a, int b)
{
a = a + b; // a changed
return a;
}
}
a in add2Numbers does not
change x public class Wrong
{
public static void main(String[ ] args)
{
int x;
otherMethod( );
}
public static void otherMethod( )
{
System.out.println(x); // ERROR
}
}
public class AddDifferentTypes
{
public static void main(String[ ] args)
{
int x=1, y=3, z;
double a=2.5, b=3.2, c;
z = add(x,y);
c = add(a,b);
System.out.println(x + " + " + y + " = " + z);
System.out.println(a + " + " + b + " = " + c);
}
public static int add(int num1, int num2)
{
return num1 + num2;
}
public static double add(double num1, double num2)
{
return num1 + num2;
}
}
int[] iarray; // iarray declared -- an array of integers iarray = new int[10]; // iarray instantiated -- with an array of size 10 double[] darray; // darray declared -- an array of doubles darray = new double[3]; // darray instantiated -- with an array of size 3
int[] numbers = new int[5]; // create a new array of length 5
for (int i = 0; i < 5; i++)
numbers[i] = 0; // each (ith) element receives a value 0
numbers[1] = 3; // assign 3 in the 2nd element (index 1)
Schematically,
0 1 2 3 4 <-- index
+---+---+---+---+---+
numbers | 0 | 3 | 0 | 0 | 0 |
+---+---+---+---+---+
int[] numbers = {0, 3, 0, 0, 0}; // NOTE: don't need size or new
Scanner scan = new Scanner(System.in);
System.out.print("Enter the length of the array: ");
int n = scan.nextInt();
int[] ar = new int[n]; // n contains the length specified by the user
// Suppose an array of ints of some length is created.
int[] numbers = new int[...];
// Assume some values are assigned in the array.
// Now traverse the array to print out each element to System.out.
for (int i = 0; i < numbers.length; i++)
System.out.println(numbers[i]);
int[] numbers = new int[5]; numbers[-1] = 3; // ILLEGAL!! Index out of bounds (negative index) numbers[0] = 3; // ok numbers[5] = 3; // ILLEGAL!! Index out of bounds (beyond the range)
double[] sales = new double[10];
int index;
double largestSale, sum, average;
// (1) Initialize an array with a specific value
for (index = 0; index < sales.length; index++)
sales[index] = 10.00;
// (2) Reading data into an array
for (index = 0; index < sales.length; index++)
sales[index] = console.nextDouble();
// (3) Printing an array
for (index = 0; index < sales.length; index++)
System.out.print(sales[index] + " ");
/*
* (4) Finding the sum and average of an array
*/
sum = 0;
for (index = 0; index < sales.length; index++)
sum = sum + sales[index];
if (sales.length != 0) // to avoid a divide-by-zero error
average = sum / sales.length;
else
average = 0.0;
/*
* (5) Determining the largest element in the array
*/
int maxIndex = 0; // index to the maximum element; initially set to 0
for (index = 1; index < sales.length; index++) { // index starts from 1 (not 0)
if (sales[maxIndex] < sales[index])
maxIndex = index;
}
// After the loop terminates, maxIndex has the index to the maximum element.
// Thus, the maximum VALUE is the element at that index.
largestSale = sales[maxIndex];
//Program to read five numbers, find their sum, and
//print the numbers in the reverse order.
import java.util.*;
public class ReversePrintII
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
int[] items = new int[5]; //declare an array item of
//five components
int sum;
int counter;
System.out.println("Enter five integers:");
sum = 0;
for (counter = 0; counter < items.length; counter++)
{
items[counter] = console.nextInt();
sum = sum + items[counter];
}
System.out.println("The sum of the numbers = " + sum);
System.out.print("The numbers in the reverse order are: ");
//print the numbers in the reverse order
for (counter = items.length - 1; counter >= 0;
counter--)
System.out.print(items[counter] + " ");
System.out.println();
}
}
public class ArrayMethods1
{
public static void main(String[] args)
{
int[] nums = {10, 20, 30, 40};
boolean result = isEven(nums[0]); // pass one element
int sum = sumArray(nums); // pass whole array, by its name
squareArray(nums);
// At this point, elements in the array are changed.
}
public static boolean isEven(int number)
{
if (number % 2 == 0)
return true;
else
return false;
}
public static int sumArray(int[] n) // this method doesn't modify array
{
int total = 0;
for (int i = 0; i < n.length; i++)
total += n[i];
return total;
}
public static void squareArray(int[] n) // this method modifies array
{
for (int i = 0; i < n.length; i++)
n[i] = Math.pow(n[i], 2.0); // ith element is assigned a new value
}
}
public static boolean isEqualArrays(int[] firstArray, int[] secondArray)
{
if (firstArray.length != secondArray.length)
return false;
for (int i = 0; i < firstArray.length; i++)
{
if (firstArray[i] != secondArray[i])
return false;
}
return true;
}
// Assume ar1 has elements in it, while ar2 is empty (but has the same length)
public static void copyArrayParameters(int[] ar1, int[] ar2)
{
// Copy each element, one by one.
for (int i = 0; i < ar1.length; i++)
ar2[i] = ar1[i];
}
public static int[] copyArrayByReturn(int[] orig)
{
int[] copy = new int[orig.length]; // a separate, empty array
for (int i = 0; i < orig.length; i++)
copy[i] = orig[i];
return copy;
}
public class PassExampleArgs
{
public static void main(String[ ] args)
{
int x, y;
x = Integer.parseInt(args[0]);
y = Integer.parseInt(args[1]);
System.out.println("Their sum is " + sum(x,y));
}
public static int sum(int a, int b)
{
a = a + b;
return a;
}
}
java PassExampleArgs 6 2
will print out "Their sum is 8"
// filename: Car.java
public class Car
{
/* fields (data members) -- they are most often private */
private String model;
private int odometer;
private double fuel;
/* methods */
public Car(String m, int od, double fl) // constructor
{ model = m; odometer = od; fuel = fl; }
public String getModel() { return model; }
public int getOdometer() { return odometer; }
public void setOdometer(int newod) { odometer = newod; }
public void addFuel(double morefl) { fuel += morefl; }
public void Drive(int miles) { ... }
}
int x;
Car c; // c is a reference (to an Car object)
c = new Car("Toyota Camry", 0, 2.0); // instantiation of a Car with particular
// values for the fields
Pictorially,
instantiated Car object
+------------------------+
| +--------------+ |
+---+ | model |"Toyota Camry"| |
c | o----->| +--------------+ |
+---+ | +---+ |
| odometer | 0 | |
| +---+ |
| +------+ |
| fuel | 2.0 | |
| +------+ |
+------------------------+
// filename: CarDemo.java -- a CLIENT program which uses Car objects
public class CarDemo
{
public static void main(String[] args)
{
// Create Car objects by 'new' operator, calling constructor
Car c1 = new Car("Toyota Camry", 0, 2.0);
Car c2 = new Car("Nissan Maxima", 25000, 5.4);
// Invoke a method inside an object -- by using . operator
c1.Drive(300); // drive c1
c2.Drive(25); // drive c2
// NOTE: Drive() is a void method (thus no value returned)
String mdl = c1.getModel(); // c1's model
int odm = c1.getOdometer(); // c1's odometer
System.out.println(mdl + " has " + odm + " miles");
// display c2's information
System.out.println(c2.getModel() + " has " +
c2.getOdometer() + " miles");
}
}// filename: Car.java
public class Car
{
/* fields */
private String model;
private int odometer;
private double fuel;
/* methods */
public Car() // default constructor
{
model = ""; odometer = 0; fuel = 0.0;
}
public Car(String m, int od, double fl) // another constructor, overloaded
{
model = m; odometer = od; fuel = fl;
}
public String getModel() { return model; }
public int getOdometer() { return odometer; }
public void setOdometer(int newod) { odometer = newod; }
public void addFuel(double morefl) { fuel += morefl; }
public void Drive(int miles) { ... }
public String toString()
{
String ret = ""; // start with an empty string
ret = ret + model + ", " + odometer + " miles"; // build the return string by concatenation
return ret; // return that string
}
}
// An example use of 'this'
public int getOdometer() { return this.odometer; }
To create an object or invoking a method inside an object, we must pass EXACTLY THE SAME number/order and type of parameters as specified in the method. Otherwise, syntax error.
// filename: CarDemo.java
public class CarDemo
{
public static void main(String[] args)
{
// Create Car objects by 'new' operator and calling constructor
Car c1 = new Car("Toyota Camry", 0, 2.0);
Car c2 = new Car("Nissan Maxima", 25000, 5.4);
// Drive c1 for 300 miles
c1.Drive(300);
System.out.println(c1.getModel() + " has " +
c1.getOdometer() + " miles");
// c2 remains the same
System.out.println(c2.getModel() + " has " + c2.getOdometer() + " miles");
}
}
int x = 3; // x is a primitive type (int) String s1 = "abc"; // s1 itself is a reference String s2 = "Hi"; // s2 itself is a reference

s2 = s1; // s2 points to the same address/object as s1; // s2's object becomes orphan -- later cleaned up (garbage collected)
Car cobj;
int count = 0;
while (count < 5) {
System.out.print("Enter the manufacturer's name:" );
String mname = sc.next();
cobj = new Car(mname, 0, 0); // a new object instantiated to the same reference
..
count++;
}
String s1; // s1 is initialized to null automatically.
// NOTE: No object (in heap) is instantiated
// (i.e., without '= ".."' or 'new String(..)')
System.out.println(s1); // ERROR!!
public class Car
{
/* data members */
private String model;
private double fuel;
private int odometer;
private final double mpg = 21.7; // this field is added
/* methods */
....
public void Drive(int miles)
{
if (hasEnoughFuel(miles)) // calls another method
{
odometer = odometer + miles;
fuel = fuel - (miles / mpg);
}
else
System.out.println("ERROR: not enough fuel");
}
private bool hasEnoughFuel(int miles) // note this method is private
{
// Determine how much fuel is needed to run 'miles' miles.
double needed = miles / mpg;
// If the car has more than needed, ok.
if (fuel >= needed)
return true;
else
return false;
}
}
public class Money
{
...
// Returns true if this money is strictly less than the parameter money.
public boolean isLessThan(Money m2)
{
if (this.dollar < m2.dollar)
return true;
else if (this.dollar > m2.dollar)
return false;
else // i.e., this.dollar == m2.dollar
return (this.cent < m2.cent); // < evaluates to true/false
}
}
Now, how would you call such method in the application (e.g. test driver code)??
public class MoneyDemo
{
public static void main(String[] args)
{
Money mm1 = new Money(15, 99);
Money mm2 = new Money(11, 17);
if (mm1.isLessThan(mm2)) // mm2 corresponds to 'm2' in class definition,
// mm1 corresponds to 'this' object in class definition
System.out.println(mm1 + " is smaller than " + mm2);
else if (mm2.isLessThan(mm1)) // mm1 corresponds to 'm2',
// mm2 corresponds to 'this' object
System.out.println(mm2 + " is smaller than " + mm1);
else
System.out.println("They are the same");
...
public class Money
{
...
// Adds this money and the parameter money, and returns the sum money.
public Money add(Money m2)
{
int totalCents = (this.dollar + m2.dollar) * 100 +
(this.cent + m2.cent);
Money sum = new Money(totalCents/100, totalCents%100);
return sum;
}
}
public class Money
{
...
public Money add(Money m2)
{
int totalCents = (this.dollar + m2.dollar) * 100 +
(this.cent + m2.cent);
Money sum = new Money(totalCents/100, totalCents%100);
return sum;
}
// Another add method, with one int (cents)
public Money add(int moreCents)
{
int totalCents = this.dollar * 100 + (this.cent + moreCents);
Money sum = new Money(totalCents/100, totalCents%100);
return sum;
}
}
public class SomeClass
{
private int a;
public void Fn1(int b)
{
int c;
c = a; // (1) legal or illegal?
c = b; // (2) legal or illegal?
c = d; // (3) legal or illegal?
}
public void Fn2(int d)
{
a = d; // (4) legal or illegal?
c = d; // (5) legal or illegal?
}
}
java.lang.Math Class/* filename: MathDemo.java
* Simple program which demonstrates some Math class variables/methods.
*/
public class MathDemo
{
public static void main(String[] args)
{
double radius = 2.5;
double area = Math.pow(radius, 2.0) * Math.PI; // pow(r,2) static method in Math
// PI is a static variable/constant
System.out.println("Area is " + area);
System.out.println(); // NOTE: a blank line
System.out.println("Square root of 2 is " + Math.sqrt(2)); // sqrt method
}
}
import javax.swing.*;
public class Ex2
{
public static void main(String[] args)
{
String s = JOptionPane.showInputDialog("Enter an int"); // e.g. "514"
// Convert a String to an int
int n = Integer.parseInt(s); // parseInt() is a static method in Integer
System.out.println("The largest int is "
+ Integer.MAX_VALUE); // a static constant MAX_VALUE in Integer
...
public class Ex3
{
public static void main(String[] args)
{
for (int i = 0; i < 5; i++)
doEcho(); // call another method
}
public static void doEcho() // must be a static method
{
System.out.println("Hello! ");
}
}
public class Car2
{
/* data members */
private String model; // instance variable
...
// NEW DATA MEMBERS
private int serial_no; // instance data
private static int object_counter = 0; // static variable,
// initialized ONLY ONCE when the class is first loaded
/* methods */
public Car2(String mdl, String clr, double fl)
{
model = mdl;
color = clr;
fuel = fl;
odometer = 0;
// Additional lines to increment object_counter and set serial_no.
object_counter++;
serial_no = object_counter;
}
public int getSerialNo()
{
return serial_no;
}
public static int getObjectCount() // static method
{
return object_count; // can only look at static member
}
...
}
// Test driver code
public class TestCar2
{
public static void main (String[] args)
{
Car2 ca = new Car2("Camero", "red", 30.0);
Car2 mu = new Car2("Mustang", "black", 31.0);
Car2 th = new Car2("Thunderbird", "blue", 28.0);
// Object count is a class data (static), so call within the class.
int oc = Car2.getObjectCounter();
System.out.println("The object counter is " + oc); // 3
// Look at serial number captured in each object.
// Serial number is an instance data, so call within an object
int ca_no = ca.getSerialNo();
int mu_no = mu.getSerialNo();
int th_no = th.getSerialNo();
System.out.println();
System.out.println(ca + ", serial number = " + ca_no); // 1
System.out.println(mu + ", serial number = " + mu_no); // 2
System.out.println(th + ", serial number = " + th_no); // 3
}
}
// Class Point -- represents a point in 2-D dimension
public class Point
{
private double x, y; // X,Y coordinate of a point
public Point(double xval, double yval) { x = xval; y = yval; }
public double getX() { return x; }
public double getY() { return y; }
public String toString()
{
String ret = "(" + x + ", " + y + ")";
return ret;
}
}
=======================================================================
// Class Line -- a Line is defined by two Point's
public class Line
{
// fields
private Point p1, p2;
// methods
public Line(Point po1, Point po2)
{
p1 = po1; p2 = po2;
}
public Point getP1() { return p1; }
public Point getP2() { return p2; }
public double distance()
{
// access into component objects through their public methods
double xdist = p1.getX() - p2.getX();
double ydist = p1.getY() - p2.getY();
return Math.sqrt(Math.pow(xdist, 2) + Math.pow(ydist, 2));
}
}
=======================================================================
// application class
public class LineTest
{
public static void main(String[] args)
{
Line ln = new Line(new Point(2.0, 0.8),
new Point(4.5, 1.5));
System.out.println("The distance between " + ln.getP1()
+ " and " + ln.getP2()
+ " is " + ln.distance());
}
}