Packages and Classes

A java program has user-defined classes whose objects interact with those from java class libraries. In Java, related classes are grouped into packages, many of which are provided with the compailer. You can put your own classes into a package-this facilitates their use in other programs.
The package java.lang, which contains many commonly used classes, is automatically provided to all java programs. To use any other package in a program, an important statement must be used. To import all of the classes in a package called packagename, use the form:
    import packagename.*;
To import a single class called ClassName from the package, use
    import packagename.ClassName;
Java has a hierarchy of packages and subpackages. Subpackages are selected using multiple dots:
    import packagename.subpackagename.ClassName;
The import statement allows the programmer to use the objects and methods defined in the designated package. By convention java package names are lower case.
A java program must have at least one class, the one that contains the main method. In general, the name of the file containing each public class must match the name of the class, with the suffix .java. These files, which consist of human-readable java statements, are called source files.
A compiler converts source code into machine-readable form called bytecode. All the bytecode is linked together by a linker, ans the program is then executed. Here is a typical source file for a java program:
/* Program FirstProg.java
Start with a comment, giving the program name and a brief
description of what the program does. */
import package1.*;
import package2.subpackage.ClassName;

public class FirstProg  {  //note that the file name is FirstProg.java
    public static type1 method1( parameter list)  {
       <code for method1>
    }
    public static type2 method2(parameter list)  {
       <code for method2>
    }
       . . .
    Public static void main( String[] args )  {
       <your code>
    }
}//end of class FristProg


NOTE
             1. all java methods must be contained in a class, and all program staements must be placed inside a method.
             2. typically, the class that contains the main methods does not contains many additional mathods.
             3. the words class, public, static, void , and main are reserved words, also called keywords.
            
4. the keyword public signal that the class or method is usable outside of the class, whereas private data members    or methods   are not.
             5. the key word static is used for methods that will not access any objects of a class, such as the mothods in the firstprog class, such as the methods in a source file that contains no insurance variables. most methods in java do operate on objects and are not statics. the main method, however, must always be static.
             6. the program shown on the previous page is a java application. this is not to confused with a java applet,a program that runs inside a web browser or applet viewer. applets are not part of the AP sybset.

types and identifiers

identifiers    an identifier is a name for a variable, parameter, constant, user-defined method, or user-defined class. in java  an identifier is any sequence of letters, digits, and the underscore characters. identifiers may not begin with a digit. identifiers are identifiers should be concise and self documenting. a variable called area is more illuminating, than one is  called a.
By  convention idetifiers for variable and methods are lowercase. uppercase letters are used to seperate these into multiple words, for example getname , findsurfacearea, pretaxtotal, and so on. note that a class name starts with  capital letter. reserved words are entirely lowercase and may not be use as identifiers.
built-in types      every identifier in a java program has a type associated with it. the primitive or built-in types that are included in the AP java subset are

int          integer. for example, 2,-26, 3000
boolean  boolean. just two values, true or false
double    double precision floating -point number. for example, 2.718,-367189.41,1.6e4

(note that primitive type char is not included in the AP java subset)
interger values are stored exactly. because there's fixed amount of memory set aside for their storage, however, intergers are bounded. if you try to store a value whose magnitude is too big in an int variable, you'll get an overflow error. an identifier, for example a variable, is introduced into a java program with a declaration that specifies its type. some examples follow:
int x;
double y, z;
boolean found;
int count= 1;                         //count initialized to 1
double p =2.3, q= 4.1;          //p and q initialized to 2.3 and 4.1
one type can be cast to another compatible type if appropriate. for example,
int total, n;
double average;
      ...
average= (double) total/n;         // total cast to double to ensure
                                                    // real division is used
alternatively,
average = total/9(double) n;
assigning an int to a double automatically casts the int to double. for example,
int num = 5;
double realnum = num;        //num is cast to double
assigning a double to an int without a cast, however, causes a compile-time error. for example,
double x=6.79;
int intnum = x;     //error. need an explicit cast to int
note that casting a floating-point (real) number to an interger simply truncates the number. for example,
double cost = 10.95;
int numdollars = (int) cost;       // set numdollars to 10
if you intent was to round cost to the nearest dollar, you needed to write
int numdollars = (int) (cost + 0.5);    // numdollars has value 11
to round a negative number to the nearest interger:
double negamount = -4.8;
int roundneg = (int) (negamount - 0.5);   //roundneg has a value -5
the strategy of adding or subtracting 0.5 before casting correctly rounds in all cases

final variables      a final variable or user-defined constant, identified by the keyword final, is used to name  a quantity whose value will not change. here are some examples of final declarations:
final double tax_rate= 0.08
final int class_size = 35;

NOTE   1. constant identifiers are, by convention, capitalized.
             2. a final variable can be declared  without initializing it immediately. for example,
final double tax_rate;
if (<some condition>)
tax_rate = 0.08;
else
tax_rate = 0.0;
// tax_rate can be designed to just once: its value is final!
            3.a common use for a constant is as an array bound. for example,
final int maxstudents = 25;
int[] class list = new int [maxstudents];
            4. using constants makes it easier to revise code. just a single change in the final declaration need be made, rather than having to change every occurrence of a value.

arithmetic         
operators    
OPERATOR
MEANING
EXAMPLE
+
addition
3+ x
-
subtraction
p - q
*
multiplication
6 * i
/ division
10/4   //returns 2, not 2.5!
%
mod(remainder)
11% 8  //returns 3




<>NOTE         1. these operators can be  applied to types int and double, even if both type occur in the same expression. for operation involving a double and an int, the int is promoted to double, and the result is a double.                                                                                           2. the mod operator % as in the expression a % b, gives the remainder when a is divided by b. thus 10% 3 evaluates to 1, whereas 4.2% 2.0 evaluate to 0.2.                          
              
3. interger division a/b where both a  and b are of type int returns the interger quotient only (i.e., the answer is truncated). thus 22/6 gives you 3, and 3/4 gives 0. if at least one of the operands is of type double, then the operation becomes regular floating-point division, and there is no truncation. you can control the kind of division that is carried out by explicitly casting ( one or both of) the operands from int to double and vice versa. thus
3.0/4----------------------> 0.75
3/4.0----------------------> 0.75
(int) 3.0/4-----------------> 0
(double) 3/4--------------->0.75 
                                                                                                                                                                                                                                              
you must, however, be careful:
(double) (3/4) ------->   0.0
since the interger division 3/4 is computerd first, before casting the double.
4. the arithmetic operators follow the normal precedence rules (order of operations):
(1) parentheses, from the inner ones out (highest procedence)
(2) *,/,%
(3) +,- (lowest precedence)
here operators on the same line have the same precedence, and, in the absence of parentheses, are invoked from left to right. thus the expressions 19 % 5*3+14/5 evaluates to 4 * 3 +2 =14. note that casting has precedence over all of the operators. thus in the expressions (double) 3/4, 3 wil be cast to double before the division is done.
RELATIONAL
OPERATORS
OPERATOR
MEANING
EXAMPLE
==
equal to
if (x == 100)
! =
not equal to
if (age ! = 21)
>
greater than
if (salary > 30000)
<
less than
if (grade < 65)
>=
greater then or equal to
if (age >= 16)
<=
less then or equal
if (height <=6)

NOTE   1. relational operators are used in boolean expressions that evaluate to true or false.
boolean x = (a !=b)         // initializes x to true if a ! =b,
                                   //  false otherwise
return p ==q;                // returns true if p equals q,
                                  // false otherwise
2. if operands are an int and a double, the int is promoted to a double as for arithmetic operators.
3. relational operators should only be used in the comparison of primitice types (i.e., int, double, or boolean). user-defined types are compared using the equals and compare to methods.
4. be careful when comparing floating-point values! since floating-point numbers cannot be always be represented exactly in the computer memory, they should not be compared directly using relational operators.
                                                             COMPATING FLOATING-POINT NUMBERS
since floating-point numbers are manipulated and stored with a fixed number of significant digits, arithmetic operations generally produce result that must be rounded. this causes round-of error. one concequence is that you cant rely on using the = = or ! = operators to compare two double values for equality. they may differ in their last significant digit or two becuase of round-off error. instead you should test that the magnitud of the diference between the numbers is less than some number about the size of the machine precision. the machine precision is usually denoted e, and is typically about 10^-16 for double precision. so you would like to test something like this [x-y]<e. but this is not good if x and y are very large. these nukbers are essentially equal to machine precision. since they only differ in the 16th signifiant digit. but [x-y] = 10^-6 , not only 10^-16. here you should chack the relative difference:
[x-y] / min ([x], [y])<e
but this test wilol fail for very small numbers, in particular if one of the numbers is zero. so the best general strategy is to test the relative difference unless the numbers are small, in which case you test the absolute difference, whew!


LOGICAL OPERATORS
OPERATOR
MEANING
EXAMPLE
!
NOT
if ( ! found)
&&
AND
if (x < 3 && y >4)
I I
OR
if (age < 2 II height <4)
NOTE                       1. logical operators are applied to boolean expressions to form compund boolean expressions that evaluate to true or false.
                                2. values of true or false are assigned according to the truth tables for the logical operators.
&&
T
F
II
T
F
!

T
T
F
T
T
T
T
F
F
F
F
F
T
F
F
T
3. short-circuit evaluation. the subexpressions in a compound boolean expression are evaluated from left to right, and evaluation automatically stops as soon as the values of the entire expression is known. if a is false, then a && b evaluates to false irrespective of the second operand. so in each case the second operand is not evaluated. this is becuase numscores != 0 will evaluate to false, causing the entire boolean expression conatining the division.
ASSIGMENT
OPERATORS
OPERATOR
EXAMPLE
MEANING
=
x =2
simple assigment
+ =
x + = 4
x = x + 4
- =
y - = 6
y = y - 6
*=
p * = 5
p = p * 5
/ =
n / = 10
n = n / 10
% =
n % = 10
n = n % 10
NOTE     1. all these operators, with the exception of simple assigment, are called compound assignment operators.
              2. chaining of assignment statement is allowed, with evaluation from right to left.
int next, prev, sum;
next = prev= sum = 0;  //initializes sum to 0, then prev to 0
                                //then next to 0
                                                                                                                                                         
INCREMENT AND
DECREMENT
OPERATORS 
OPERATOR
EXAMPLE
MEANING
+ +
i + + or + + i
i is incremented by 1
--
k -- or -- k
k is decremented by 1
note that i + +(postfix) and  + + i(prefix) both have the net effect of incrementing i by 1, but they are not equavalent. its easy to remember: if the + +  is first, you first increment. a similar distiction occurs between k -- and -- k.
OPERATOR                           highest precedence --> (1) !,++, --
PRECEDENCE                                                          (2) *, /,%
                                                                               (3) =, -
                                                                               (4) <,>, < =, >=
                                                                               (5) = =, ! =
                                                                               (6) &&
                                                                               (7) II
                                                        lowest precedence -->  (8) =, +=, -=, *=, /=, %=

here operators on the same line have equal precedence. this evaluation of the operators with equal precedence is from left to right, except for rows 1 and 8 where the order is right to left. it is easy to remember: the only "backward" order is for the unary operators row 1 ans for the varioys assignment operators row 8.
EXAMPLE 1
what will be output by the following statement?
system.out.println (5 +3< 6-1);
since + and - have precedence over <, 5+3 and 6-1, will be evaluated before evaluating the boolean expression. since the value of the expression is false, the stament will output false.
EXAMPLE 2
suppose the int variables x, y and z cuurently have the values 3, 4, and 5. what will the following statement do?
x + =y -= z *= 2;
it will assign a value of 10 to z
then assing a value of -6 to y
the assign the value of -3 to x
(this is the kind of unreadable coding style you should avoid!)

INPUT/OUTPUT

since there is so many ways to provide input to a program, user input is not a part of the AP java subset. if reading input is a necessary part of a question on the AP exam, it will be indicated something like this:
double x = call to a method that reads a floating-point number
or
double x =I0. readdouble( );   //read user input
reading in strings and converting them to numberic values is not in the subset.

OUTPUT              testing the output will berestricted to system.out.println. formatted output will be not be tested.system.out is an object in the system class that allows output to be displayed on the screen. the println method outputs an items and then goes to a new line. the print method outputs an item without going to a new line afterward. an item to be printed can be a string, or a number, or the value of a boolean expression. here are osme examples:
system.out.int ("hot");        }  print hotdogs
system.out.println("dog");

system.out.println ("hot");     } print   hot
system.out.println ("dog");                 dog

system.out.println(7+3);       }   prints   10

system.out.println (7 = = 2+5);    }prints   true

int x = 27;
system.out.println (x) ;      }    prints 27
system.out.println ("values of x is " + x );
                                        prints   value of x is 27

ESCAPE SEQUENCE  
an escape sequence is a backslash foolowed bya single character. it is used to print special character. the three escape sequences that you should know for the AP exam are
ESCAPE SEQUENCE
MEANING
\n
newline
\"
double quote
\\
backslash

here are some examples:
system.out.println ("welcome to\na new line";
prints
welcome to
a new line
the statement
system.out.println (" he is known as \ "hothead harry\".");
prints
he is known as "hothead harry".
the statement
system,.out.println ("the file path is d:\\myfiles\\..");
prints
the file path i d: \myfiles\..

control structures

control structures are the mechanism by which you make the staments of a program run in a nonsequential order. these are two general types: decision making iteration.

DECISION-MAKING
CONTROL STRUCTURES
these include the if, if... else, and switch statements. they are all selection contro structures that introduce a decision-making ability into a program. based on the truth value of a boolean expression, the computer will decide which path to follow. the switch statement is not part of the AP java subset.
THE IF STATEMENT
if (boolean expression)
{
   statements
}
here the statement will be executed only if the boolean expression is true. if it is false, control passes immediately to the first statement following the if statement.
THE IF . . . ELSE STATEMENT
if (boolean expression)
{
statements
}
else
{
statements
}
here if the boolean expression is true, only the statements immidiately following the test will be executed. if the boolean expression is false, only the statements following the else will be executed.

NESTED IF STATEMENT
if the statemnt part of an if statement is itself an if statement, the result is a nested if statement.
EXAMPLE 1
If (boolean exprl)
      if (boolean expr2)
            statement
this is equivalent to
    if (boolean exprl && boolean expr2)
         statement
EXAMPLE 2
beware the dangling else! suppose you want to read in an interger and print it if its positive and even. will the following code do the job?
int n =I0. readint ( )         //read user input
if (n>0)                  
       if (n % 2 = = 0)
               system.out.println(n);
else
   system.out.println (n +" is not positive")
a user enters 7 and is surprised to see the output
7 is not positive
the reasoon is that else always gets matched with the nearest unpaired if, not the first if as the indentiting would suggest. there are towo ways to fix the precceding code. the first is to use {} delimiters to group the statements correctly.
int n = I0.readint ( )       //read user input
if ( n> 0)
{
if (n % 2 = = 0)
     system.out.println (n);
}
else
system.out.println(n + " is not positive");
the second way of fixing the code is to rearrange the statements.
int n = I0.readint ( );             //read user input
if (n <= 0)
system.out.println (n + " is not positive");
else
if (n % 2 = = 0)
system.out.println(n);
system.out.println("welcome to\na new line");
prints
welcome to
a new line
the statement
system.out.println("he is known as\"hotheah harry\".");
prints
he is known as the "hothead harry".
the startement
system.out.println (';the file path is d:\\myfiles\\. . ");
prints
the file path is d:\myfiles\ . .

control structure

control structures are the mechanisms by which you make the statements of a program run in a nonsequential order. there are two general types: decicion making and iteration.
DECISION-MAKING
CONTROL STRUCTURES
these included the if, if. . .else, and switch statements. they are all selection control structures that include a decision-making ability into a program. based on the truth value of a boolean expression, the computer will decide which path to follow. the switch statement is not part of the AP java sebset.
the if statement
if (boolean expression)
{
  statement
}
here the statements will be executed only if the boolean expression is true. if it is false, control passes immediately to the first statement following the if statement.
the if . . . else statement
if (boolean expression)

    statements
}
else
{
    statements
}
here is the boolean expression is true, only the statements immediately following the test will  be executed. if the boolean expression is false, only the statements following the else will be executed.
NESTED IF STATEMENT
the statement part of an if statement is itself an if statement, the result is a nested if statement.
EXAMPLE 1
if (boolean exprl)
     if (boolean expr2)
          statement;
this is equivalent to
if (boolean exprl && boolean expr2)
statement;
EXAMPLE 2
beware the dangling else! suppose you want to read in an integer and print it if its positive and even. will the following code do the job?
int n I0.readint ( );                                    //read user input
if (n > 0)
      if (n % 2 = = 0)
             system.out.println (n);
else
     system.out.println (n + " is not positive");
a user enters 7 and is surprised to see the output
7 is not positive
the reason is the else always gets matched with the nearest unpair if, not the first as the indenting would suggest.
there are 2 ways to fix the preceding code. the first is to use {} delimeters to group the statements correctly.
int n = I0.readprintln(n)        //read user input
{
if  (n % 2 = = 0)
       system.out.println(n)
}
else
     system.out.println(n + " is not positive");
the second way of fixing the code is to rearange the statements.
int n = I0.readint( );                     //read user input
if ( n < = 0)
      system.out.println(n + " is not positive");
else
     if (n % 2 = = 0)
          system.out.println(n);
EXTENDED IF STATEMENT
FOR EXAMPLE,
string grade = I0.readstring ( );      //read user input
if (grade.equals "A"))
     system.out.println ("good");
else if (grade.equals ("C") II grade.equals ("D"))
       system.out.println ("Poor");
if any of a,b,c,d or f are entered, an appropriate message will be written and control will go to the statement immediately following the extended if statement. if any other string is entered, the final else is involked, and the message invalid grade will be written.
java has three different contro structures that allow the computer to perform iterative task: the for loop, while loop, and do . . .while loop. the do . . . while loop is not in the AP java subset.
the for loop
the general form of the for loop is
for (initialization; termination condition;update statement)
{
     statements                  //body of loop
}
the termination condition is tested at the top of the loop; the update statement is performed at the battom.
EXAMPLE 1
//outputs 1 2 3 4
for (i = 1; i < 5; i ++)
       system.out.print(i + " ");
here's how it works. the loop variable i is initialized to 1, and the termination condition 1 < 5 is evaluated. if it is true, the body of the loop is executed and then the loop variable i is incremented according to the update statement. as soon as the termination condition is false (i.e., i > = 5), control passed to the first statement following the loop.
EXAMPLE 2
//OUTPUTS 20 19 18 17 16 15
for (k = 20; k > =15; k --)
       system.out.print (k + "");
EXAMPLE 3
//OUTPUTS 2 4 6 8 10
FOR (J=2; J<=10; J + = 2)
       system.out.print(j + '' '');
NOTE                           1. the loop variable should not have its value changed inside the loop body.
                                    2. the initializing and update statements can use any valid constants,. variables. or expressions.
                                    3. the scope of the loop variable can be restricted to the loop body by combining the loop variable  declaration with the initialization. for example,
for (int i = 0; i < 3; i + + )
{
            . . .
}
                                   4. the following is a syntactically valid:
for ( i = 1; i , =0; i + +)
{
     . . .
}
the loop body will be  executed at all, since the existing condition is true before the first execution.
THE WHILE LOOP
the general form of the while loop is
while (boolean test)
{     
      statements         //loop body
}
hte boolean test is performed at the beginning of the loop. if true, the loop body is executed. otherwise, control passes to the first statementfollowing the loop. after execution of the loop body, the test is performed again. if true, the loop is executed again , and so on.
EXAMPLE 1
int i = 1, mult3 = 3;
while (mult3, 20)
{
    system.out.printl(mult3 + " ");
i + +
mult3 * = i;
}                         //outputs 3 6 18
NOTE                      1. it is possib;e for the body of a while loop never to be executed. this will happen if the test evaluates to false the first time.
                               2. disaster will strikle in the form of an infinite loop if the test can never be false. dont forget to change the loop variable in the body of the loop of the loop in a way that leads to termination!
EXAMPLE 2
INT POWER2 = 1
WHILE ( power2 ! = 20)
{
   system.out.println(power2);
power2 *= 2;
}
since power2 will never exactly equal 20, the loop will grind merrily along eventually causing an interger overflow.
EXAMPLE 3
/* screen out bad data.
* the loop wont allow execution to continue until a valid
* interger is entered */
system.out.println ("enter a positive interger from 1 to 100");
int num = I0.readint ( );                       //read user input
while (num < 1 II num > 100)
{
system.out.println ("number must be from 1 to 100.";
system.out.println ("please reenter");
num = I0.readint ( );
}
EXAMPLE 4
/*uses a sentinel to terminate data entered at the keyboard.
* the sentinel is a value that cannot be part of the data.
It signals the end of the list*/

final int sentinel = - 999;
system.out.println (" enter list of positive intergers, " +
" end list with " + sentinel);
int value = I0.readint ( );     // read user input
while (value ! = sentinel)
{
process the value
value I0.readint( );            //read another value
}
NESTED LOOPS
you create a nested loop when a loop is a statement in the body of another loop.

EXAMPLE 1
for (int k =1; k < = 3; k + + )
{
for ( int i = 1; i < = 4; i + + )
      system.out.print ( " * ");
system.out.println ( );
}
 think:
for each of the 3 rows
}
        print 4 stars
        go to the next line
}
output
* * * *
* * * *
* * * *
EXAMPLE 2
this example has two loops nested in an outer loop.
for (ibt i = 1; i < = 6; i + + )
{
    for (int j = 1; j < = i; j + + )
          system.out.print ("+");
    for ( int j = 1; j < = 6 -i; j + + )
          system.out.print(" *");
    system.out.println( );
}
output
+ * * * * *
+ + * * * *
+ + + * * *
+ + + +* *
+ + + + + *
+ + + + + +

Errors and Exceptions

an exception is an error condition that occurs during the execution of a java program. if you use a negative array index, an arrayindexoutofboundsexception wil be thrown. an unchecked exception is one where you dont provide code to deal with the error. such exception is one where you dont  provide code to deal with the error. such exceptions are automatically handle by java's standard exception-handling methods, which determine execution. you now need to fix your code! a checked exception is one where you provide code ( try/catch/finally statements) to handle the exception. these exceptions are generally not caused by an error in the code. checked exceptions are not part of the ap java subset.
note that in java, arithmetic operations with type double do not throw exceptions. the following exceptions are in the java subset:
EXCEPTION
DISCUSSED IN PAGE
arithmeticexception
15
nullpointerexception
41
classcastexception
79
arrayindexoutofboundexception
170
indexoutoffboundexception 180
nosuchelementexception
250, 252, 375
illegalstateexception
252, 255

java allows you to write code that throws a standard unchecked exception. here is a typical example:
if (numscores = = 0 )
throw new arithmeticexception ( "cannot drive by zero");
else
findaveragescore ( );

NOTE    1. throw and new are both reserved words.
             2. the error message is optional: the line could have read
                      throw new arithmeticexception
             3. writing code to throw your own exceptions is not part of the level a subset. level ab students may be asked to throw a nosuchelementexception or an illegalstateexception.