Java History • Java is a general purpose , object-oriented programming language.• The fastest growing programming language in the history of computing• Developed by Sun Microsystems of USA in 1991.• Originally it is called Oak by James Gosling.• Originally designed in 1991 for use in embedded consumer applications• Java team which headed James Gosling developed a Web browser called “Hot Java” tolocate and run applet programs on Internet in 1994.• Oak was renamed “Java” in 1995. • Redesigned in early 1995 with Internet application capabilities• Introduced in May, 1995 and immediately supported by the Netscape Web browser.• Rapidly overtaking C++ in popularity among commercial software developers• Java established itself not only as a leader for Internet programming but also as ageneral purpose, object-oriented programming language.• Java found its home in the heart of the modern programmer.• Java is the first programming language that is not tied to any particular hardware oroperating system.• Programs developed in java can be executed anywhere on any system.• Therefore Java comes as a revolutionary technology because it has brought in afundamental shift in how we develop and use programs.
| Java Features | ||||||||||||
|
| Simple: |
| Java is a simple language as it does not use pointers, preprocessor header files; go to statement and many more others. |
| Object oriented: |
| In Java everything is object. All program code and data within objects and classes. |
| Distributed: |
| Java is designed as a distributed language for creating applications on networks. It has ability to share both data and programs. |
| Interpreted: |
| Interpreting means actually compiling the program line by line and generates the machine code. Java interpreter generates machine code that can be directly executed by the machine is that running the Java program. |
| Robust: |
| Java is a robust language as it provides many safeguards to ensure reliable code. It has strict compile time and run time checking for data types. |
| Secure: |
| No viruses can affect the Java program as Java ensures that program cannot gain access to memory locations without proper authorization. Java systems not only verify all memory access but also ensure that no viruses are communicated with an applet. |
| Architecture-neutral: |
| In Java, changes and upgrade in operating system, processors and system resources will not force any changes in Java programs. |
| Portable: |
| Java programs can be easily moved from one computer system to another, anytime, and anywhere. Java ensures portability in two ways. First, Java compiler generates bytecode instructions that can be implemented on any machin. Secondly the sizes of the primitive data type are machin-independent. |
| High-performance: |
| Java performance is impressive for an interpreted language , mainly due to the use of intermediate bytecode. |
| Multithreaded: |
| Java support multithreaded programs means handling multiple task simultaneously. |
| Dynamic: |
| Java is capable of dynamically linking in new class libraries, methods and objects. |
| Java Features | ||||||||||||
|
| Simple: |
| Java is a simple language as it does not use pointers, preprocessor header files; go to statement and many more others. |
| Object oriented: |
| In Java everything is object. All program code and data within objects and classes. |
| Distributed: |
| Java is designed as a distributed language for creating applications on networks. It has ability to share both data and programs. |
| Interpreted: |
| Interpreting means actually compiling the program line by line and generates the machine code. Java interpreter generates machine code that can be directly executed by the machine is that running the Java program. |
| Robust: |
| Java is a robust language as it provides many safeguards to ensure reliable code. It has strict compile time and run time checking for data types. |
| Secure: |
| No viruses can affect the Java program as Java ensures that program cannot gain access to memory locations without proper authorization. Java systems not only verify all memory access but also ensure that no viruses are communicated with an applet. |
| Architecture-neutral: |
| In Java, changes and upgrade in operating system, processors and system resources will not force any changes in Java programs. |
| Portable: |
| Java programs can be easily moved from one computer system to another, anytime, and anywhere. Java ensures portability in two ways. First, Java compiler generates bytecode instructions that can be implemented on any machin. Secondly the sizes of the primitive data type are machin-independent. |
| High-performance: |
| Java performance is impressive for an interpreted language , mainly due to the use of intermediate bytecode. |
| Multithreaded: |
| Java support multithreaded programs means handling multiple task simultaneously. |
| Dynamic: |
| Java is capable of dynamically linking in new class libraries, methods and objects. |
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| exception handling, networking, multi-threading, I/O, and more. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Java has two things: a programming language and a platform.
The Java Programming Language Java is a high-level programming language that is all of the following:
Java is also unusual in that each Java program is both compiled and interpreted.With a compiler, it translates a Java program into an intermediate language called Java bytecodes–the platform-independent codes interpreted by the Java interpreter. With an interpreter, each Java bytecode instruction is parsed and run on the computer. Compilation happens just once; interpretation occurs each time the program is executed. This figure show how it works.
The Java bytecodes is the machine code instructions for the Java Virtual Machine (Java VM). Every Java interpreter, whether it’s a Java development tool or a Web browser that can run Java applets, is an implementation of the Java VM. The Java VM can also be implemented in hardware. Java bytecodes help make “write once, run anywhere” possible. One can compile your Java program into bytecodes on any platform that has a Java compiler. The bytecodes can then be run on any implementation of the Java VM.
The Java Platform
The Java VM is the base for the Java platform and is ported onto various hardware-based platforms. The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. The Java API(application programming interface) is grouped into libraries (packages) of related components.
Java Development Kit
The below figure depicts a Java program, such as an application or applet, that’s running on the Java platform. As the figure shows, the Java API and Virtual Machine insulates the Java program from hardware dependencies.
To View the Installation Process of JDK (Java Development Kit)(With Sound), Click Here!
HARDWARE AND SOFTWARE REQUIREMENTS Java is currently supported on Window 95, Window NT, Sun Solaries, Macintosh and UNIX machine.The minimum software and hardware requirement for 95 version of Java are as follows: • IBM-compatible 486 system • Minimum of 8 MB memory • Windows 95 software • A Windows-compatible sound card • A hard drive; • A CD-ROM drive • A Microsoft-compatible mouse
Disadvantages of Java
Example:
To view, how to write,compile and run the Java Program.(With Sound) Click Here! Comments in Java Code The bold characters in the following listing are comments. /**
Defining a Class
Defining a Class
The main Method The first bold line in the following listing begins the definition of a main method. /** class HelloWorldApp { Every Java application must contain a main method whose signature looks like this: public static void main(String[] args) Every Java application must contain a main method whose signature looks like this: public static void main(String[] args) The method signature for the main method contains three modifiers: • public indicates that the main method can be called by any object.
Using Classes and Objects The “Hello World” application is about the simplest Java program one can write that actually does something. Because it is such a simple program, it doesn’t need to define any classes except for HelloWorldApp. The “Hello World” application does use another class–the System class–that is part of the API (application programming interface) provided with the Java environment. The System class provides system-independent access to system-dependent functionality. The bold code in the following listing illustrates the use of a class variable of the System class, and of an instance method. /** class HelloWorldApp The construct System.out is the full name of the out variable in the System class. Using an Instance Method or Variable Methods and variables that are not class methods or class variables are known as instance methods and instance variables. While System’s out variable is a class variable, it refers to an instance of the PrintStream class (a class provided with the Java development environment) that implements the standard output stream. When the System class is loaded into the application, it instantiates PrintStream and assigns the new PrintStream object to the out class variable. System.out.println(“Hello World!”); This line of code displays “Hello World!” to the application’s standard output stream
Java Program Structure A Java program may contain one or more section which is as follow:
The documentation section comprises a set of comment line of the program, the author
This statement declares a package name and inform the compiler that the class defined here belong to this package.Ex: package student;
This statement instructs the interpreter to load the specific class contained in the package.Ex: import student. test;
An interface is like a class but include a group of method declarations.
Classes are the primary and essential elements of Java program. These classes are used
As every Java stand-alone program requires a main method as its starting point, this class is the essential part of the program.
Java Tokens The smallest individual units in a program are known as TOKEN.A java program is a collection of tokens, comments and white spaces.Java language includes five types of tokens They are:
Reserved KeywordKeywords have specific meaning and implement specific features of the language.
Ex: {}, [], ; , . , () etc.
|
Variables
| Variables are locations in memory in which values can be stored. Each one has a name, a type, and a value.
Before we can use a variable, we have to declare it. After it is declared, we can then assign values to it. |
||||
| Java actually has three kinds of variables: | ||||
|
||||
| Instance variables, are used to define the attributes of a particular object. Class variables are similar to instance variables, except their values apply to all that class’s instances (and to the class itself) rather than having different values for each object. Local variables are declared and used inside method definitions, Although all three kinds of variables are declared in much the same ways, class and instance variables are accessed and assigned in slightly different ways from local variables. Java does not have global variables-that is, variables that are global to all parts of a program. Instance and class variables can be used to communicate global information between and among objects. |
| Declaring Variables |
| To use any variable in a Java program, we must first declare it. Variable declarations consist of a type and a variable name: |
| int myAge; String myName; boolean isTired; |
| Variable definitions can go anywhere in a method definition (that is, anywhere a regular Java statement can go), although they are most commonly declared at the beginning of the definition before they are used: |
| public static void main (String args[]) { int count; String title; boolean isAsleep; … } |
| We can string together variable names with the same type on one line: |
| int x, y, z; String firstName, LastName; |
| We can also give each variable an initial value when we declare it: |
| int myAge, mySize, numShoes = 28; String myName = “eBIZ”; boolean isTired = true; int a = 4, b = 5, c = 6; |
| If there are multiple variables on the same line with only one initializer the initial value applies to only the last variable in a declaration. We can also group individual variables and initializers on the same line using |
Rules on Variable Names Variable names in Java can start with a letter, an underscore (_), or a dollar sign ($). They cannot start with a number. After the first character, our variable names can include any letter or number. Symbols, such as %, *, @, and so on, are often reserved for operators in Java, so we should be careful when using symbols in variable names. The Java language uses the Unicode character set. The Java language is case sensitive, which means that uppercase letters are different from lowercase letters. This means that the variable X is different from the variable x, and a rose is not a Rose is not a ROSE.
| Variable Types | ||
| In addition to the variable name, each variable declaration must have a type, which defines what values that variable can hold. | ||
| The variable type can be one of three things: | ||
| • One of the eight primitive data types • The name of a class or interface • An array |
||
|
|
||
| Primitive Data Types | ||
| The eight primitive data types handle common types for integers, floating-point numbers, characters, and boolean values (true or false). | ||
| They’re called primitive because they’re built into the system and are not actual objects, which makes them more efficient to use. | ||
| Integer Type | ||
| There are four Java integer types, each with a different range of values. All are signed, which means they can hold either positive or negative numbers. |
||
|
|||||||||||||||
|
| Floating-point type: |
| Floating-point numbers are used for numbers with a decimal part. There are two floating-point types: float (32 bits, single precision) and double (64 bits, double precision). |
| Char type: |
| The char type is used for individual characters. Because Java uses the Unicode character set, the char type has 16 bits of precision, unsigned. |
|
||||||
|
||||||
|
||||||
| Example 2: | ||||||
|
||||||
|
||||||
|
|
||||||
Expressions and Operators
| Operators enable us to perform an evaluation or computation on a data object or objects. Operators applied to variables and literals form expressions. |
||
| An expression can be thought of as a programmatic equation. Therefore, an expression is a sequence of one or more data objects (operands) and zero or more operators that produce a result. | ||
| An example of an expression follows: | ||
| x = y / 3;
In this expression, x and y are variables, 3 is a literal, and = and / are operators. This expression states that the y variable is divided by 3 using the division Here the expression is described from right to left. |
||
|
|
| Operator Precedence |
| Java expressions are typically evaluated from left to right, there still are many times when the result of an expression would be indeterminate without other rules. |
| The following expression illustrates the problem: |
| x = 2 * 6 + 16 / 4 |
| By using the left-to-right evaluation of the expression, the multiplication operation 2 * 6 is carried out first, which leaves a result of 12. The addition operation 12 + 16 is then performed, which gives a result of 28. The division operation 28 / 4 is then performed, which gives a result of 7. Finally, the assignment operation x = 7 is handled, in which the number 7 is assigned to the variable x. But–it’s wrong! The problem is that using a simple left-to-right evaluation of expressions can yield inconsistent results, depending on the order of the operators. The solution to this problem lies in operator precedence, which determines the order in which operators are evaluated. Every Java operator has an associated precedence. Following is a list of all the Java operators from highest to lowest precedence. In this list of operators, all the operators in a particular row have equal precedence. The precedence level of each row decreases from top to bottom. This means that the [] operator has a higher precedence than the * operator, but the same precedence as the () operator. |
| . | [] | () | |
| ++ | – | ! | ~ |
| * | / | % | |
| + | – | ||
| << | >> | >>> | |
| < | > | <= | >= |
| = | != | ||
| & | |||
| ^ | |||
| && | |||
| || | |||
| ?: | |||
| = |
Evaluation of expressions still moves from left to right, but only when dealing with operators that have the same precedence. Otherwise, operators with a higher precedence are evaluated before operators with a lower precedence. Knowing this, take another look at the sample equation:x = 2 * 6 + 16 / 4 Before using the left-to-right evaluation of the expression, first look to see whether any of the operators have differing precedence. Here the multiplication (*) and division (/) operators both have the highest precedence, followed by the addition operator (+), and then the assignment operator (=).
Because the multiplication and division operators share the same precedence, evaluate
them from left to right. Doing this, we first perform the multiplication operation 2 * 6
with the result of 12. Then we perform the division operation 16 / 4, which results in 4. After performing these two operations, the expression looks like this:x = 12 + 4; Because the addition operator has a higher precedence than the assignment operator, we perform the addition operation 12 + 4 next, resulting in 16. Finally, the assignment operation x = 16 is processed, resulting in the number 16 being assigned to the variable x. As we can see, evaluating the expression using operator precedence yields a completely different result. Just to get the point across, take a look at another expression that uses parentheses for grouping purposes:x = 2 * (11 – 7); Without the grouping parentheses, we would perform the multiplication operation first and then the subtraction operation. However, referring back to the precedence list, the () operator comes before all other operators. So the subtraction operation 11 – 7 is performed first, yielding 4 and the following expression:x = 2 * 4; The rest of the expression is easily resolved with a multiplication operation and an assignment operation to yield a result of 8 in the variable x.
| Integer Operators | ||||
|
| Unary Integer Operators | |||||||||||||||||||
| Unary integer operators act on a single integer. Lists of the unary integer operators. | |||||||||||||||||||
| The unary integer operators. | |||||||||||||||||||
|
|||||||||||||||||||
| The increment and decrement operators (++ and –) increase and decrease integer ariables by 1.
These operators can be used in either prefix or postfix form. A prefix operator takes effect before the evaluation of the expression it is in; a postfix operator takes effect after the expression has been evaluated. Prefix unary operators are placed immediately before the variable; postfix unary operators are placed immediately following the variable. Following are examples of each type of operator: |
|||||||||||||||||||
| y = ++x; z = x–; |
|||||||||||||||||||
| In the first example, x is prefix incremented, which means that it is incremented before being assigned to y. In the second example, x is postfix decremented, which means that it is decremented after being assigned to z. Here z is assigned the value of x before x is decremented. The IncDec program, which uses both types of operators. |
|||||||||||||||||||
| The IncDec class. | |||||||||||||||||||
| class IncDec { public static void main (String args[]) { int x = 8, y = 13; System.out.println(“x = ” + x); System.out.println(“y = ” + y); System.out.println(“++x = ” + ++x); System.out.println(“y++ = ” + y++); System.out.println(“x = ” + x); System.out.println(“y = ” + y); } } |
|||||||||||||||||||
| The IncDec program produces the following results: | |||||||||||||||||||
| x = 8 y = 13 ++x = 9 y++ = 13 x = 9 y = 14 |
|||||||||||||||||||
| The negation unary integer operator (-) is used to change the sign of an integer value. | |||||||||||||||||||
| x = 8; y = -x; |
|||||||||||||||||||
| In this example, x is assigned the literal value 8 and then is negated and assigned to y. The resulting value of y is -8. |
|||||||||||||||||||
|
| Binary Integer Operators | ||||||||||||||||||||||||
| Binary integer operators act on pairs of integers. Lists of the binary integer operators. | ||||||||||||||||||||||||
| The binary integer operators. | ||||||||||||||||||||||||
|
The Arithmetic program, which shows how the basic binary integer arithmetic operators work.
| The Arithmetic class. |
| class Arithmetic { public static void main (String args[]) { int x = 17, y = 5; System.out.println(“x = ” + x); System.out.println(“y = ” + y); System.out.println(“x + y = ” + (x + y)); System.out.println(“x – y = ” + (x – y)); System.out.println(“x * y = ” + (x * y)); System.out.println(“x / y = ” + (x / y)); System.out.println(“x % y = ” + (x % y)); } } |
| The results of running the Arithmetic program follow: |
| x = 17 y = 5 x + y = 22 x – y = 12 x * y = 85 x / y = 3 x % y = 2 |
The bitwise AND, OR, and XOR operators (&, |, and ^) all act on the individual bits of an integer. These operators are sometimes useful when an integer is being used as a bit field.
| The Bitwise class. | |
| class Bitwise { public static void main (String args[]) { int x = 5, y = 6; System.out.println(“x = ” + x); System.out.println(“y = ” + y); System.out.println(“x & y = ” + (x & y)); System.out.println(“x | y = ” + (x | y)); System.out.println(“x ^ y = ” + (x ^ y)); } } |
|
| The output of running Bitwise follows: | |
| x = 5 y = 6 x & y = 4 x | y = 7 x ^ y = 3 |
|
|
|
|
| In Bitwise, the variables x and y are set to 5 and 6, which correspond to the binary numbers 0101 and 0110. | |
| The bitwise AND operation compares each bit of each number to see whether they are the same. It then sets the resulting bit to 1 if both bits being compared are 1; it sets the resulting bit to 0 otherwise. The result of the bitwise AND operation on these two numbers is 0100 in binary, or decimal 4. | |
| The bitwise OR operator sets the resulting bit to 1 if either of the bits being compared is 1. For these numbers, the result is 0111 binary, or 7 decimal. | |
| Finally, the bitwise XOR operator sets resulting bits to 1 if exactly one of the bits being compared is 1 and 0 otherwise. For these numbers, the result is 0011 binary, or 3 decimal. The left-shift, right-shift, and zero-fill-right-shift operators (<<, >>, and >>>) shift the individual bits of an integer by a specified integer amount. |
|
| Following are some examples of how these operators are used: | |
| x << 3; y >> 7; z >>> 2; |
|
| In the first example, the individual bits of the integer variable x are shifted to the left three places. In the second example, the bits of y are shifted to the right seven places. Finally, the third example shows z being shifted to the right two places, with zeros shifted into the two leftmost places. |
| The Shift class. |
| class Shift { public static void main (String args[]) { int x = 7; System.out.println(“x = ” + x); System.out.println(“x >> 2 = ” + (x >> 2)); System.out.println(“x << 1 = ” + (x << 1)); System.out.println(“x >>> 1 = ” + (x >>> 1)); } } |
| The output of Shift follows: |
| x = 7 x >> 2 = 1 x << 1 = 14 x >>> 1 = 3 |
| The number being shifted in this case is the decimal 7, which is represented in binary as 0111. The first right-shift operation shifts the bits two places to the right, resulting in the binary number 0001, or decimal 1.
The next operation, a left-shift, shifts the bits one place to the left, resulting in the binary number 1110, or decimal 14. The last operation is a zero-fill-right-shift, which shifts the bits one place to the right, resulting in the binary number 0011, or decimal 3. |
| Relational Integer Operators |
| The last group of integer operators is the relational operators, which all operate on integers but return a type boolean. Lists of the relational integer operators. |
| The relational integer operators. |
|
Description |
Operator |
| Less-than | < |
| Greater-than | > |
| Less-than-or-equal-to | <= |
| Greater-than-or-equal-to | >= |
| Equal-to | == |
| Not-equal-to | != |
These operators all perform comparisons between integers.
| The Relational class |
| class Relational { public static void main (String args[]) { } |
| The output of running Relational follows: |
| x= 7 y = 11 z = 11 x < y = true x > z = false y <= z = true x >= y = false y == z = true x != y = true |
| Output |
| Floating point Operators |
| There are three types of operations that can be performed on floating-point numbers: |
| 1. unary, 2. binary, 3. and relational |
| Unary operators act only on single floating-point numbers,
binary operators act on pairs of floating-point numbers. Both unary and binary floating-point operators return floating-point results. Relational operators, act on two floating-point numbers but return a boolean result. Unary and binary floating-point operators return a float type if both operands are of type float. If one or both of the operands are of type double, however, the result of the operation is of type double. |
| Unary Floating-Point Operators | ||||||
| The unary floating point operators act on a single floating-point number. Lists of the unary floating-point operators. | ||||||
| The unary floating-point operators. | ||||||
|
||||||
| The only two unary floating-point operators are the increment and decrement operators. These two operators respectively add and subtract 1.0 from their floating-point operand. |
| Binary Floating-Point Operators | ||||||||||||
| The binary floating-point operators act on a pair of floating-point numbers. Lists of the binary floating-point operators. | ||||||||||||
| The binary floating-point operators. | ||||||||||||
|
||||||||||||
| The binary floating-point operators consist of the four traditional binary operations (+, -, *, /), along with the modulus operator (%). |
| The FloatMath class. |
| class FloatMath { public static void main (String args[]) { float x = 23.5F, y = 7.3F; System.out.println(“x = ” + x); System.out.println(“y = ” + y); System.out.println(“x + y = ” + (x + y)); System.out.println(“x – y = ” + (x – y)); System.out.println(“x * y = ” + (x * y)); System.out.println(“x / y = ” + (x / y)); System.out.println(“x % y = ” + (x % y)); } } |
| The output of FloatMath follows: |
| x = 23.5 y = 7.3 x + y = 30.8 x – y = 16.2 x * y = 171.55 x / y = 3.21918 x % y = 1.6 |
| Output |
| Relational Floating-Point Operators | ||||||||||||||||||||
| The relational floating-point operators compare two floating-point operands, leaving a boolean result. | ||||||||||||||||||||
| Boolean Operators | ||||||||||||||||||||
| Boolean operators act on boolean types and return a boolean result. | ||||||||||||||||||||
| The boolean operators | ||||||||||||||||||||
|
||||||||||||||||||||
| The evaluation operators (&, |, and ^) evaluate both sides of an expression before determining the result. | ||||||||||||||||||||
| The following code shows how the evaluation AND operator is necessary for the complete evaluation of an expression: | ||||||||||||||||||||
| while ((++x < 10) && (++y < 15)) { System.out.println(x); System.out.println(y); } |
||||||||||||||||||||
| The three boolean operators–negation, equal-to, and not-equal-to (!, ==, and !=) The negation operator toggles the value of a boolean from false to true or from true to false, depending on the original value. The equal-to operator simply determines whether two boolean values are equal (both true or both false). Similarly, the not-equal-to operator determines whether two boolean operands are unequal. The conditional boolean operator (? 🙂 is the most unique of the boolean operators This operator also is known as the ternary operator because it takes three items: a condition and two expressions. The syntax for the conditional operator follows: Condition ? Expression1 : Expression2 The Condition, which itself is a boolean, is first evaluated to determine whether it is true or false. If Condition evaluates to a true result, Expression1 is evaluated. If Condition ends up being false, Expression2 is evaluated. |
| The Conditional class | |
| class Conditional { public static void main (String args[]) { int x = 0; boolean isEven = false; System.out.println(“x = ” + x); x = isEven ? 4 : 7; System.out.println(“x = ” + x); } } |
|
| The results of the Conditional program follow: | |
| x = 0 x = 7 |
|
|
|
|
|
| Relational Floating-Point Operators | ||||||||||||||||||||
| The relational floating-point operators compare two floating-point operands, leaving a boolean result. | ||||||||||||||||||||
| Boolean Operators | ||||||||||||||||||||
| Boolean operators act on boolean types and return a boolean result. | ||||||||||||||||||||
| The boolean operators | ||||||||||||||||||||
|
||||||||||||||||||||
| The evaluation operators (&, |, and ^) evaluate both sides of an expression before determining the result. | ||||||||||||||||||||
| The following code shows how the evaluation AND operator is necessary for the complete evaluation of an expression: | ||||||||||||||||||||
| while ((++x < 10) && (++y < 15)) { System.out.println(x); System.out.println(y); } |
||||||||||||||||||||
| The three boolean operators–negation, equal-to, and not-equal-to (!, ==, and !=) The negation operator toggles the value of a boolean from false to true or from true to false, depending on the original value. The equal-to operator simply determines whether two boolean values are equal (both true or both false). Similarly, the not-equal-to operator determines whether two boolean operands are unequal. The conditional boolean operator (? 🙂 is the most unique of the boolean operators This operator also is known as the ternary operator because it takes three items: a condition and two expressions. The syntax for the conditional operator follows: Condition ? Expression1 : Expression2 The Condition, which itself is a boolean, is first evaluated to determine whether it is true or false. If Condition evaluates to a true result, Expression1 is evaluated. If Condition ends up being false, Expression2 is evaluated. |
| The Conditional class | |
| class Conditional { public static void main (String args[]) { int x = 0; boolean isEven = false; System.out.println(“x = ” + x); x = isEven ? 4 : 7; System.out.println(“x = ” + x); } } |
|
| The results of the Conditional program follow: | |
| x = 0 x = 7 |
|
|
|
|
|
String Operator
| There is only one string operator: the concatenation operator (+). The concatenation operator for strings works very similarly to the addition operator for numbers–it adds strings together. |
| The Concatenation class |
| class Concatenation { public static void main (String args[]) { String firstHalf = “What ” + “did “; String secondHalf = “you ” + “say?”; System.out.println(firstHalf + secondHalf); } } |
| The output of Concatenation follows: |
| What did you say? |
| Output |
In the Concatenation program, literal strings are concatenated to make assignments to
the two string variables, firstHalf and secondHalf, at time of creation. The two string
variables are then concatenated within the call to the println() method.
Assignment Operators
| Assignment operators actually work with all the fundamental data types. | ||||||||||||||||||||
| The assignment operators | ||||||||||||||||||||
|
||||||||||||||||||||
| Examples: | ||||||||||||||||||||
| x += 6; x *= (y – 3); |
||||||||||||||||||||
| In the first example, x and 6 are added and the result stored in x. In the second example, 3 is subtracted from y and the result is multiplied by x. The final result is then stored in x |
Arithmetic assignment operations
|
||||||||||||
|
Example:This program reads a percentage value from the user (such as 5.5) and converts to the correct decimal equivalent (such as 0.055) by using the division assignment operator. import java.util.*;
import java.io.*;
public class AppStr
{
public static void main(String[] args)
{
// Variable for holding a percentage entered by the user // Prompt for and read the percentage System.out.print(“Enter a percentage in n.nn format: “);
double percent;
Scanner Keyboard = new Scanner(System.in);
percent = Keyboard.nextDouble();
//percent = Keyboard.readDouble();
// Convert it to its decimal equivalent and display the result
percent /= 100;
System.out.println(“The decimal equivalent is ” + percent);
}
}
| Output |
Conversions
| Conversion is performed automatically when mixed numeric types appear within an expression.
Variables and constants are not altered, but their values are copied to intermediate areas of larger size or precision to prevent possible data loss during the calculation. This is known as a “widening” conversion. |
| The order of conversion (from narrowest to widest) is as follows. Memorize this table! |
| The data type resulting from an expression is that of the largest or most precise variable or constant appearing in the expression but is never smaller than int. |
| Example: |
| This program to convert a fahrenheit temperature to celsius will NOT compile. |
| import
java.util.*; // Variables for holding fahrenheit and celsius temperatures float tempC; // Prompt for and read the fahrenheit temperature System.out.print(“Enter the fahrenheit temperature (nn.n): “); // Convert to celsius and display the result tempC = 5 * (tempF – 32) / 9; } |
Note:To fix the compile error in this code, tempC must be double or tempF must be float . After Correction changing the tempC into double the result is…..
Click Here to view the image!
Casts
|
||||||||
|
| Some thing on arithmetic expressions |
| Arithmetic expressions can be large and complex with several variables, constants, and operators. The order in which operations are performed is the same as in mathematics (multiplication and division first, then addition and subtraction, working from left to right).
To avoid confusion, good programmers keep their expressions as simple as possible and use parenthesis for clarity. |
Logical operators
| 1. Combine the results of two Boolean expressions into a single boolean value | ||||||||||||||||||||||||
| 2. Provide for complex logic. The following table shows the operators and how they can be | ||||||||||||||||||||||||
| used to combine the results of two Boolean expressions X and Y: | ||||||||||||||||||||||||
|
||||||||||||||||||||||||
|
Bitwise operations
| Bitwise operations act upon individual bits within integer data. |
| They are used to perform the logical operations AND, OR, and XOR (eXclusive OR), complementing (reversing all bits), and shifting (sliding bits to the left or right). |
| Logical bitwise operations | ||||||||
| 1. Use the standard boolean operators (&, |, and ^) to act upon two integer values. The short-circuit boolean operators (&& and ||) are not used for bitwise operations and will result in a compile error if attempted. | ||||||||
| 2. Produce an integer result (of size int or larger) that is the logical AND, OR, or XOR of two operands. | ||||||||
| The rules for these operations are as follows: | ||||||||
|
The complement operator
| 1. Is unary (has a single operand)? |
| 2. Uses the ~ operator to “flip” (reverse) the bits within an integer value. If a bit is “on” it is turned “off”. If a bit is “off” it is turned “on”. |
| For example, |
| if byte a = 17; // Binary value: 0001 0001 Hex value: 11 byte b; after executing the statement b = (byte) ~a; |
| variable b will have a value of -18 (because 0001 0001 reverses to 1110 1110). Once again, the cast is needed in order to store the int value that results from the operation. |
| Example: |
| The following program can be run to test complement operations. | |
| import java.util.*; import java.io.*; public class Aman { public static void main(String[] args) { // Variable to be read from the user // Prompt for and read an integer value System.out.print(“Integer: “); // Display the result of complementing the number System.out.println(” ~” + number + ” = ” + ~number); |
|
|
|
|
| Flow control with if and else | ||||||||||||||||||
|
||||||||||||||||||
|
||||||||||||||||||
| The first form is often referred to as a “single statement if”. | ||||||||||||||||||
|
||||||||||||||||||
|
|
||||||||||||||||||
| The else statement |
| 1) Defines an alternative and mutually exclusive logic path to be followed if the preceding if statement expression evaluates to false |
| 2) Must always be paired with, and follow, an if statement. It can never be coded separately |
| 3) Have two forms. |
| The general syntax is either of the following: |
| else statement; or else |
| The first form is often referred to as a “single statement else”. |
| For example, |
| if (amountDue > 0) System.out.println(“You owe ” + amountDue); else System.out.println(“You owe nothing”); |
| will add to the grand total and display how much is owed if amountDue is greater than zero. Otherwise, the customerRating will be set to ‘A’ and the “You owe nothing” message will be displayed. |
| The two logic paths are mutually exclusive and merge at the first statement after the end of the else block. |
| 4) Can trap programmers who get sloppy. |
| For example, |
| if (age < 65) System.out.println(“Regular admission”); else; System.out.println(“Senior admission”); |
| will always display the “Senior admission” message no matter what value age has. The accidental semicolon after the else says that if the expression is false you want to do nothing. Logic then merges at the next statement, so the message is always displayed. |
Nesting
|
It is permitted. |
|
| Example: | |
| import java.util.*; import java.io.*; public class Aman { public static void main(String[] args) { System.out.print(“Enter age: “); } |
|
|
| Notes: |
| 1. The program prompts for and reads a person’s age from the user. |
| 2. Based upon the value of age, it displays a different admission fee (under 5 is free, 5-17 is 2 dollars, 18-64 is 5 dollars, and 65 and over is 4 dollars). |
| Switch statements | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| for, while, and do-while statements | |
| The ability to “loop” by executing one or more statements repetitively is an important part of programming. | |
| Loops reduce the number of statements a programmer must code and result in a smaller, more memory efficient program. | |
| In Java, looping is performed using the for, while, and do-while statements. | |
|
|
| The for statement |
| 1) It is useful when the number of passes (iterations) can be predetermined |
| The general syntax |
| for (initialization; condition; update) { statements; } |
| where: |
| initialization – represents the declaration of one or more local variables of the same data type. When loop processing is complete, all such variables are destroyed. |
| condition – represents a binary expression that, if true, allows the loop to continue. The condition is tested prior to each iteration. If no longer true, processing continues at the first statement after the closing brace of the for loop. |
| update – represents one or more expressions to be executed at the end of each iteration. |
| The braces may be omitted if the loop consists of a single statement. This would constitute a “single statement for loop”. |
| Example 1: |
| Counting to 10 with a local variable |
| for (int i = 1; i <= 10; i++) System.out.println(i); |
| This is a single statement for loop. |
| Local variable i is initialized to 1 before the first iteration and is used for loop control (its value determines when the loop will end). As long as i is less than or equal to 10, looping will continue. At the end of each iteration, i is incremented. Within each iteration, the current value of i is displayed. |
| When the condition is no longer true, processing will continue at the next statement in the program and variable i will be destroyed. |
| Example 2: |
| Counting to 10 without a local variable |
| Counting to 10 without a local variable int i = 1; for (; i <= 10; i++) System.out.println(i); System.out.println(“Now i is ” + i); |
| Here loop control variable i is initialized outside the loop, it will not be destroyed when the loop completes. Its final value (which will be 11) is displayed by the statement after the loop. |
| Notice that when no initialization expression is coded, a place holding semicolon is still required. |
| Example 3: | |
| Coding multiple initialization and update expressions | |
| for (int i = 1, j = 10; i <= 10; i++, j–) System.out.println(i + ” x ” + j + ” = ” + (i * j)); |
|
| This loop initializes two local variables, i and j, of the same data type before the first iteration. | |
| At the end of each iteration, i is incremented and j is decremented. Within each iteration, the product of i and j is displayed. | |
| Notice that commas are used to separate multiple initialization and update expressions. | |
| It can be nested. | |
| For example, | |
| the following program generates a simple 9 x 9 multiplication table: | |
| import java.io.*; public class Aman { public static void main(String[] args) { // This outer loop generates one row of the multiplication for (int row = 1; row <= 9; row++) { // This inner loop generates one column of the current row for (int column = 1; column <= 9; column++) // If a one digit number is about to be displayed, preceed it if ((row * column) < 10) // Display the number. System.out.print((row * column)); // End the current line. System.out.print(” “); |
|
|
|
| The while statement |
| 1) It Defines a block of code to be executed as long as a particular condition is met. |
| The condition is tested prior to each iteration. |
| It has the general syntax |
| while (condition) { statements; } |
| where condition represents a binary expression that, if true, permits an iteration of the loop. If no longer true, processing continues at the first statement after the closing brace of the while loop. |
| The braces may be omitted if the loop consists of a single statement. This would constitute a “single statement while loop”. |
| 1) It does not provide for initialization of variables or automatic update expressions. In spite of these limitations, a while loop can be used in place of nearly any for loop as shown by these examples: |
| Example 1: |
| Counting to 10 without a local variable |
| int i = 1; while (i <= 10) { System.out.println(i); i++; } |
| Loop control variable i is initialized outside the loop. Prior to each iteration, the value of i is tested to determine if it is still less than or equal to 10. If so, the current value of i is displayed and i is incremented. Otherwise processing will jump to the first statement after the closing brace of the loop. |
| Example 2: |
| An endless loop |
| while (true) System.out.println(“I won’t end”); |
| This is the preferred technique for launching an endless loop. |
| Example 3: |
| A small program using nested while loops to generate a 9 x 9 multiplication table: |
| import java.io.*; public class Aman { public static void main(String[] args) { // Initialize the row number. int row = 1; // This outer loop generates one row of the multiplication while (row <= 9) // Initialize the column number. int column = 1; // This inner loop generates one column of the current row while (column <= 9) // If a one digit number is about to be displayed, preceed it if ((row * column) < 10) // Display the number. System.out.print((row * column)); // Increment the column number. column++; // End the current line. System.out.print(” “); // Increment the row number. row++; |
| Output |
The do-while statement
| 1) It defines a block of code to be executed as long as a particular condition is met. The condition is tested at the end of each iteration. It always guaranteed at least one pass through a do-while loop. | |
| syntax do { statements; } while (condition); |
|
| where condition represents a binary expression that, if true, permits another iteration of the loop to be performed. If no longer true, processing continues at the next statement. | |
| The braces may be omitted if the loop consists of a single statement. This would constitute a “single statement do-while loop”. | |
| It can be used in place of nearly any while loop as shown by these examples: | |
| Example 1: | |
| Counting to 10 without a local variable | |
| int i = 1; do { System.out.println(i); i++; } while (i <= 10); |
|
| Loop control variable i is initialized outside the loop. Within the loop, the current value of i is displayed and i is incremented. At the end of each iteration, the value of i is tested to determine if it is still less than or equal to 10. If so, the body of the loop is repeated. Otherwise processing will jump to the next statement. | |
| Example 2: | |
| An endless loop | |
| do { System.out.println(“I won’t end”); } while(true); |
|
| Example 3: | |
| A small program using nested do-while loops to generate a 9 x 9 multiplication table | |
| import java.io.*; public class Aman { public static void main(String[] args) { // Initialize the row number. int row = 1; // This outer loop generates one row of the multiplication do // Initialize the column number. int column = 1; // This inner loop generates one column of the current row do // If a one digit number is about to be displayed, preceed it if ((row * column) < 10) // Display the number. System.out.print((row * column)); // Increment the column number. column++; // End the current line. System.out.print(” “); // Increment the row number. row++; |
|
|
| Using break and continue | |
| At times, it is desirable to exit from a loop or short-circuit the current iteration of a loop. The break and continue statements make it happen. | |
|
|
|
The break statement
| 1) Can only appear within a loop or a switch statement. |
| 2) Causes an immediate exit from a loop structure before the test condition is met. Once a break statement is encountered, the loop immediately terminates, skipping any remaining code. |
| For example, |
| for (int x = 0; x < 10; x++) { if (x == 5) break; else System.out.print(” ” + x); } |
| will end prematurely when x takes on a value of 5. |
| The output displayed will be: |
| 0 1 2 3 4 |
| 3) It may specify the label of the loop to be abandoned. This makes it possible to abandon a specific loop. |
| For example, |
| outer: for (int i = 1; i <= 5; i++) { for (int j = 5; j >= 1; j–) { if (i == j) break outer; else System.out.println(“i = ” + i + “, j = ” + j); } } |
| will end the outer loop when i equals j. |
| The output displayed will be: |
| i = 1, j = 5 i = 1, j = 4 i = 1, j = 3 i = 1, j = 2 |
| 4) It causes an immediate exit from a switch, skipping any remaining code. |
| For example, if key is a char variable having a value entered by the user, the following statements will display whether they entered an ‘A’ or a ‘B’: |
| switch (key) { case ‘a’: case ‘A’: System.out.println(“You entered an ‘A'”); break; case ‘b’: case ‘B’: System.out.println(“You entered a ‘B'”); break; default: System.out.println(“You did not enter an ‘A’ or a ‘B'”); break; } |
The continue statement
| 1) Can only appear within a loop. |
| 2) Skips all remaining statements within the loop and resumes with the next iteration. |
| For example, |
| for (int x = 0; x < 10; x++) { if (x == 5) continue; else System.out.print(” ” + x); } |
| will short-circuit when x takes on a value of 5. |
| The output displayed will be: |
| 0 1 2 3 4 6 7 8 9 |
| 3)It may specify the label of the loop to be continued. This makes it possible to skip to the next iteration of the specified loop. |
| For example, |
| outer: for (int i = 1; i <= 5; i++) { for (int j = 5; j >= 1; j–) { if (i == j) continue outer; else System.out.println(“i = ” + i + “, j = ” + j); } } |
| will short-circuit to the next iteration of the loop labeled outer when i equals j. |
| The output displayed will be: |
| i = 1, j = 5 i = 1, j = 4 i = 1, j = 3 i = 1, j = 2 i = 2, j = 5 i = 2, j = 4 i = 2, j = 3 i = 3, j = 5 i = 3, j = 4 i = 4, j = 5 |
| Introduction to Classes | ||||
|
||||
|
|
||||
| The Benefit of Classes | ||||||||||||||||||||||||||||||||||
| Objects provide the benefit of modularity and information hiding. Classes provide the benefit of reusability. Software programmers use the same class, and thus the same code, over and over again to create many objects. | ||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| Defining Classes | ||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||
| Class using constructor | |||||||||||||||||||||
|
|||||||||||||||||||||
|
|
|||||||||||||||||||||
| Object | |||||||||||||||||||||
|
|||||||||||||||||||||
|
|
|||||||||||||||||||||
| Declaring an Object | ||||||
|
||||||
| Instantiating an Object | ||||||||||||
|
||||||||||||
|
|
||||||||||||
| Initializing an Object | |||||||||||||||||||||
|
|||||||||||||||||||||
|
|
|||||||||||||||||||||
Referencing an Object’s Variables
| Assume we create a rectangle named rect as described in the previous section. To move rect to a new location, |
| we would write: |
| rect.origin = new Point(15, 30); |
| This statement moves the rectangle by setting its point of origin to a new position. rect.origin is the name of rect’s origin variable. |
| The Rectangle class has two other variables– width and height– that are accessible to objects outside of the class. We can use the same notation to access them and calculate the rectangle’s area using this statement |
| area = rect.height * rect.width;; |
| In general, to refer to an object’s variables, append the name of the variable to an object reference with an intervening period (.): |
| objectReference.variable |
| The first part of the variable’s name, objectReference, must be a reference to an object. |
Referencing an Object’s Variables
| Assume we create a rectangle named rect as described in the previous section. To move rect to a new location, |
| we would write: |
| rect.origin = new Point(15, 30); |
| This statement moves the rectangle by setting its point of origin to a new position. rect.origin is the name of rect’s origin variable. |
| The Rectangle class has two other variables– width and height– that are accessible to objects outside of the class. We can use the same notation to access them and calculate the rectangle’s area using this statement |
| area = rect.height * rect.width;; |
| In general, to refer to an object’s variables, append the name of the variable to an object reference with an intervening period (.): |
| objectReference.variable |
| The first part of the variable’s name, objectReference, must be a reference to an object. |
Creating Classes
| The diagram lists the class and identifies the structure of the code. |
| The Class Declaration | |
|
|
|
| public | |
| The public modifier declares that the class can be used by any class regardless of its package. | |
| abstract | |
| Declares that the class cannot be instantiated. | |
| final | |
| Declares that the class cannot be subclassed. | |
| class Name Of Class | |
| The class keyword indicates to the compiler that this is a class declaration and that the name of the class is NameOfClass. | |
| extends Super | |
| The extends clause identifies Super as the superclass of the class, thereby inserting the class within the class hierarchy | |
| implements Interfaces | |
| To declare that our class implements one or more interfaces, use the keyword implements followed by a comma-delimited list of the names of the interfaces implemented by the class | |
|
|
|
| The Class Body | |||||||
| The class body contains all of the code that provides for the life cycle of the objects created from it: | |||||||
|
|||||||
| Variables and methods collectively are called members. | |||||||
| Constructors are not methods. Nor are they members. | |||||||
|
|
onstructors for Classes
| All Java classes have constructors that are used to initialize a new object of that type. |
| A constructor has the same name as the class. |
| For example, |
| The name of the Stack class’s constructor is Stack, the name of the Rectangle class’s constructor is Rectangle, and the name of the Thread class’s constructor is Thread. Stack defines a single constructor: |
| public Stack() { items = new Vector(10); } |
| A constructor uses its arguments to initialize the new object’s state. When creating an object, choose the constructor whose arguments best reflect how we want to initialize the new object. |
| When declaring constructors for our class, we use the following access specifiers in the constructor declaration to specify what other objects can create instances of our class: |
| private |
| No other class can instantiate our class. Our class may contain public class methods (sometimes called factory methods), and those methods can construct an object and return it, but no other classes can. |
| protected |
| Only subclasses of our class can create instances of it. |
| public |
| Any class can create an instance of our class. |
| package |
| Only classes within the same package as our class can construct an instance of it. Constructors provide a way to initialize a new object. |
| Implementing Methods | |||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| The Method Body | |||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| A Method’s Name | |||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| Example of the Math class | |||||||||||||||||||||||||||||||||||||||||
| Different methods in the Math Class: | |||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
Arrays
| Introduction |
| An array is a collection of items. Each slot in the array can hold an object or a primitive value. Arrays in Java are objects that can be treated just like other objects in the language. |
| An array is an indexed table of like values. While they can exist in more than one dimension, we are only interested in one-dimensional arrays as depicted by the following: |
| This array consists of five elements where each is an integer value (217, 138, 92, 12, and 168). |
| To access a particular element within an array, its corresponding index (offset) is used. For example, the integer value at index location 3 within this array is 12. Notice that the indexes are zero based because the offset of the first element is always zero (you don’t have to skip over any other elements to get there). |
| While all programming languages include the ability to process arrays, Java provides enhanced integrity and other features not found in other languages. |
ava arrays
| Java array require that all elements be of the same data type. |
| For example, |
| We may create an array of char values, or an array of float values, or an array of boolean values, etc… |
| Java array are objects and must be declared like one. |
| The general syntax is as follows: |
| data-type[] identifier = new data-type[n]; or data-type identifier[] = new data-type[n]; |
| Where identifier is the array (object) reference and n is an integer expression that specifies how many elements are in the array. |
| For example, |
| int[] myArray = new int[5]; |
| Alternatively, a programmer may split the definition of the array reference and the instantiation of the array into two statements as follows: |
| int[] myArray; myArray = new int[5]; |
| Using either technique, it is important to understand what is created. |
| The following diagram may help: |
| The array reference (myArray) can be thought of as pointing to the array whose elements reside on the memory heap. |
| Notes: |
| 1. At the time an array reference is declared, it initially contains null (it doesn’t point to anything). It doesn’t receive a value until an array is assigned to it. |
| 2. An array reference can only be assigned an array of the correct type. In the above example, myArray is declared to be a reference to an int array, so only an array of int values can ever be assigned to it. To attempt otherwise will result in a compile error. |
| 3. An array reference may be reused to point to a different array (of the appropriate type). Like all objects, however, an array that can no longer be r eferenced will be garbage collected. |
| 4. When instantiated, all array elements are automatically initialized to binary zeros. This means all elements of numeric arrays will be zero, all elements of boolean arrays will be false, and all elements of char arrays will be the null character. |
| Java array can be constructed from a value list. |
| This is an alternative construction technique as shown by |
| char[] chars = {‘a’, ‘b’, ‘c’}; |
| This creates a three element array of characters. The first element is initialized to ‘a’, the second is initialized to ‘b’, and the third is initialized to ‘c’. |
| Notes: |
| 1. The number of elements in the array is determined by the number of values in the list and the new keyword isn’t coded. |
| 2. When a value list is used, it can only be coded in the statement that declares the array reference. |
| In other words, the following will not compile: |
| char[] chars; chars = {‘a’, ‘b’, ‘c’}; |
| Java array permit an element to be accessed via its unique index. |
| For example, |
| int[] numbers = {12, 15, 3, 8}; |
| The following expression will reference the third element (an int with a value of 3) |
| numbers[2] |
| Notes: |
| 1. An index must be int or able to be widened to int to avoid a compile error. It may not be boolean, long, float, or double. |
| 2. If an index is negative of exceeds the maximum valid index for the array, a runtime error occurs. The JVM will throw an ArrayIndexOutOfBoundsException. Catching and processing such exceptions is a topic in advanced Java. |
| Java array have a publicly available length field. This is an int constant representing the number of elements within the array. It is extremely useful when coding a loop to process all the elements within an array. |
| For example, |
| The following small program creates an array, loads it with some random numbers, and displays the array’s contents: |
| public class AppArr { public static void main(String[] args) { double[] values = new double[10]; for (int i = 0; i < values.length; i++) { values[i] = Math.random(); } for (int i = 0; i < values.length; i++) { System.out.println(values[i]); } } } |
| Notes: |
| 1. In an array object, length is a field and NOT a method. A common mistake is to code length() as you would with a String or StringBuffer object and get a compile error. |
| 2. Because the for loops are limited by the length of the array, the code is very flexible. Changing the number of elements in the array declaration is all that is needed to work with a different sized array. |
| Object arrays | ||||||||||||||||||||||||||||||||||||||
| Object array are declared with the class name as the type. | ||||||||||||||||||||||||||||||||||||||
| For example | ||||||||||||||||||||||||||||||||||||||
| String[] names = new String[5]; | ||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||
| Strings | |||
| A sequence of character data is called a string and is implemented in the Java environment by the String class (a member of the java.lang package). The character-counting program uses Strings in two different places. The first is in the definition of the main() method: | |||
| String[] args | |||
| This code explicitly declares an array, named args, that contains String objects. The empty brackets indicate that the length of the array is unknown at compilation time because the array is passed in at runtime. | |||
| The second use of Strings in the example program is these two uses of literal strings | |||
| (a string of characters between double quotation marks ” and “): | |||
| “Input has ” . . . ” chars.” |
|||
| The compiler implicitly allocates a String object when it encounters a literal string. So, the program implicitly allocates two String objects one for each of the two literal strings shown previously. | |||
| String String[] arrayOfStrings = new String[10]; | |||
| The elements in this array are reference types, that is, each element contains a reference to a String object. | |||
| At this point, enough memory has been allocated to contain the String references, but no memory has been allocated for the Strings themselves. If we attempted to access one of arrayOfStrings elements at this point, we would get a NullPointerException because the array is empty and contains no Strings and no String objects. | |||
| We have to allocate the actual String objects separately: | |||
| for (int i = 0; i < arrayOfStrings.length; i ++) { arrayOfStrings[i] = new String(“Hello ” + i); |
|||
| objects are immutable–that is, they cannot be changed once they’ve been created. The java.lang package provides a different class, StringBuffer, which we can use to create and manipulate character data on the fly. | |||
|
|
|||
| tring Concatenation | |||
| Java lets us concatenate strings together easily using the + operator. The example program uses this feature of the Java language to print its output. The following code snippet concatenates three strings together to produce its output: | |||
| “Input has ” + count + ” chars.” | |||
| Two of the strings concatenated together are literal strings: “Input has ” and ” chars.” The third string–the one in the middle–is actually an integer that first gets converted to a string and then is concatenated to the others. | |||
|
|
|||
Inheritance Introduction
| Inheritance is a concept in object-oriented programming where all classes are arranged in a strict hierarchy. Each class in the hierarchy has superclasses (classes above it in the hierarchy) and any number of subclasses (classes below it in the hierarchy). Subclasses inherit attributes and behavior from their superclasses |
| In Java, as in object-oriented programming languages, classes can be derived from other classes. |
| The derived class (the class that is derived from another class) is called a subclass. |
| The class from which its derived is called the superclass. |
| In fact, in Java, all classes must be derived from some class. |
| The top-most class, the class from which all other classes are derived, is the Object class defined in java.lang. |
| Object is the root of a hierarchy of classes. |
| The subclass inherits state and behavior in the form of variables and methods from its superclass. |
| The subclass can just use the items inherited from its superclass as is, or the subclass can modify or override it. |
| Definition: |
| A subclass is a class that derives from another class. A subclass inherits state and behavior from all of its ancestors. |
Creating Subclasses
| For example, |
| suppose that we wanted to create a subclass named SubClass of another class named SuperClass. We would write: |
| class SubClass extends SuperClass { . . . } |
| This declares that SubClass is the subclass of the Superclass class. It also implicitly declares that SuperClass is the superclass of SubClass. A subclass also inherits variables and methods from its superclass’s superclass, and so on up the inheritance tree. |
| A Java class can have only one direct superclass. |
| Java does not support multiple inheritance. |
| Creating a subclass can be as simple as including the extends clause in your class declaration. |
| Member Variables In Subclass Inherit? | ||||||||||||
|
||||||||||||
|
|
||||||||||||
Hiding Member Variables
| The member variables defined in the subclass hide member variables of the same name in the superclass. |
| One interesting feature of Java member variables is that a class can access a hidden member variable through its superclass. |
| Consider this superclass and subclass pair: |
| class Super { Number aNumber; } class Sub extends Super { Float aNumber; } |
| The aNumber variable in Sub hides aNumber in Super. But we can access aNumber from the superclass with: |
| super.aNumber |
| super is a Java language keyword that allows a method to refer to hidden variables and overriden methods of the superclass. |
Methods In Subclass Inherit?
| The rule that specifies which methods get inherited by a subclass is similar to that for member variables. |
| Rule: |
| A subclass inherits all of the methods within its superclass that are accessible to that subclass (unless the method is overriden by the subclass). |
| That is, subclasses |
| 1. inherit those methods declared as public or protected |
| 2. inherit those methods declared with no access specifier as long as the subclass is in the same package as the superclass |
| 3. don’t inherit a superclass’s method if the subclass declares a method using the same name. The method in the subclass is said to override the one in the superclass. |
| 4. don’t inherit private methods |
| Methods a Subclass Must Override | |||||||||||
|
|||||||||||
|
|
|||||||||||
| he Benefits of Inheritance | |||||||||||
| • Subclasses provide specialized behaviors from the basis of common elements provided by the superclass. Through the use of inheritance, programmers can reuse the code in the superclass many times. | |||||||||||
| • Programmers can implement superclasses called abstract classes that define “generic” behaviors. The abstract superclass defines and may partially implement the behavior but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses. | |||||||||||
Interfaces
| An interface is a collection of method names, without definitions, that can be added to classes to provide additional behavior not included with those methods the class defined itself or inherited from its superclasses. |
| The problem with multiple inheritance is that it makes a programming language far more complex to learn, to use, and to implement. |
| A Java interface is a collection of abstract behavior that can be mixed into any class to add to that class behavior that is not supplied by its superclasses. Specifically, a Java interface contains nothing but abstract method definitions and constants-no instance variables and no method implementations. |
| Interfaces are implemented and used throughout the Java class library whenever a behavior is expected to be implemented by a number of disparate classes. |
| The Java class hierarchy, for example, defines and uses the interfaces java.lang.Runnable |
| java.util.Enumeration, |
| java.util.Observable, |
| java.awt.image.ImageConsumer, and java.awt.image.ImageProducer. |
| Interfaces and Classes | ||||||||||
|
||||||||||
|
|
||||||||||
| Implementing and Using Interfaces | ||||||||||||||||||||
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| Implementing Multiple Interfaces | ||||||||||||||||||||
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| Creating and Extending Interfaces | ||||||||||||||||||||
|
||||||||||||||||||||
| Interfaces, like classes, can belong to a package by adding a package statement to the first line of the class file. | ||||||||||||||||||||
| Interfaces can also import other interfaces and classes from other packages, just as classes can. | ||||||||||||||||||||
|
|
||||||||||||||||||||
| Methods Inside Interfaces | ||||||||||||||||||||
| An actual implementation for the method in a class: | ||||||||||||||||||||
| public class Orange extends Fruit { public germinate(Fruitlike self) |
||||||||||||||||||||
|
|
||||||||||||||||||||
| Extending Interfaces | ||||||||||||||||||||
| When one interface inherits from another interface, that “subinterface” acquires all the method definitions and constants that its “superinterface” defined. | ||||||||||||||||||||
| To extend an interface, we use the extends keyword just as you do in a class definition: | ||||||||||||||||||||
| public interface Fruitlike extends Foodlike { … } |
||||||||||||||||||||
| In multiply inherited interfaces, the rules for managing method name conflicts are the same as for classes that use multiple interfaces; methods that differ only in return type will result in a compiler error. | ||||||||||||||||||||
|
|
||||||||||||||||||||
| Introduction | ||||||||||||||||||||
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| Declaring Packages | ||||||||||||||||||||
| The syntax for the package statement: | ||||||||||||||||||||
| package Identifier; | ||||||||||||||||||||
| This statement must be placed at the beginning of a compilation unit (a single source file), before any class declarations. | ||||||||||||||||||||
| Every class located in a compilation unit with a package statement is considered part of that package | ||||||||||||||||||||
| Packages can be nested within other packages. When this is done, the Java interpreter expects the directory structure containing the executable classes to match the package hierarchy. | ||||||||||||||||||||
|
|
||||||||||||||||||||
Importing Packages
| The import statement enables us to import classes from other packages into a compilation unit. We can import individual classes or entire packages of classes at the same time if we want. |
| The syntax for the import statement follows: |
| import Identifier; |
| Identifier is the name of the class or package of classes we are importing. |
| Other Example: |
| import java.awt.Color; import java.awt.*; |
| The first statement imports the specific class Color, which is located in the java.awt package. The second statement imports all the classes in the java.awt package. |
| Note that the following statement doesn’t work: |
| import java.*; |
| This statement doesn’t work because we can’t import nested packages with the * specification. This wildcard works only when importing all the classes in a particular package, which is still very useful. |
| There is one other way to import objects from other packages: explicit package referencing. |
| By explicitly referencing the package name each time we use an object, we can avoid using an import statement. Using this technique, the declaration of the color member variable look like this: |
| java.awt.Color color; |
Creating Our Own Packages
| The first step is to decide what the name of our package is going to be. |
| The name we choose for our package depends on how we are going to be using those classes. |
| Step two in creating packages is to create a directory structure on our disk that matches the package name. |
| If your package has just one name (mypackage), we’ll only have to create a directory for that one name. |
| If the package name has several parts, however, we’ll have to create directories within directories. |
| For the package name edu.nonsense.eng.fooblitzky, we’ll need to create an edu directory and then create a nonsense directory inside edu, an eng directory inside nonsense, and a fooblitzky directory inside eng. Our classes and source files can then go inside the fooblitzky directory. |
| Use package to Add Our Class to a Package |
| The final step to putting our class inside packages is to add the package command to our source files. |
| The package command says “this class goes inside this package,” and is used like this: |
| package myclasses; package edu.nonsense.eng.fooblitzky; package java.awt; |
The Java Language Package
| The Different Java Packages |
| Eight packages comprise the standard Java development environment. |
| The Java language package, also known as java.lang, contains classes that are core to the Java language. The classes in this package are grouped as follow: |
| Object |
| The grand-daddy of all classes–the class from which all others inherit. |
| Data Type Wrappers |
| A collection of classes used to wrap variables of a primitive data type: Boolean, Character, Double, Float, Integer and Long. Each of these classes are subclasses of the abstract class Number. |
| Strings |
| Two classes that implement character data. is a thorough lesson on the use of both types of strings. |
| System and Runtime |
| These two classes provide let your programs use system resources. System provides a system-independent programming interface to system resources and Runtime gives you direct system-specific access to the runtime environment. |
| Threads |
| The Thread, ThreadDeath and ThreadGroup classes implement the multi-threading capabilities so important to the Java language. The java.lang package also defines the Runnable interface. Runnable makes it convenient for Java class to be active without subclassing the Thread class. |
| Classes |
| The Class class provides a runtime description of a class and the ClassLoader class allows you to load classes into your program during runtime. |
| Math |
| A library of math routines and values such as pi. |
| Exceptions, Errors and Throwable |
| When an error occurs in a Java program, the program throws an object which indicates what the problem was and the state of the interpreter when the error occurred. Only objects that derive from the Throwable class can be thrown. There are two main subclasses of Throwable: Exception and Error. Exceptions are a form of Throwable that “normal” programs may try to catch. Errors are used for more catastophic errors–normal programs should not catch errors. The java.lang package contains the Throwable, Exception and Error classes, and numerous subclasses of Exception and Error that represent specific problems. |
| Processes |
| Process objects represent the system process that is created when you use Runtime to execute system commands. The java.lang packages defines and implements the generic Process class. |
The compiler automatically imports this package for us. No other packages are automatically imported.
he Java I/O Package The Java I/O Package (java.io) provides a set of input and output streams used to read and write data to files or other input and output sources.
The Java Utility Package This Java package, java.util, contains a collection of utility classes. Among them are several generic data structures (Dictionary, Stack, Vector, Hashtable) a useful object for tokenizing a string and another for manipulating calendar dates. The java.util package also contains the Observer interface and Observable class which allow objects to notify one another when they change. The java.util classes aren’t covered separately in this tutorial although some examples use these classes.
| The Java Networking Package | ||
| The java.net package contains classes and interface definitions that implement various networking capabilities. The classes in this package include a class that implement a URL, a connection to a URL, a socket connection, and a datagram packet. You can use these classes to implement client-server applications and other networking communication applications. | ||
|
|
||
| The Applet Package | ||
| This package contains the Applet class — the class that you must subclass if you’re writing an applet. Included in this package is the AudioClip interface which provides a very high level abstraction of audio. | ||
|
|
||
The Abstract Window Toolkit Packages
| Three packages comprise the Abstract Window Toolkit: java.awt, java.awt.image, and java.awt.peer. |
| AWT Package |
| The java.awt package provides GUI elements used to get input from and display information to the user such as windows, buttons, scrollbars, and text items. |
| AWT Image Package |
| The java.awt.image package contains classes and interfaces for managing image data, such as setting the color model, cropping, color filtering, setting pixel values, and grabbing snapshots of the screen. |
| AWT Peer Package |
| The java.awt.peer package contains classes and interfaces that connect platform-independent AWT components to their platform-dependent implementation (such as Motif widgets or Microsoft Windows controls). |
Introduction:
| Multithreading is a fundamental feature of the Java language specification. The creators of Java understood the importance of multithreading and provided easy to use features for application developers. Two of these features, the Thread class and the Runnable interface, will be covered shortly. |
| Multithreading is not the same as multiprocessing. The latter involves the use of two or more processors (CPUs). Multithreading involves the sharing of a single processor and the interleaving of CPU time as shown by the following diagram: |
| Because there is only one processor, only one instruction can be executed at a time. In a Java program, the decision as to which thread is currently executing is determined by the JVM. |
| Multithreading is used to execute even the simplest Java program. Even if a program doesn’t create its own threads, the Java Virtual Machine creates multiple threads to support the program. One thread performs the processing of the main() method. Other threads manage and monitor system resources. The garbage collector, for example, is always running as a low-priority thread. |
Thread
| A thread–sometimes known as an execution context or a lightweight process–is a single sequential flow of control within a process. |
| Definition: |
| A thread is a single sequential flow of control within a program |
| Example: |
| The following program is a simple Java application that creates and starts two independent threads: |
| class TwoThreadsTest { public static void main (String[] args) { class SimpleThread extends Thread { { } |
| A thread is similar to the sequential programs described above: a single thread also has a beginning, an end, a sequence, and at any given time during the runtime of the thread there is a single point of execution. |
The HotJava Web browser is an example of a multithreaded application. Within the HotJava browser we can scroll a page while it’s downloading an applet or image, play animation and sound concurrently, print a page in the background while we download a new page, or watch three sorting algorithms race to the finish.
Thread Attributes
| Java threads are implemented by the Thread class, which is part of the java.lang package. The Thread class implements a system independent definition of Java threads. But under the hood, the actual implementation of concurrent operation is provided by a system-specific implementation. |
| The life of a thread |
| In Java, all threads are objects that are constructed, pass between several “states”, and die in keeping with the following diagram: |
| 1. When initially constructed, the thread is New |
| 2. When all resources the thread requires are available, it enters the Ready state. The thread is ready to use the CPU. |
| 1. When selected by the JVM for processing, the thread enters the Running state. This is the state that all threads aspire to but only one is ever running at an instant in time. |
| 2. When the thread requests to sleep for an interval of time, must wait for a resource (such as completion of I/O), or is suspended by the JVM, it becomes Blocked. It gives up the CPU and will return to the Ready state when the block is removed. |
| 3. When the thread completes its processing or is killed by the JVM, it enters the Dead state. The thread object will still exist, but will no longer be allowed to use the CPU. |
| Thread Body |
| All of the action takes place in the thread’s body–the thread’s run() method. We can provide the body to a Thread in one of two ways: |
| a. by subclassing the Thread class and overriding its run() method, |
b. by creating a Thread with a Runnable object as its target. Creating the ThreadThe application in which an applet is running calls the applet’s start() method when the user visits the applet’s page.The Clock applet creates a Thread, clockThread, in its start() method and starts the thread. public void start()
{
if (clockThread == null)
{
clockThread = new Thread(this, “Clock”);
clockThread.start();
}
} First, the start() method checks to see if clockThread is null. If clockThread is null, then the applet has just been loaded or has been previously stopped and a new thread must be created. Otherwise, the applet is already running. The applet creates a new thread with this invocation:clockThread = new Thread(this, “Clock”); Here–the Clock applet–is the first argument to the thread constructor. The first argument to this Thread constructor must implement the Runnable interface and becomes the thread’s target. When constructed in this way, the clock thread gets its run() method from its target Runnable object–in this case, the Clock applet. The second argument is just a name for the thread. After a thread has been created and initialized, the runtime system calls its run() method. The code in the run() method implements the behavior for which the thread was created. Stopping the ThreadWhen we leave the page that displays the Clock applet, the application in which the applet is running calls the applet’s stop() method.The Clock’s stop() method sets the clockThread to null.This tells the main loop in the run() method to terminate eventually resulting in the thread stopping and being garbage collected.public void stop()
{
clockThread = null;
} we can use clockThread.stop() instead, which would immediately stop the clock thread.However, the Thread class’s stop() method has a sudden effect, which means that the run() method might be in the middle of some critical operation when the thread is stopped.For more complex run() methods, using Thread’s stop() method might leave the program in an inconsistent or awkward state. For this reason, it’s best to avoid using the Thread class’s stop() method when possible. If we revisit the page, the start() method is called again, and the clock starts up again with a new thread. The Run MethodAnd finally the Clock’s run() method implements the heart of the Clock applet and looks like this: public void run()
{
// loop terminates when clockThread is set to null in stop()
while (Thread.currentThread() == clockThread)
{
repaint();
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
}
}
}
Thread State
| Throughout its life, a Java thread is in one of several states. A thread’s state indicates what the Thread is doing and what it is capable of doing at that time of its life: is it running? Is it sleeping? Is it dead? |
| The above diagram illustrates the various states that a Java thread can be in at any point during its life. It also illustrates which method calls cause a transition to another State. |
| New Thread |
| The following statement creates a new thread but does not start it, thereby leaving the thread in the “New Thread” state. |
| Thread myThread = new MyThreadClass(); |
| When a thread is in the “New Thread” state, it is merely an empty Thread object. No system resources have been allocated for it yet. Thus when a thread is in this state, we can only start the thread or stop it. Calling any method besides start() or stop() when a thread is in this state makes no sense and causes an IllegalThreadstateException. |
| Runnable |
| Now consider these two lines of code: |
| Thread myThread = new MyThreadClass(); myThread.start(); |
| The start() method creates the system resources necessary to run the thread, schedules the thread to run, and calls the thread’s run() method. At this point the thread is in the“Runnable” state. This state is called “Runnable” rather than “Running” because the thread might not actually be running when it is in this state. Many computers have a single processor, making it impossible to run all “Runnable” threads at the same time. So, the Java runtime system must implement a scheduling scheme that shares the processor between all “Runnable” threads. |
| Not Runnable |
| A thread enters the “Not Runnable” state when one of these four events occurs: |
| 1. Someone invokes its sleep() method. |
| 2. Someone invokes its suspend() method. |
| 3. The thread uses its wait() method to wait on a condition variable. |
| 4. The thread is blocking on I/O. |
| For example, |
| The bold line in the following code snippet puts the current thread to sleep for 10 seconds (10,000 milliseconds): |
| try { Thread.sleep(10000); } catch (InterruptedException e) { } |
| During the 10 seconds that myThread is asleep; even if the processor becomes available myThread does not run. After the 10 seconds are up, myThread becomes “Runnable”again and, if the processor becomes available, runs. |
| If a thread has been put to sleep, then the specified number of milliseconds must elapse before the thread becomes “Runnable” again. Calling resume() on a sleeping thread has no effect. |
| The following indicates the escape route for every entrance into the “Not Runnable” state. |
| 1. If a thread has been put to sleep, then the specified number of milliseconds must elapse. |
| 2. If a thread has been suspended, then someone must call its resume() method. |
| 3. If a thread is waiting on a condition variable, whatever object owns the variable must relinquish it by calling either notify() or notifyAll(). |
| 4. If a thread is blocked on I/O, then the I/O must complete. |
| Dead |
| A thread can die in two ways: either from natural causes, or by being killed (stopped). A thread dies naturally when its run() method exits normally. |
| For example, |
| The while loop in this method is a finite loop–it will iterate 100 times and then exit. |
| public void run() { int i = 0; while (i < 100) { i++; System.out.println(“i = ” + i); } } |
| A thread with this run() method will die naturally after the loop and the run() method completes. |
| We can also kill a thread at any time by calling its stop() method. |
| The following code snippet creates and starts myThread then puts the current thread to sleep for 10 seconds. When the current thread wakes up, the bold line in the code segment kills myThread. |
| Thread myThread = new MyThreadClass(); myThread.start(); try { Thread.sleep(10000); } catch (InterruptedException e) { } myThread.stop(); |
| The stop() method throws a ThreadDeath object at the thread to kill it. Thus when a thread is killed in this manner it dies asynchronously. The thread will die when it actually receives the ThreadDeath exception. |
| IllegalThreadStateException |
| The runtime system throws an IllegalThreadStateException when we call a method on a thread and that thread’s state does not allow for that method call. |
| For example, |
| IllegalThreadStateException is thrown when we invoke suspend() on a thread that is not“Runnable”. |
| The isAlive() Method |
| A final word about thread state: the programming interface for the Thread class includes a method called isAlive(). |
| The isAlive() method returns true if the thread has been started and not stopped. |
| Thus, if the isAlive() method returns false we know that the thread is either a “New Thread” or “Dead”. |
| If the isAlive() method returns true, we know that the thread is either “Runnable” or “Not Runnable”. |
| We cannot differentiate between a “New Thread” and a “Dead” thread; nor can we differentiate between a “Runnable” thread and a “Not Runnable” thread. |
| Thread Priority |
| A thread’s priority tells the Java thread scheduler when this thread should run in relation to other threads. |
| Some points |
| 1. Most computers have only one CPU, thus threads must share the CPU with other threads. The execution of multiple threads on a single CPU, in some order, is called scheduling. The Java runtime supports a very simple, deterministic scheduling algorithm known as fixed priority scheduling. |
| 2. Each Java thread is given a numeric priority between MIN_PRIORITY and MAX_PRIORITY (constants defined in class Thread). At any given time, when multiple threads are ready to be executed, the thread with the highest priority will be chosen for execution. Only when that thread stops, or is suspended for some reason, will a lower priority thread start executing. |
| 3. Scheduling of the CPU is fully preemptive. If a thread with a higher priority than the currently executing thread needs to execute, the higher priority thread is immediately scheduled. |
| 4. The Java runtime will not preempt the currently running thread for another thread of the same priority. In other words, the Java runtime does not time-slice. However, the system implementation of threads underlying the Java Thread class may support time-slicing. Do not write code that relies on time-slicing. |
| 5. In addition, a given thread may, at any time, give up its right to execute by calling the yield() method. Threads can only yield the CPU to other threads of the same priority–attempts to yield to a lower priority thread are ignored. |
| 6. When all the “Runnable” threads in the system have the same priority, the scheduler chooses the next thread to run in a simple, non-preemptive, round-robin scheduling order. |
| Daemon Threads |
| Daemon threads are those that provide a service for other threads in the system. Any Java thread can be a daemon thread. |
Thread Group
| All threads belong to a thread group. ThreadGroup, a java.lang class, defines and implements the capabilities of a group of related threads. |
| The ThreadGroup class manages groups of threads for Java applications. A ThreadGroup can contain any number of threads. The threads in a group are generally related in some way, such as who created them, what function they perform, or when they should be started and stopped. |
| ThreadGroups can contain not only threads but also other ThreadGroups. The top most thread group in a Java application is the thread group named “main”. We can create threads and thread groups in the “main” group. We can also create threads and thread groups in subgroups of “main” and so on. |
| The result is a root-like hierarchy of threads and thread groups. |
| The ThreadGroup class has methods that can be categorized as follows: |
| 1. Collection management Method:-methods that manage the collection of threads and subgroups contained in the thread group. |
| 2. Method that Operate on the Group:-these methods set or get attributes of the ThreadGroup object. |
| 3. Method that Operate on All Threads within a Group –this is a set of methods that perform some operation, such as start or resume, on all the threads and subgroups within the ThreadGroup. |
| 4. Access Restriction Methods:-ThreadGroup and Thread allow the security manager to restrict access to threads based on group membership. |
| Collection Management Methods |
| The ThreadGroup provides a set of methods that manage the threads and subgroups within the group and allow other objects to query the ThreadGroup for information about its contents. |
| For example, |
| You can call ThreadGroup’s activeCount() method to find out the number of active threads currently in the group. The activeCount() method is often used with the enumerate() method to get an array filled with references to all the active threads in a ThreadGroup. |
| For example, |
| The listCurrentThreads() method in the following example fills an array with all of the active threads in the current thread group and prints their names: |
| class EnumerateTest { void listCurrentThreads() { ThreadGroup currentGroup = Thread.currentThread().getThreadGroup(); int numThreads; Thread[] listOfThreads; numThreads = currentGroup.activeCount(); |
Other collection management methods provided by the ThreadGroup class include activeGroupCount() and list().
Methods that Operate on the Group
| The ThreadGroup class supports several attributes that are set and retrieved from the group as a whole. These attributes include the maximum priority that any thread within the group can have, whether the group is a “daemon” group, the name of the group, and the parent of the group. |
| The methods that get and set ThreadGroup attributes operate at the group level. That is, they inspect or change the attribute on the ThreadGroup object, but do not affect any of the threads within the group. |
| The following is a list of ThreadGroup methods that operate at the group level: |
| 1. getMaxPriority(), and setMaxPriority() |
| 2. getDaemon(), and setDaemon() |
| 3. getName() |
| 4. getParent(), and parentOf() |
| 5. toString() |
| So for example, when we use setMaxPriority() to change a group’s maximum priority, we are only changing the attribute on the group object; we are not changing the priority of any of the threads within the group. |
| Consider this small program that creates a group and a thread within that group: |
| class MaxPriorityTest { public static void main(String[] args) { ThreadGroup groupNORM = new ThreadGroup( // set Thread’s priority to max (10) // set ThreadGroup’s max priority to normal (5) System.out.println(“Group’s maximum priority = ” + |
| When the ThreadGroup groupNORM is created, it inherits its maximum priority attribute from its parent thread group. In this case, the parent group priority is the maximum (MAX_PRIORITY) allowed by the Java runtime system. Next the program sets the priority of the priorityMAX thread to the maximum allowed by the Java runtime system. Then the program lowers the group’s maximum to the normal priority (NORM_PRIORITY). The setMaxPriority() method does not affect the priority of the priorityMAX thread, so that at this point, the priorityMAX thread has a priority of 10 which is greater than the maximum priority of its group groupNORM. This is the output from the program: |
| Group’s maximum priority = 5 Thread’s priority = 10 |
| As we can see a thread can have a higher priority than the maximum allowed by its group as long as the thread’s priority is set before the group’s maximum priority is lowered. A thread group’s maximum priority is used to limit a thread’s priority when the thread is first created within a group or when you use setPriority() to change the thread’s priority. Note that setMaxPriority() does change the maximum priority of all of its sub-threadgroups. |
| Methods that Operate on All Threads within a Group |
| The ThreadGroup class has three methods that allow us to modify the current state of all the threads within that group: |
| 1. resume() |
| 2. stop() |
| 3. suspend() |
| These methods apply the appropriate state change to every thread in the thread group and its subgroups. |
Access Restriction Methods
| The ThreadGroup class itself does not impose any access restrictions, such as allowing threads from one group to inspect or modify threads in a different group. Rather the Thread and ThreadGroup classes cooperate with security managers (subclasses of the java.lang.SecurityManager class), which can impose access restrictions based on thread group membership. |
| The Thread and ThreadGroup class both have a method, checkAccess(), which calls the current security manager’s checkAccess() method. The security manager decides whether to allow the access based on the group membership of the threads involved. If access is not allowed, the checkAccess() method throws a SecurityException. Otherwise, checkAccess() simply returns. |
| The following is a list of ThreadGroup methods that call ThreadGroup’s checkAccess() before performing the action of the method. These are what are known as regulated accesses, that is, accesses that must be approved by the security manager before they can be completed. |
| 1. ThreadGroup(ThreadGroup parent, String name) |
| 2. setDaemon(boolean isDaemon) |
| 3. setMaxPriority(int maxPriority) |
| 4. stop() |
| 5. suspend() |
| 6. resume() |
| 7. destroy() |
| This is a list of the methods in the Thread class that call checkAccess() before proceeding: |
| 1. constructors that specify a thread group |
| 2. stop() |
| 3. suspend() |
| 4. resume() |
| 5. setPriority(int priority) |
| 6. setName(String name) |
| 7. setDaemon(boolean isDaemon) |
| We can define and implement our own access restrictions for thread groups by subclassing SecurityManager, overriding the appropriate methods, and installing it as the current security manager in our application. |
The notifyAll() and wait() Methods
| The notifyAll() and wait() methods can be invoked only by the thread that holds the lock. |
| The notifyAll() method |
| The notifyAll() method notifies all the threads waiting on the monitor held by the current thread and wakes them up. |
| Example: |
| public synchronized int get() { while (available == false) { try { wait(); } |
| In the above example the Producer/Consumer example, the Consumer thread calls the get() method, so the Consumer thread holds the monitor during the execution of get(). At the end of the get() method, the call to notifyAll() wakes up the Producer thread that is waiting to get the monitor. Now, the Producer thread can get the monitor and proceed. |
| If multiple threads are waiting for a monitor, the Java runtime system chooses one of the waiting threads to run, making no commitments or guarantees about which thread will be chosen. |
| The wait() method |
| The wait() method causes the current thread to wait (possibly forever) until another thread notifies it of a condition change. |
| We use wait() in conjunction with notify() or notifyAll() to coordinate the activities of multiple threads using the same resources. |
| Example: |
| public synchronized int get() { while (available == false) { try { wait(); // waits for notifyAll() call from Producer } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; } |
| The Object class contains two other versions of the wait() method: |
| wait(long timeout) |
| waits for notification or until the timeout period has elapsed–timeout is measured in milliseconds. |
| wait(long timeout, int nanos) |
| waits for notification or until timeout milliseconds plus nanos nanoseconds have elapsed. |
| It has a number of methods, some of which are static. |
Frequently used Method The most frequently used methods are the following:
Exception Handling Introduction
| Errors are a normal part of programming. |
| Some of these errors are flaws in a program’s basic design or implementation–these are called bugs. |
| Other types of errors are not really bugs; rather, they are the result of situations like low memory or invalid filenames. |
| The way we handle the second type of error determines whether they become bugs. |
| Java’s exception-handling mechanism lets us handle errors without forcing us to spend most of our energy worrying about them. |
| What Is an Exception? | ||
| As the name implies, an exception is an exceptional condition. An exception is something out of the ordinary. Most often, exceptions are used as a way to report error conditions. | ||
| Exceptions provide notification of errors and a way to handle them. This control structure allows us to specify exactly where to handle specific types of errors. | ||
|
|
||
If Exceptions than? The most common means of error checking is the function’s return value.Consider the problem of calculating the retail cost of an item and displaying it. For this example, the retail cost is twice the wholesale cost: int retailCost( int wholesale )
{
if ( wholesale <= 0 )
{
return 0 ;
}
return (wholesale * 2 ) ;
} The retailCost() method takes the wholesale price of an item and doubles it. If the wholesale price is negative or zero, the function returns zero to indicate that an error has occurred.
The exception handling technique
| • Involves the use of the try, catch, and finally Java keywords |
| • Consists of several steps |
| 1. try a block of code that may result in an exception being “thrown” |
| 2. Code one or more blocks designed to automatically catch and handle a specific type of exception if one occurs. At most, only one of these blocks can be called in a single pass through the code. If none of the specified exceptions occurs, none of the blocks will be executed. |
| 3. Optionally code a block that will finally be run in ALL situations, whether an exception occurs or not |
| • Has the following general syntax: |
| try { statements that may result in an exception being thrown; } catch (exception-type1 reference) catch (exception-type2 reference) other catch blocks… finally |
| Example: |
| The following is a modified version of the “shell game” program presented earlier. It contains a try block and two catch blocks. One handles a NullPointerException and the other handles an ArrayIndexOutOfBoundsException. No finally block is specified, so logic comes together after the end of the last catch block. |
| public class AppExcep { public static void main(String[] args) { // Loop control variable. char again = ‘y’; // Main loop. One array is entered and processed in each iteration. while (again == ‘Y’ || again ==’y’) // Instantiate a three element array and load a single String String[] strings = new String[3]; // Ask the user to guess the element location. Utility.separator(50, ‘>’); // “Try” to read their response, use it to index into the array, try // If they guess the element location, display a message. Otherwise, if (strings[Keyboard.readInt() – 1].equals(“Lucky”)) // This block is automatically executed if a NullPointerException catch (NullPointerException err) // If an ArrayIndexOutOfBoundsException occurs, this block is catch (ArrayIndexOutOfBoundsException err) // Ask the user if they want to do it again and repeat the loop as Utility.separator(40, ‘=’); |
| Some Terminology | ||
| Exception handling can be viewed as a nonlocal control structure. | ||
| When a method throws an exception, its caller must determine whether it can catch the exception. | ||
| If the calling method can catch the exception, it takes over and execution continues in the caller. | ||
| Java exceptions are class objects subclassed from java.lang.Throwable. Because exceptions are class objects, they can contain both data and methods. In fact, the base class Throwable implements a method that returns a String describing the error that caused the exception. This is useful for debugging and if we want to give users a meaningful error message. | ||
|
|
||
Throw an Exception The method instantiates an object of type Exception. The Exception constructor takes a String parameter. The string contains a message that can be retrieved when the exception is caught. The throw statement terminates the method and gives its caller the opportunity to catch it: if( correct > total )
{
throw new Exception( “Invalid values” ) ;
}
if ( (float)correct / (float)total > 0.70 )
{
returnCode = true ;
}
return returnCode ;
}
Throw, try, and catch Blocks
| To respond to an exception, the call to the method that produces it must be placed within a try block. | |
| A try block is a block of code beginning with the try keyword followed by a left and right curly brace. Every try block is associated with one or more catch blocks. Here is a try block: | |
| try { // method calls go here } |
|
| If a method is to catch exceptions thrown by the methods it calls, the calls must be placed within a try block. | |
| If an exception is thrown, it is handled in a catch block. Different catch blocks handle different types of exceptions. | |
| This is a try block and a catch block set up to handle exceptions of type Exception: | |
| try { // method calls go here } catch( Exception e ) { // handle exceptons here } |
|
| When any method in the try block throws any type of exception, execution of the try block ceases. Program control passes immediately to the associated catch block. | |
| If the catch block can handle the given exception type, it takes over. | |
| If it cannot handle the exception, the exception is passed to the method’s caller. In an application, this process goes on until a catch block catches the exception or the exception reaches the main() method uncaught and causes the application to terminate. | |
| An Exceptional Example | |
| The gradeTest application. | |
| import java.io.* ; import java.lang.Exception ; public class gradeTest { public static void main( String[] args ) { try { // the second call to passingGrade throws // an excption so the third call never // gets executed System.out.println( passingGrade( 60, 80 ) ) ; System.out.println( passingGrade( 75, 0 ) ) ; System.out.println( passingGrade( 90, 100 ) ) ; } catch( Exception e ) { System.out.println( “Caught exception –” + e.getMessage() ) ; } } static boolean passingGrade( int correct, int total ) throws Exception { boolean returnCode = false ; if( correct > total ) { throw new Exception( “Invalid values” ) ; } if ( (float)correct / (float)total > 0.70 ) { returnCode = true ; } return returnCode ; } } |
|
|
|
| The second call to passingGrade() fails in this case because the method checks to see whether the number of correct responses is less than the total responses. |
When passingGrade() throws an exception, control passes to the main() method. In the example, the catch block in main() catches the exception and prints Caught exception – Invalid values.
Multiple catch Blocks
| In some cases, a method may have to catch different types of exceptions. Java supports multiple catch blocks. Each catch block must specify a different type of exception: | |
| try { // method calls go here } catch( SomeExceptionClass e ) { // handle SomeExceptionClass exceptions here } catch( SomeOtherExceptionClass e ) { // handle SomeOtherExceptionClass exceptions here } |
|
| When an exception is thrown in the try block, it is caught by the first catch block of the appropriate type. | |
| A method that ignores exceptions thrown by the method it calls. | |
| import java.io.* ; import java.lang.Exception ; public class MultiThrow { public static void main( String[] args ) { try { fool() ; } catch( Exception e ) { System.out.println( “Caught exception ” + e.getMessage() ) ; } } static void fool() throws Exception { bar() ; } static void bar() throws Exception { throw new Exception( “Who cares” ) ; } } |
|
|
|
| In the example main() calls fool() which calls bar(). Because bar() throws an exception and doesn’t catch it, fool() has the opportunity to catch it. The fool() method has no catch block, so it cannot catch the exception. In this case, the exception propagates up the call stack to fool()’s caller, main(). | |
| A method that catches and rethrows an exception. | |
| import java.io.* ; import java.lang.Exception ; public class MultiThrowA { public static void main( String[] args ) { try { fool() ; } catch( Exception e ) { System.out.println( “Caught exception ” + e.getMessage() ) ; } } static void fool() throws Exception { try { bar() ; } catch( Exception e ) { System.out.println( “Re throw exception — ” + e.getMessage() ) ; throw e ; } } static void bar() throws Exception { throw new Exception( “Who cares” ) ; } } |
|
|
|
| The fool() method calls bar(). The bar() method throws an exception and fool() catches it. In the example, fool() simply rethrows the exception, which is ultimately caught in the application’s main() method. In a real application, fool() could do some processing and then rethrow the exception. This arrangement allows both fool() and main() to handle the exception. | |
| The finally Clause | ||||||||||
|
||||||||||
|
|
||||||||||
The finally Clause
| Java introduces a new concept in exception handling: the finally clause. The finally clause sets apart a block of code that is always executed. |
| Example of a finally clause: |
| import java.io.* ; import java.lang.Exception ; public class MultiThrowFin { public static void main( String[] args ) { try { alpha() ; } catch( Exception e )} { System.out.println( “Caught exception ” ) ; } finally() { System.out.println( “Finally. ” ) ; } } } |
| In normal execution (that is, when no exceptions are thrown), the finally block is executed immediately after the try block. |
| When an exception is thrown, the finally block is executed before control passes to the caller. |
| If alpha() throws an exception, it is caught in the catch block and then the finally block is executed. |
| If alpha() does not throw an exception, the finally block is executed after the try block. If any code in a try block is executed, the finally block is executed as well. |
The Throwable Class
| All exceptions in Java are subclassed from the class Throwable. |
| If we want to create your own exception classes, we must subclass Throwable. Most Java programs do not have to subclass their own exception classes. |
| Following is the public portion of the class definition of Throwable: |
| public class Throwable { public Throwable() ; public Throwable(String message) ; public String getMessage() public String toString() ; public void printStackTrace() ; public void printStackTrace( java.io.PrintStream s) ; private native void printStackTrace0( java.io.PrintStream s); public native Throwable fillInStackTrace(); } |
| Java exceptions are Throwable objects (they are instances of Throwable or a subclass of Throwable). The Java packages contain numerous classes that derive from Throwable and thus, build a hierarchy of Throwable classes. |
| Types of Exceptions | ||||||||||
|
||||||||||
|
|
||||||||||
Different List of Exception
| java.awt Exceptions |
| The AWT classes have members that throw one error and two exceptions: |
| • AWTException (exception in AWT) |
| • llegalComponentStateException (a component is not in the proper state for a requested operation) |
| • AWTErr (error in AWT) |
| java.awt.datatransfer Exception |
| Classes of the AWT data transfer package may throw this exception: |
| • UnsupportedFlavorException (data in improper format) |
| java.beans Exceptions |
| The classes of the java.beans package throw the following exceptions: |
| • IntrospectionException (unable to resolve object during introspection) |
| • PropertyVetoException (illegal property change) |
| java.io Exceptions |
| The classes in the java.io package throw a variety of exceptions, Any classes that work with I/O are good candidates to throw recoverable exceptions. For example, activities such as opening files or writing to files are likely to fail from time to time. The classes of the java.io package do not throw errors at all. |
| The java.io exceptions. |
|
The java.io exception hierarchy. |
| java.lang Exceptions |
| The java.lang package contains much of the core Java language. The exceptions subclassed from RuntimeException do not have to be declared in a method’s throws clause. These exceptions are considered normal because nearly any method can throw them. |
| The java.lang exceptions. |
| The java.lang errors. |
|
The java.lang exception hierarchy. |
| java.lang.reflect Exception |
| The classes of java.lang.reflect throw the following exception: |
| • InvocationTargetException (invoked method has thrown an exception) |
| java.net Exceptions |
| The java.net package handles network communications. Its classes most often throw exceptions to indicate connect failures and the like. |
| The java.net exceptions. |
|
The java.net exception hierarchy. |
| java.rmi Error |
| The Java Remote Method Invocation classes allow Java objects to exist on remote machines. These classes throw the following error: |
| • ServerError (remote server indicates error) |
| java.rmi Exceptions |
| Java objects whose methods are invoked remotely through RMI may throw exceptions. |
| The java.rmi exceptions. |
The java.rmi exception hierarchy. java.rmi.server ExceptionsRMI servers throw exceptions. The java.rmi.server exceptions.
java.security ExceptionsThe Java security API allows users to implement security features in Java. The API includes support for digital signatures, data encryption, key management, and access control. The java.security exceptions.
The java.security exception hierarchy.
| java.security.acl Exceptions |
| The Java security access control list API allows Java developers to control access to specific users. The classes of java.security.acl throw the following exceptions: |
| • ACLNotFoundException (unable to find access control list) |
| • LastOwnerExcepti (attempt to delete last owner of ACL) |
| • NotOwnerExcepti (only the owner may modify) |
| java.sql Exceptions |
| The Java SQL API throws the following exceptions: |
| • DataTruncation (unexpected data truncation) |
| • SQLException (SQL error–contains detailed SQL information) |
| • SQLWarning (SQL warning) |
| java.text Exception |
| The Java text API throws the following exception: |
| • FormatException (format or parsing error) |
| java.util Exceptions |
| The classes of the java.util package throw the following exceptions: |
| • EmptyStackException (no objects on stack) |
| • MissingResourceException (resource missing) |
| • NoSuchElementException (no more objects in collection) |
| • TooManyListenersException (thrown by unicast event listeners) |
| NOTE: |
| Unicast is Java terminology for a singleton server object. Singletons are objects that can be instantiated only once. |
| java.utils.zip Exceptions |
| The Java utilities zip API throws the following exceptions: |
| • DataFormatException (format error) |
| • ZipException (Zip error) |
Built-In Exceptions
| Here application creates a method and forces it to divide by zero. The method does not have to explicitly throw an exception because the division operator throws an exception when required. | |
| An example of a built-in exception. | |
| import java.io.* ; import java.lang.Exception ; public class DivideBy0 { public static void main( String[] args ) { int a = 2 ; int b = 3 ; int c = 5 ; int d = 0 ; int e = 1 ; int f = 3 ; try { System.out.println( a+”/”+b+” = “+div( a, b ) ) ; System.out.println( c+”/”+d+” = “+div( c, d ) ) ; System.out.println( e+”/”+f+” = “+div( e, f ) ) ; } catch( Exception except ) { System.out.println( “Caught exception ” + except.getMessage() ) ; } } static int div( int a, int b ) { return (a/b) ; } } |
|
|
|
| The output of this application is shown here: | |
| 2/3 = 0 Caught exception / by zero |
|
| The first call to div() works fine. The second call fails because of the divide-by-zero error. Even though the application did not specify it, an exception was thrown–and caught. |
| Applet | ||
| Introduction | ||
| An applet is a small program that is intended not to be run on its own, but rather to be embedded inside or launched from within another application. The most common use of applets are the small programs launched from Web pages. | ||
| Applets are graphical and event driven but, for security reasons, may never access the file system of the platform on which they are run. | ||
|
|
||
How Applets and Applications Are Different
| Java applications are standalone Java programs that can be run by using just the Java interpreter, for example, from a command line. |
| Java applets are run from inside a World Wide Web browser. |
| A reference to an applet is embedded in a Web page using a special HTML tag. When a reader, using a Java-enabled browser, loads a Web page with an applet in it, the browser downloads that applet from a Web server and executes it on the local system (the one the browser is running on). |
| (The Java interpreter is built into the browser and runs the compiled Java class file from there.) |
| Because Java applets run inside a Java browser, they have access to the structure the browser provides: an existing window, an event-handling and graphics context, and the surrounding user interface. |
| A single Java program can be written to operate as both a Java application and a Java applet. While we use different procedures and rules to create applets and applications, none of those procedures or rules conflict with each other. |
| The features specific to applets are ignored when the program runs as an application, and vice versa. |
| Limitation of Applet | |||||||||
|
|||||||||
|
|
|||||||||
| The Applet class |
| • Is part of the java.applet package |
| • Is an extension of the Panel class |
| • Must be the superclass of any applet that is to be embedded in a Web page or viewed by a Java applet viewer. The Applet class provides a standard interface between applets and their environment. |
| • Is subclassed to define an applet. |
| For example, |
| public class MyApplet extends Applet |
| begins the definition of a class named MyApplet that inherits all the features of the Object, Component, Container, Panel, and Applet classes. All that remains is to supply custom features that define application processing. |
| • Has many methods. The most frequently used are: |
| Other methods exist for retrieving image files, retrieving and playing audio clips, and more. |
ajor Applet Activities
| Applets have many different activities that correspond to various major events in the life cycle of the applet-for example, | |
| 1. initialization, | |
| 2. painting, | |
| 3. and mouse events. | |
| Each activity has a corresponding method, so when an event occurs, the browser or other Java-enabled tool calls those specific methods. | |
| There are five of the most important methods in an applet’s execution: | |
| 1. initialization, | |
| 2. starting, | |
| 3. stopping, | |
| 4. destroying, | |
| 5. and painting. | |
| Initialization | |
| Initialization occurs when the applet is first loaded (or reloaded), similarly to the main() method in applications. The initialization of an applet might include reading and parsing any parameters to the applet, creating any helper objects it needs, setting up an initial state, or loading images or fonts. | |
| To provide behavior for the initialization of our applet, override the init() method in our applet class: | |
| public void init() { … } Starting |
|
| After an applet is initialized, it is started. Starting is different from initialization because it can happen many different times during an applet’s lifetime, whereas initialization happens only once. Starting can also occur if the applet was previously stopped. | |
| For example, | |
| An applet is stopped if the reader follows a link to a different page, and it is started again when the reader returns to this page. | |
| To provide startup behavior for your applet, override the start() method: | |
| public void start() { … } Stopping |
|
| Stopping | |
| Stopping occurs when the reader leaves the page that contains a currently running applet, or you can stop the applet yourself by calling stop(). By default, when the reader leaves a page, any threads the applet had s tarted will continue running. | |
| By overriding stop(), you can suspend execution of these threads and then restart them if the applet is viewed again: | |
| public void stop() { … } |
|
| Destroying | |
| Destroying enables the applet to clean up after itself just before it is freed or the browser exits-for example, to stop and remove any running threads, close any open network connections, or release any other running objects. Generally, we won’t want to override destroy() unless we have specific resources that need to be released-for example, threads that the applet has created. | |
| To provide clean-up behavior for your applet, override the destroy() method: | |
| public void destroy() { … } |
|
| Painting | |
| Painting is how an applet actually draws something on the screen, be it text, a line, a colored background, or an image. Painting can occur many thousands of times during an applet’s life . We override the paint() method if your applet needs to have an actual appearance on the screen (that is, most of the time). | |
| The paint() method looks like this: | |
| public void paint(Graphics g) { … } |
|
| paint() takes an argument, an instance of the class Graphics. This object is created and passed to paint by the browser, | |
| import java.awt.Graphics; | |
| A Simple Applet The Hello Again applet import java.awt.Graphics; import java.awt.Font; |
|
|
This applet implements the paint() method, one of the major methods described in the previous section (actually, it overrides the default implementation of paint(), which does nothing). Because the applet doesn’t actually do much (all it does is print a couple words to the screen), and there’s not really anything to initialize, you don’t need a start(), stop(), init(), or destroy() method.
The life cycle of a Web page applet
| The processing of all Web page applets is as follows: |
| 1. The applet’s init() method is automatically called when the page containing the applet is loaded by the browser or applet viewer. Its purpose is to perform applet initialization and it is called only once during the life of the applet. For a simple applet, this is the only required method. An applet does not need a main() method. If one exists, it is ignored. |
| 2. The applet’s start() method is automatically called after init() and every time the page is revisited. Its purpose is to resume suspended applet processing when the user returns to the page after surfing. |
| 3. The applet’s stop() method is automatically called when the user surfs to another page or when the browser is being shut down. Its purpose is to suspend applet processing. |
| 4. The applet’s destroy() method is automatically called after stop() when the browser or applet viewer is being shut down. Its purpose is to release all applet resources and it is called only once during the life of the applet. |
| A sample applet |
| The following statements define a small applet that displays a message when the user clicks a button. The button may then be re-clicked to clear the message: |
| import java.awt.*; import java.awt.event.*; import java.applet.*; public class Aman extends Applet implements ActionListener Button b = new Button(“Show message”); public void init() public void actionPerformed(ActionEvent e) |
| Notes: |
| 1. By importing the java.applet package, accessing the Applet class is made easier |
| 2. The applet needs no WindowListener interface because it isn’t a window |
| 3. Processing begins with the init() method. It immediately resizes the window to override any size specified by the applet’s HTML tag .Everything else about the applet is virtually the same as we would see in an equivalent windows program (with the exception of window event handling which isn’t needed). |
| 4. NOTE: The procedure for compiling a Java applet is identical to the procedure for compiling a Java program. To test the applet’s bytecode, however,we must launch the applet viewer program. This is done by entering the command: appletviewer App.php |
Including an Applet on a Web Page
| After we create a class or classes that contain our applet and compile them into class files as we would any other Java program, we have to create a Web page that will hold that applet by using the HTML language. |
| There is a special HTML tag for including applets in Web pages; Java-enabled browsers use the information contained in that tag to locate the compiled class files and execute the applet itself. |
| The <APPLET> Tag |
| To include an applet on a Web page, use the <APPLET> tag. <APPLET> is a special extension to HTML for including applets in Web pages. |
| A simple HTML page. |
| <HTML> <HEAD> <TITLE>This page has an applet on it</TITLE> </HEAD> <BODY> <P>My second Java applet says: <BR><APPLET CODE=”HelloAgainApplet.class” WIDTH=200 HEIGHT=50> Hello Again! </APPLET> </BODY> </HTML> |
| 1. The CODE attribute indicates the name of the class file that contains this applet, including the .class extension. In this case, the class file must be in the same directory as this HTML file. To indicate applets are in a specific directory, use CODEBASE, described later today. |
| 2. WIDTH and HEIGHT are required and are used to indicate the bounding box of the applet-that is, how big a box to draw for the applet on the Web page. Be sure we set WIDTH and HEIGHT to be an appropriate size for the applet; depending on the browser, if our applet draws outside the boundaries of the space you’ve given it, we may not be able to see or get to those parts of the applet outside the bounding box. |
| 3. The text between the <APPLET> and </APPLET> tags is displayed by browsers that do not understand the <APPLET> tag (which includes most browsers that are not Java aware). Because our page may be viewed in many different kinds of browsers, it is a very good idea to include some sort of alternate text or HTML tags here so that readers of your page who don’t have Java will see something other than a blank line. |
| 4. Note that the <APPLET> tag, like the <IMG> tag itself, is not a paragraph, so it should be enclosed inside a more general text tag, such as <P> or one of the heading tags (<H1>, <H2>, and so on). |
Essential HTML to launch an applet and pass it parameters
| Web pages |
| • Are really text documents, in spite of their fancy features |
| • Can be created or viewed with any text editor, such as Microsoft Word or Windows Notepad |
| • Have a file extension of either .php or .php |
| HyperText Markup Language (HTML) |
| • Enhances the capabilities of text-only documents to permit special text formatting, links to other pages, and the insertion of objects (audio files, graphic files, etc.). It also provides for the insertion and execution of Java applets. |
| • Uses special tags (codes) within the text file. The tags are acted upon by the browser when the Web page is loaded. |
| Example: |
| Displaying text in bold |
| This will be bold |
| Notes: |
| 1. The tag marks the beginning of bold text and the marks the end of bold text |
| 2. HTML tags are not case sensitive. These tags could have been coded and. |
| 3. Most text formatting tags are paired. There is a beginning tag and ending tag. |
| 4. Other HTML tags exist to specify text size, italicizing, centering, the start of a new paragraph, etc. |
| Example: |
| Inserting a graphic image |
| <<IMG SRC=myPhoto.jpg WIDTH=100 HEIGHT=150>> |
| Notes: |
| 1. This tag has attributes (parameters) that specify the file name as well as the image width and height in pixels |
| 2. Unlike HTML tags and attributes, file names are case sensitive. Proper capitalization must be maintained. |
| 3. The image will appear at the location of the tag within the document |
| 4. Tags that insert image objects and audio clips are not paired |
| • Is simplified by the use of various software products. In fact, a detailed understanding of HTML is no longer required to create sophisticated Web pages. |
The only HTML you are required to learn in this course involves launching a Java applet. While some packages help generate the tags, it is sometimes necessary to code or edit the tags manually.
Launching an applet in an HTML document
| • Requires a pair of tags. The first tag must have attributes that identify the class name of the applet and its size in pixels. The second tag marks the end of the pair. |
| Example: |
| Launching a simple applet |
| Notes: |
| 1. In order to launch the applet, the browser must be Java enabled. Otherwise, the tags are ignored. |
| 2. The attributes can be coded in any order |
| 3. The CODE= attribute specifies the name of the applet’s .class file (the bytecode file generated by the Java compiler). If no path is specified, the file is assumed to exist in the same server directory as the web page. This attribute may optionally be coded within quotes. For example, CODE=”MyApplet.class” |
| 4. The initial pixel width and height of the screen area used by the applet are specified by the WIDTH= and HEIGHT= attributes. A call to the resize() method within the applet class can modify this size. A maximum size of 600 x 400 is recommended for proper display regardless of the graphics resolution. |
| 5. There are many other attributes for an applet. |
| Notes: |
| 1. The tag is required for each parameter that is passed to an applet. |
| 2. The NAME= attribute specifies the case-sensitive identifier of the parameter. The VALUE= attribute specifies a case-sensitive string value associated with the parameter. It must be coded in quotes if it contains any spaces. For example, a tag to pass a message to an applet might contain the attribute VALUE=”Hello world!” |
| 3. To retrieve the parameter’s value from the browser, the following expression must be coded within the applet: |
| getParameter(“taxRate”) |
| In this example, the value received from the browser would be a String object having the value “.06” |
| 4. There is no restriction on the number of parameters. Simply code a PARAM tag for each one and place them between the and tags. |
A sample applet that receives a parameter
| This applet is a very slightly modified version of the applet from the previous lesson. The message it displays when the user clicks the button is received as a parameter from the HTML within the Web page. |
| To test the applet, a tag such as <applet> must exist in the App.php source file between the …> and tags. To verify that the tag exists, or to add it if it doesn’t, use any text editor (such as Notepad ). |
| The applet’s code is as follows: |
| import java.awt.*; import java.awt.event.*; import java.applet.*; public class App extends Applet implements ActionListener Button b = new Button(“Show message”); public void init() public void actionPerformed(ActionEvent e) |
| Posting a Web page that launches a custom applet | ||
| All we must do is upload the .php file of the Web page and the .class file of the applet to your Web server. The rest is automatic! | ||
|
|
||
Managing Input/Output Files in Java Introduction Nearly all programs require the ability to transfer data in and out of memory.For example, data may be stored on disk or sent over a network. The package java.io, part of the standard Java class library, provides a large number of classes designed for handling input and output to files, network connections, and other sources. These I/O classes are known as streams, and provide functionality for reading and writing data in various ways. Java’s input and output classes:• Input streams-and how to create, use, and detect the end of them-and filtered input streams, which can be nested to great effect. • Output streams, which are mostly analogous to (but the inverse of) input streams.
Streams
| A stream is a path of communication between the source of some information and its destination. This information can come from a file, the computer’s memory, or even from the Internet. |
| A stream is a path of communication between a source of information and its destination. |
| For example, |
| An input stream allows us to read data from a source, and an output stream allows us to write data to a destination. |
| The java.io Package |
| To import each individual class or to import the entire java.io package, like this: |
| import java.io.InputStream; import java.io.FilteredInputStream; import java.io.FileOutputStream; import java.io.*; |
The foundations of this stream framework in the Java class hierarchy are the two abstract classes, InputStream and OutputStream.Inheriting from these classes is a virtual cornucopia of categorized subclasses, demonstrating the wide range of streams in the system, but also demonstrating an extremely well-designed hierarchy of relationships between these streams-one well worth learning from.
| Input Streams | ||
| Input streams are streams that allow us to read data from a source. These include the root abstract class InputStream, filtered streams, buffered streams, and streams that read from files, strings, and byte arrays. | ||
|
|
||
he Abstract Class InputStream
| InputStream is an abstract class that defines the fundamental ways in which a destination (consumer) reads a stream of bytes from some source. |
| read() |
| The most important method to the consumer of an input stream is the one that reads bytes from the source. |
| Here’s the first form of read(): |
| InputStream s = getAnInputStreamFromSomewhere(); byte[] buffer = new byte[1024]; // any size will do if (s.read(buffer) != buffer.length) |
| This form of read() attempts to fill the entire buffer given. If it cannot (usually due to reaching the end of the input stream), it returns the actual number of bytes that were read into the buffer. After that, any further calls to read() return -1, indicating that you are at the end of the stream. Note that the if statement still works even in this case, because -1 != 1024 (this corresponds to an input stream with no bytes in it at all). |
| skip() |
| What if you want to skip over some of the bytes in a stream, or start reading a stream from other than its beginning? A method similar to read() does the trick: |
| if (s.skip(1024) != 1024) System.out.println(“I skipped less than I expected.”); |
| This example skips over the next 1024 bytes in the input stream. However, the implementation of skip() in InputStream may skip fewer bytes than the given argument, and so it returns a long integer representing the number of bytes it actually skipped. In this example, therefore, a message is printed if the actual number of bytes skipped is less than 1024. |
| available() |
| If for some reason we would like to know how many bytes are in the stream right now, we can ask the following: |
| if (s.available() < 1024) System.out.println(“Too little is available right now.”); |
| This tells us the number of bytes that we can read without blocking. |
| mark() and reset() InputStream s = getAnInputStreamFromSomewhere(); if (s.markSupported()) { // does s support the notion? |
| When marking a stream, we specify the maximum number of bytes you intend to allow to pass before resetting it. This allows the stream to limit the size of its byte “memory.” If this number of bytes goes by and you have not yet used reset(), the mark becomes invalid, and attempting to use reset() will throw an exception. |
| Marking and resetting a stream is most valuable when you are attempting to identify the type of the stream (or the next part of the stream), but to do so, you must consume a significant piece of it in the process. Often, this is because you have several black-box parsers that you can hand the stream to, but they will consume some (unknown to you) number of bytes before making up their mind about whether the stream is of their type. Set a large size for the limit in mark(), and let each parser run until it either throws an error or completes a successful parse. If an error is thrown, use reset() and try the next parser. |
| close() InputStream s = alwaysMakesANewInputStream(); try { |
| Get used to this idiom (using finally); it’s a useful way to be sure something (such as closing the stream) always gets done. |
| Java provides many classes that make “I/O” (input and output) relatively easy and platform independent. In this lesson, we will learn how to act upon the file structure of a platform from inside a Java application. Note that Java applets are NOT permitted to access a platform’s file structure for security reasons. |
The File class
| • Is part of the java.io package. You will need an import statement to access the class with its abbreviated name. |
| • Is an extension of the Object class |
| • Encapsulates platform-independent information about a file or a directory. |
| While all platforms use pathname strings to name files and directories, they do not agree on the format of these strings. For example, the Windows pathname string is not the same as the Unix pathname string. |
| Regardless of platform, however, all pathnames have two components: |
| 1. An optional system-dependent prefix string (such as the disk-drive specifier followed by “/” for the Unix root directory or “” for the Windows root directory) |
| 2. A sequence of zero or more string names where each name, except for the last, denotes a directory. The the last name may denote either a directory or a file. A system-dependent separator (“/” for Unix or “” for Windows) is used between each name. |
| For example, |
| The following represents a valid Windows pathname: |
| C:My DocumentsNew CoursesLesson55.php |
| Regardless of the platform, the File class presents a system-independent view of pathnames. |
| • Has a number of static fields. These two are the most useful: |
For example,The following program can determine if it is running under Windows:import java.io.*;
public class AppFile
{
public static void main(String[] args)
{
if (File.separator.equals(“”))
System.out.println(“Windows”);
else
System.out.println(“Not Windows”);
}
}
| Output |
• Has several constructors. The most frequently used constructs a File object from a pathname string as shown by the following statement:File f = new File(“C:My DocumentsMiscResume.doc”);
| NOTE: |
| Constructing a File object does NOT create a disk file. It only constructs a platform-independent object for referencing the file. |
| • Has a number of methods, some of which WILL create, rename, and delete a disk file or a directory. They should obviously be used with caution. The most frequently used methods are: |
|
Consult the Java API documentation for more details. |
| The FileDialog class | |||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||
| Low-level and high-level stream classes | |||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||
| There are many stream classes, but you will only be required to know the ones that are highlighted below: | |||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||
| The FileOutputStream class | |||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||
| The FileInputStream class | |||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||
The DataOutputStream class
| • Is part of the java.io package |
| • Is an extension of the FilterOutputStream class (a superclass that facilitates the chaining of high-level and low-level output streams) |
| • Is a high-level class that can be used to send primitive values and UTF (“Unicode Transformation Format”) strings to a stream |
| • Has a single constructor that “chains” to an object that descends from the OutputStream class (such as a FileOutputStream object). For example, if fd is the reference of a File object |
| DataOutputStream out = new DataOutputStream(new FileOutputStream(fd)); |
| It will construct a DataOutputStream object chained to a FileOutputStream object for sending primitive values and UTF strings to the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch. |
| • Has many useful methods as follows: |
| Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details. |
| • Example. The following program can be used to create a file of double values on disk. |
| import java.io.*; public class App { public static void main(String[] args) { // Local variables and object references. char again = ‘y’; // Get the path name from the user. System.out.print(“Enter the file’s complete path name: “); // Try to write data to the output stream. try // Open an output stream for the file. out = new DataOutputStream(new FileOutputStream(fd)); // This loop asks the user to enter a number and writes it to the while (again == ‘Y’ || again == ‘y’) { // Close the stream. out.close(); // Catch an IOException if one is thrown. catch (IOException e) |
| The DataOutputStream class | ||||||||||||||||||||||||||
|
||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| The DataInputStream class | ||||||||||||||||||||||||||
| • Is part of the java.io package | ||||||||||||||||||||||||||
| • Is an extension of the FilterInputStream class (a superclass that facilitates the chaining of high-level and low-level input streams) | ||||||||||||||||||||||||||
| • Is a high-level class that can be used to read primitive values and UTF (“Unicode Transformation Format”) strings from a stream | ||||||||||||||||||||||||||
| • Has a single constructor that “chains” to an object that descends from the InputStream class (such as a FileInputStream object). For example, if fd is the reference of a File object | ||||||||||||||||||||||||||
| DataInputStream in = new DataInputStream(new FileInputStream(fd)); | ||||||||||||||||||||||||||
| It will construct a DataInputStream object chained to a FileInputStream object for reading primitive values and UTF strings from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch. | ||||||||||||||||||||||||||
| • Has many useful methods as follows: | ||||||||||||||||||||||||||
| Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details. | ||||||||||||||||||||||||||
| • Example. The following program can be used to read a file of double values from disk. It can be used to display the values stored by the previous sample program. | ||||||||||||||||||||||||||
| import java.io.*; public class App { public static void main(String[] args) { // Local variables and object references. File fd; // Get the path name from the user. System.out.print(“Enter the file’s complete path name: “); // Try to read data from the input stream. try { // Open an input stream for the file. in = new DataInputStream(new FileInputStream(fd)); // This loop reads a double value from the stream and displays try // Close the stream. in.close(); // Catch an IOException if one is thrown. catch (IOException e) |
||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| The ObjectOutputStream class | ||||||||||||||||||||||||||
|
||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
he ObjectInputStream class
| • Is part of the java.io package |
| • Is an extension of the InputStream class, an abstract class that describes the behavior of an input stream |
| • Is a high-level class that can be used to read primitive values and serializable objects from a stream |
| • Has overloaded constructors but the most useful “chains” to an object that descends from the InputStream class (such as a FileInputStream object). For example, if fd is the reference of a File object |
| ObjectInputStream out = new ObjectInputStream(new FileInputStream(fd)); |
| will construct a ObjectInputStream object chained to a FileInputStream object for reading primitive values and serializable objects from the file. Because a checked, IOException may occur, the statement should be enclosed in a try block with an appropriate catch. |
| • Has many useful methods as follows: |
| Because a checked, IOException may occur, calls to these methods should be enclosed in a try block with an appropriate catch. Consult the Java API documentation for more details. |
• Example. The following program can be used to read a file of array objects from disk. It can be used to display the array values stored by the previous sample program. import java.io.*;
public class App
{
public static void main(String[] args)
{
// Local variables and object references.
File fd;
ObjectInputStream in;
// Get the path name from the user.
System.out.print(“Enter the file’s complete path name: “);
fd = new File(Keyboard.readString());
// Try to read data from the input stream.
try
{
// Open an input stream for the file.
in = new ObjectInputStream(new FileInputStream(fd));
// This loop reads a array objects from the stream and displays
// their contents. The loop ends when end of file is reached.
try
{
while (true)
{
String[] array = (String[]) in.readObject();
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
System.out.println(“<< END OF ARRAY >>”);
}
}
catch (EOFException e) {
System.out.println(“<< END OF FILE >>”);
}
// Close the stream.
in.close();
System.out.println(“Closed – ” + fd.getPath());
}
// Catch an IOException if one is thrown.
catch (IOException e) {
System.out.println(e.getMessage());
}
// Catch an ClassNotFoundException if one is thrown.
catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
