Professional Documents
Culture Documents
Course Objective
Introduce you to all the key concepts of the Java language, as well as a full coverage of the Java Syntax
You will be exposed to examples of building programs that incorporates Java as its primary building blocks.
History
Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc in 1991. It took 18 months to develop the first working version. Then language was initially called Oak but renamed Java in 1995. Somewhat surprisingly, the original impetus for Java was not the internet! Instead, the primary motivation was the need for a platformindependent (that is architecture-neutral) language that could be used to create software
To be embedded in various consumer electronic devices, such as microwave ovens and remote control. About the time that the details of java were being worked out, a second factor was emerging that would play a crucial role in the future of Java. This was, of course, the World Wide Web. Had the Web not taken shape at about the same time that Java was being implemented. Java might have remained a useful but obscure language for programming consumer electronics. However, with the emergence of the World Wide Web, Java was propelled to the forefront of
Of computer language design, because the Web, too, demanded portable programs. The Java Programming Language?
Java is a general-purpose, concurrent, class-based, object-oriented language. It is designed to be simple enough that many programmers can achieve fluency in the language. Java is related to C and C++ but is organized rather differently, with a number of aspects of C and C++ omitted and a few ideas from other languages included. Java is intended to be a production language, not a research language, and so, as C. A. R. Hoare suggested in his classic paper on language design, the design of Java has avoided including new and untested features.
Java is strongly typed. This specification clearly distinguishes between the compile-time errors that can and must be detected at compile time, and those that occur at run time. Compile time normally consists of translating Java programs into a machine-independent byte-code representation. Run-time activities include loading and linking of the classes needed to execute a program, optional machine code generation and dynamic optimization of the program, and actual program execution.
representation are not available through the language. It includes automatic storage management, typically using a garbage collector, to avoid the safety problems of explicit deallocation (as in C's free or C++'s delete). High-performance garbage-collected implementations of Java can have bounded pauses to support systems programming and realtime applications. Java does not include any unsafe constructs, such as array accesses without index checking, since such unsafe constructs would cause a program to behave in an unspecified way.
Java is normally compiled to a bytecoded instruction set and binary
Why Choose Java? You should choose Java because it is: Simple Secure Portable Object-oriented Robust Multithreaded Architecture-neutral Interpreted High performance Distributed Dynamic
abstract
assert
boolean
break
catch const do enum
byte
char continue double extends
case
class default else final
finally
goto import
float
if instanceof
for
implements int
while
\\ \"
Newline. Position the screen cursor at the beginning of the next line. Horizontal tab. Move the screen cursor to the next tab stop. Carriage return. Position the screen cursor at the beginning of the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. Backslash. Used to print a backslash character. Double quote. Used to print a double quote charcter
Fig. 2.5
Data Types
Every variable must have a data type. A variable's data type determines the values that the variable can contain and the operations that can be performed on it. For example, in the MaxVariablesDemo program, the declaration int largestInteger declares that largestInteger has an integer data type (int). Integers can contain only integral values (both positive and negative). You can perform arithmetic operations, such as addition, on integer variables. The Java programming language has two categories of data types: primitive and reference. A variable of primitive type contains a single value of the appropriate size and format for its type: a number, a character, or a boolean value. For example, an integer value is 32 bits of data in a format known as two's complement, the value of a char is 16 bits of data formatted as a Unicode character, and so on.
Primitive types building blocks for more complicated types Java is strongly typed All variables in a Java program must have a type Java primitive types portable across computer platforms that support Java
T e yp boolean
Size in b its
Sta nd a rd
16 8 16 32 64
float
32
double
64
Fig. 4.16 T he Ja va
[Note: The representation of a boolean is specific to the Java Virtual Machine on each computer platform.] '\u0000' to '\uFFFF' (ISO Unicode character set) (0 to 65535) 128 to +127 (27 to 27 1) 32,768 to +32,767 (215 to 215 1) 2,147,483,648 to +2,147,483,647 (231 to 231 1) 9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 (263 to 263 1) Negative range: (IEEE 754 floating point) 3.4028234663852886E+38 to 1.40129846432481707e45 Positive range: 1.40129846432481707e45 to 3.4028234663852886E+38 Negative range: (IEEE 754 floating point) 1.7976931348623157E+308 to 4.94065645841246544e324 Positive range: 4.94065645841246544e324 to 1.7976931348623157E+308 p rim itive typ e s.
// display them all System.out.println("The largest byte value is " + largestByte); System.out.println("The largest short value is " + largestShort); System.out.println("The largest integer value is " + largestInteger); System.out.println("The largest long value is " + largestLong); System.out.println("The largest float value is " + largestFloat); System.out.println("The largest double value is " + largestDouble); if (Character.isUpperCase(aChar)) { System.out.println("The character " + aChar + " is upper case."); } else { System.out.println("The character " + aChar + " is lower case."); } System.out.println("The value of aBoolean is " + aBoolean); } }
Reference types
Arrays, classes, and interfaces are reference types. The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable (see the following figure). A reference is called a pointer, or a memory address in other languages. The Java programming language does not support the explicit use of addresses like other languages do. You use the variable's name instead.
Operators An operator performs a function on one, two, or three operands. An operator that requires one operand is called a unary operator. For example, ++ is a unary operator that increments the value of its operand by 1. An operator that requires two operands is a binary operator . For example, = is a binary operator that assigns the value from its right-hand operand to its left-hand operand.
And finally, a ternary operator is one that requires three operands. The Java programming language has one ternary operator, ?:, which is a short-hand ifelse statement.
Arithmetic Operators The Java programming language supports various arithmetic operators for all floating-point and integer numbers. These operators are + (addition), (subtraction), * (multiplication), / (division), and % (modulo). The following table summarizes the binary arithmetic operations in the Java programming language.
O rd e r o f e va lua t io n (p re c e d e nc e ) Evaluated first. If there are several of this type of operator, they are evaluated from left to right. Evaluated next. If there are several of this type of operator, they are evaluated from left to right. Pre c e d e nc e o f a rit hm e t ic o p e ra t o rs.
Operator precedence Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: ( a + b + c ) / 3 Follows PEMDAS Parentheses, Exponents, Multiplication, Division, Addition, Subtraction
Here's an example program, ArithmeticDemo , that defines two integers and two double-precision floating-point numbers and uses the five arithmetic operators to perform different arithmetic operations. This program also uses + to concatenate strings. The arithmetic operations are shown in boldface: public class ArithmeticDemo { public static void main(String[] args) { //a few numbers int i = 37; int j = 42; double x = 27.475; double y = 7.22; System.out.println("Variable values..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" x = " + x); System.out.println(" y = " + y);
//adding numbers System.out.println("Adding..."); System.out.println(" i + j = " + (i + j)); System.out.println(" x + y = " + (x + y)); //subtracting numbers System.out.println("Subtracting..."); System.out.println(" i - j = " + (i - j)); System.out.println(" x - y = " + (x - y)); //multiplying numbers System.out.println("Multiplying..."); System.out.println(" i * j = " + (i * j)); System.out.println(" x * y = " + (x * y));
//computing the remainder resulting from dividing numbers System.out.println("Computing the remainder..."); System.out.println(" i % j = " + (i % j)); System.out.println(" x % y = " + (x % y)); //mixing types System.out.println("Mixing types..."); System.out.println(" j + y = " + (j + y)); System.out.println(" i * x = " + (i * x)); } }
The output from this program is:
Variable values... i = 37 j = 42 x = 27.475 y = 7.22 Adding... i + j = 79 x + y = 34.695 Subtracting... i - j = -5 x - y = 20.255 Multiplying... i * j = 1554 x * y = 198.37
Dividing... i/j=0 x / y = 3.8054 Computing the remainder... i % j = 37 x % y = 5.815 Mixing types... j + y = 49.22 i * x = 1016.58
Note that when an integer and a floating-point number are used as operands to a single arithmetic operation, the result is floating point. The integer is implicitly converted to a floating-point number before the operation takes place. The following table summarizes the data type returned by the arithmetic operators, based on the data type of the operands. The necessary conversions take place before the operation is performed.
Operator
Use
Description
Increments op by 1; evaluates to the value of op before it was incremented Increments op by 1; evaluates to the value of op after it was incremented
++
op++
++
---
++op
op---op
Decrements op by 1; evaluates to the value of op before it was decremented Decrements op by 1; evaluates to the value of op after it was decremented
Relational and Conditional Operators A relational operator compares two values and determines the relationship between them. For example, != returns true if its two operands are unequal. The next table summarizes the relational operators:
Sta nd a rd a lg eb ra ic Ja va eq ua lity Exa m p le eq ua lity or or rela tio na l of Ja va rela tiona l op era tor op era tor c ond itio n Equality operators == x == y = != x != y Relational operators > x > y > < x < y < >= x >= y <= x <= y Fig. 2.19 Eq ua lity a nd rela tiona l op era to rs. Mea ning of Ja va c ond ition
x is equal to y x is not equal to y x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y
Following is an example, RelationalDemo , that defines three integer numbers and uses the relational operators to compare them. The relational operations are shown in boldface:
public class RelationalDemo { public static void main(String[] args) { //a few numbers int i = 37; int j = 42; int k = 42; System.out.println("Variable values..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" k = " + k); //greater than System.out.println("Greater than..."); System.out.println(" i > j = " + (i > j)); //false System.out.println(" j > i = " + (j > i)); //true System.out.println(" k > j = " + (k > j)); //false; //they are equal //greater than or equal to System.out.println("Greater than or equal to..."); System.out.println(" i >= j = " + (i >= j)); //false System.out.println(" j >= i = " + (j >= i)); //true System.out.println(" k >= j = " + (k >= j)); //true
//less than System.out.println("Less than..."); System.out.println(" i < j = " + (i < j)); //true System.out.println(" j < i = " + (j < i)); //false System.out.println(" k < j = " + (k < j)); //false //less than or equal to System.out.println("Less than or equal to..."); System.out.println(" i <= j = " + (i <= j)); //true System.out.println(" j <= i = " + (j <= i)); //false System.out.println(" k <= j = " + (k <= j)); //true //equal to System.out.println("Equal to..."); System.out.println(" i == j = " + (i == j)); //false System.out.println(" k == j = " + (k == j)); //true //not equal to System.out.println("Not equal to..."); System.out.println(" i != j = " + (i != j)); //true System.out.println(" k != j = " + (k != j)); //false } }
Logical Operators
Logical operators
Allows for forming more complex conditions Combines simple conditions
(boolean logical AND) || (conditional OR) | (boolean logical inclusive OR) ^ (boolean logical exclusive OR) ! (logical NOT)
expression1 && expression2 false false false false true false true false false true true true Fig. 5.15 && (conditional AND) operator truth table. expression1 expression2
expression1 || expression2 false false false false true true true false true true true true Fig. 5.16 || (conditional OR) operator truth table.
expression1
expression2
Control Structures
Sequential execution Program statements execute one after the other Transfer of control Three control statements can specify order of statements
add 1 to counter
Control Structures
Java has a sequence structure built-in Java provides three selection structures
if Ifelse switch
if Single-Selection Statement
Less Than and Greater Than Comparisons if (elephantWeight > 780) System.out.println("This elephant is too fat for your tightrope act."); if (elephantTotal > 12) cleaningExpense = cleaningExpense + 150;
if (answer == rightAnswer) studentGrade = studentGrade + 10; if (studentGrade == 100) System.out.println("Congratulations -- a perfect score!"); if (team != "New York Jets") chanceToWin = 50; if (answer != rightAnswer) score = score - 5;
A Java program using a main() block statement. class Game { public static void main(String[ ] arguments) { int total = 0; int score = 7; if (score == 7) System.out.println("You score a touchdown!"); if (score == 3) System.out.println("You kick a field goal!"); total = total + score; System out.println("Total score: " + total); } }
Perform action only when condition is true Perform different specified action when condition is
There are times when you want to do something if a condition is true and do something else if the condition is false. You can do this by using the else statement in addition to the if statement, as in the following example: if (answer == correctAnswer) { score += 10; System.out.println("That's right. You get 10 points."); } else { score -= 5; System.out.println("Sorry, that's wrong. You lose 5 points."); } The else statement does not have a condition listed alongside it, unlike the if statement. Generally, the else statement is matched with the if statement that immediately comes before it in a Java program. You also can use else to chain several if statements together, as in the following example: if (grade == "A") System.out.println("You got an A. Great job!"); else if (grade == "B") System.out.println("You got a B. Good work!"); else if (grade == "C") System.out.println("You got a C. You'll never get into a good college!"); else System.out.println("You got an F. You'll do well in Congress!");
switch Statements
Another way to do this is to use the switch statement. You can use it in a Java program to test for a variety of different conditions and respond accordingly. In the following example, the grade example has been rewritten with the switch statement to handle a complicated range of choices:
switch (grade) { case A: System.out.println("You got an A. Great job!"); break; case B: System.out.println("You got a B. Good work!"); break; case C: System.out.println("You got a C. You'll never get into a good college!"); break; default: System.out.println("You got an F. You'll do well in Congress!"); }
the
This module functionality would be to evaluate age value and print appropriate information listed below. If Age < 18 print "You're young - enjoy it! If not print "You're not under 18"
If Age >= 18 and Age < 50 print "You're in the prime of your life if not print "You're not in the prime of your life\n";
If Age >= 50 print " print "You can retire soon - hurrah! if not print "print "You cannot retire soon :( .
the
This module functionality would be to evaluate age value and print appropriate information listed below.
Age < 10 print " print "You're under 10 Age < 20 print "You're under 20 Age < 30 print "You're under 30 Age < 40 print "You're under 40 Age more than 40 print "You're over 40"
the
This module functionality would be to evaluate name value and print appropriate information listed below.
Name is Jim print " print "You're name is Jim Name is Bob print "You're name is Bob Name is Sally print "You're name is Sally Name is Linda print "You're name is Linda Else print I dont know youre name"
This module functionality would be to evaluate a numeric value and print the appropriate information listed below.
iValue = 1 set value = Ace iValue = 10 set value = Ten iValue = 11 set value = Jack iValue = 12 set value = Queen iValue = 13 set value = King After evaluation print iValue = value variable.
This module functionality would be to evaluate grade value and print the appropriate information listed below.
Grade = A print You got an A. Great job Grade = B print You got a B. Good work! Grade = C print You got a C. You'll never get into a good college! Grade = F print "You got an F. You'll do well in Congress!"
/** * Creates a new instance of <code>ClockTalk</code>. */ public ClockTalk() { } /** * @param args the command line arguments */ public static void main(String[] args) { // get current time and date GregorianCalendar now = new GregorianCalendar(); int hour = now.get(Calendar.HOUR); int minute = now.get(Calendar.MINUTE); int month = now.get(Calendar.MONTH) + 1; int day = now.get(Calendar.DATE); int year = now.get(Calendar.YEAR);
// display greeting if (hour < 12) System.out.println("Good morning.\n"); else if (hour < 17) System.out.println("Good afternoon.\n"); else System.out.println("Good evening.\n"); // begin time message by showing the minutes System.out.print("It's"); if (minute != 0) { System.out.print(" " + minute + " "); System.out.print( (minute != 1) ? "minutes" : "minute"); System.out.print(" past"); } // display the hour System.out.print(" "); System.out.print( (hour > 12) ? (hour - 12) : hour ); System.out.print(" o'clock on ");
// display the name of the month switch (month) { case (1): System.out.print("January"); break; case (2): System.out.print("February"); break; case (3): System.out.print("March"); break; case (4): System.out.print("April"); break; case (5): System.out.print("May"); break; case (6): System.out.print("June"); break; case (7): System.out.print("July"); break; case (8): System.out.print("August"); break;
case (9): break; case (10): System.out.print("October"); break; case (11): System.out.print("November"); break; case (12): System.out.print("December"); } // display the date and year System.out.println(" " + day+", " + year + "."); }
merge
decision
The most complex of the loop statements is for. The for loop is often used in cases where you want to repeat a section of a program for a fixed amount of times. It also can be used if the number of times the loop should be repeated is variable. The following is an example of a for loop: for (int number = 0; number < 1000; number++) { if (number % 12 == 0) System.out.println("#: " + number); }
while
Like the for loop, the while loop has a loop condition that controls the execution of the loop statement. Unlike the for loop, the while loop has no initialization or step expressions. The syntax for the while statement follows: while (LoopCondition) Statement
If the Boolean LoopCondition evaluates to true, the Statement is executed and the process starts over. It is important to understand that there is no step expression, as in a for loop. This means that the LoopCondition must somehow be affected by code in the Statement or the loop will infinitely repeat, which is a bad thing. This is bad because an infinite loop causes a program to never exit, which hogs processor time and can ultimately hang the system.
Another important thing to notice about the while loop is that its LoopCondition occurs before the body of the loop Statement. This means that if the LoopCondition initially evaluates to false, the Statement never will be executed. This might seem trivial, but it is in fact the only thing that differentiates the while loop from the do-while loop.
To better understand how the while loop works, take a look at Listing 13.15, which shows how a counting program works using a while loop. The WhileCount class. class WhileCount { public static void main (String args[ ]) { String strLine = ""; int numToCount; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a number to count to between 0 and 10:"); try { strLine =in.readLine(); } catch (Exception e) { System.out.println("Error: " + e.toString()); } numToCount = Integer.parseInt(strLine); if ((numToCount > 0) && (numToCount < 11)) { int i = 1; while (i <= numToCount) { System.out.println(i); i++; } } else System.out.println("That number was not between 0 and 10!"); } }
do-while
The do-while loop is very similar to the while loop, as you can see in the following syntax:
do Statement while (LoopCondition); The major difference between the do-while loop and the while loop is that the LoopCondition is evaluated after the Statement is executed. This difference is important because there might be times when you want the Statement code to be executed at least once, regardless of the LoopCondition. The syntax for the do-while loop follows: The Statement is executed initially, and from then on it is executed as long as the LoopCondition evaluates to true. Like the while loop, you must be careful with the do-while loop to avoid creating an infinite loop. An infinite loop occurs when the LoopCondition remains true indefinitely.
Because the LoopCondition is always true, the message Im Stuck! is printed forever, or at least until you hit Ctrl+C and break out of the program. break and continue Youve already seen how the break statement works in regard to the switch branch. The break statement is also useful when dealing with loops. You can use the break statement to jump out of a loop and effectively bypass the loop condition. Listing 13.16 shows how the break statement can help you out of the infinite loop problem shown earlier.
The BreakLoop class. class BreakLoop { public static void main (String args[]) { int i = 0; do { System.out.println(Im stuck!); i++; if (i > 100) break; }
while (true); } }
Exercises (Loop)
Create a module nestedLoop1.java.
Exercises (Loop)
Create a module nestedLoop2.java.
public class nestedFor { public static void main(String[] args) { for (int i = 1; i < 3; i++) { for (int j = 1; j < 3; j++) { for (int k = 1; k < 3; k++) { System.out.println( "I: "+ i +", J:"+ j +", K: "+k+"\n");
}
} } } }
}
} }