![]() |
![]() | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]()
|
Introduction and Overview Java, developed by Sun Microsystems, is an object-oriented programming (OOP) language based on C. Many years in development, it has shown an explosive growth in popularity since its formal release in 1995. This is due, in part, to the relative simplicity of the language when compared to C and other high-level languages, particularly languages such as C++. It is also due to the design and implementation of Java which allows compiled programs to be shipped across the Internet to run on a wide variety client systems. Java is not just for web sites. Java is a programming language that lets you do almost anything you can do with a traditional programming langauge like Fortran, C or C++. However, Java has benefited from the experiences of its predecessors. It is considerably cleaner and easier to use than previous high-level languages. The major characteristics of the Java programming language include the following:
Learning ObjectivesThe purpose of this lesson is to introduce you to the basic structure and syntax of Java programs. At the end of this lesson, you should be able to:
History and Language StandardsJava began its existance under a different name and for a different application area than that for which it is now recognized. The original 'Oak' programming language was written to facilitate software development for consumer electronics devices, such as toasters, microwave ovens, and Personal Digital Assistants (PDAs).In the early 1990s, the introduction of embedded microprocessors to consummer devices (e.g., TVs and VCRs) was seen by many people as a significant point in the development of consummer electronics. To address the issues related to effectively programming and porting these embedded microprocessors, Sun Microsystems funded in 1991 an internal research project code-named "Green." The small "Green" team, headed by James Gosling, quickly realized that languages like C and C++ were not well suited to the range of tasks "consumer devices" needed to perform. One problem anticipated by the "Green" team was the difficulty in providing software for new devices ... every time a new embedded microprocessor was introduced to the marketplace and incorporated into an existing device, programmers would have to recompile programs written in C or C++ for this device. The complexity of C and C++ meant that it would be extremely difficult to write reliable software. As a result, in mid 1991, James Gosling started working on a new language more appropriate for those specific tasks. He named the language 'Oak' after an oak tree outside his window at Sun. Gosling designed this new language to be small, reliable and architecture-independent. The development team was soon incorporated in a new company FirstPerson. Unfortunately, FirstPerson ran into a lot of difficulties mainly because the marketplace for intelligent consumer electronic devices was not developing as Sun had anticipated. It was the release of NCSA Mosaic and the explosion of the World Wide Web in 1993 which saved the project. The developers of Oak realized that an architecture-neutral language would be ideal for programming on the Internet because a program could run anywhere, and on many different types of computers connected to the Internet. The developers made minor changes to the design and changed the name 'Oak' to 'Java'. The World Wide Web took the Internet by storm, and Java would take the World Wide Web by storm also. Having develop Java for consumer electronics products result in a robust language. When the Java team decided that Java would be particulary well suited for the Internet because of its platform independance, they added a lot functionalities to the language for handling network tasks. That's how Java became the new language of choice to develop network or client/server applications. Sun formally announced Java at the SunWorld conference in May 1995. Java generated immediate interest in the business community because it was neither an academic language like Pascal, nor a language designed by one person (or a small group) for their own local use like C or C++. Java was designed instead for commercial reasons. Enormous interest in Java was generated in the business community because of another Internet related development, the World Wide Web. Current StandardsIn April 1999, Sun Microsystems, Inc. proposed to formally standardize the Java technology in ECMA (formerly known as the European Computer Manufacturers Association), an internationally recognized standards developing body with strong ties to ISO/IEC JTC-1.ECMA is an open, consensus-based forum for the development of standards in information technology, telecommunications and consumer electronics. Since its formation in 1961, ECMA has published about 250 ECMA standards and 75 technical reports of high quality. ECMA is a Class A ISO liaison, and this unique relationship allows ECMA standards to be forwarded to ISO for adoption as international standards. ISO has adopted over 100 ECMA standards using this path. The formal standardization of Java technology in ECMA is an excellent choice given that many of the major Java-technology stakeholders are ECMA members and ECMA offers a proven path to ISO/IEC JTC-1. The ISO/IEC JTC 1 Secretariat is administered by the American National Standards Institute located at 11 West 42nd Street, New York, NY, 10036. Sun has submitted to ECMA the Java 2 Standard Edition (J2SE), Version 1.2.2. This specification, which is being widely adopted and used by the international Java community, consists of:
Why Study Java?Why is the Java technology so popular? The primary reason is that it is closely tied to use over computer networks, especially the Internet.With Java technology, the Internet and private networks become your computing environment. Coupled with the power of networking, the Java platform is helping computer users to do things that were previously unimaginable. For example, users can securely access their personal information and applications when they are far away from the office by using any computer that is connected to the Internet; soon they will be able to access tailored applications from a mobile phone based on the Java platform, or even use smart cards as a pass key to everything from the cash machine to ski lifts. Why Java technology? Networks require software that is portable, modular, and secure ... all areas where Java technology shines, because it was designed for use on networks from the beginning. Java BasicsJava Virtual MachineThe Java Virtual Machine (JVM) is at the heart of the Java programming language. It is because of the Java Virtual Machine that Java is architecture neutral, dynamic, interpreted and compiled, network ready and compatible, portable, robust, and secure. The JVM makes these features possible by providing an abstract specification for which developers can design interpreters and programmers can design applications. This abstract specification is a virtual machine that exists only in nanospace. Because the Java Virtual Machine exists only in memory, the Java developers were able to use object-oriented methodology to pass information-parameters, method calls, and other types of data-back and forth between the real machine and the virtual machine. After the developers mapped out the necessary interaction between the real machine and the virtual machine for things like standard I/O, file I/O, and memory management, they could create additional Java runtime environments for other systems. Because the specification for the Java Virtual Machine is fully described for all to use and thus open for development, the Java programming language is free from the restrictions of proprietary languages. This means that any developer can create an interpreter for the Java Virtual Machine. Applications & Applets What is the difference between an application and an applet? This question can be answered on many levels. Technically an application is a Java class that has a main() method. An applet is a Java class which extends java.applet.Applet. A class which extends java.applet.Applet and also has a main() method is both an application and an applet. More generally and less technically an application is a stand-alone program, normally launched from the command line, and which has more or less unrestricted access to the host system. An applet is a program which is run in the context of an applet viewer or web browser, and which has strictly limited access to the host system. For instance an applet can normally not read or write files on the host system whereas an application normally can. The actions of both applets and applications, however, can be controlled by SecurityManager objects. If you can change the SecurityManager that's used you can change what an applet or an application is and is not allowed to do. Thus these are not hard and fast differences, though this is normally how they separate out in practice. Java-Related Definitions A few of the more important Java-related definitions are included below. Additional definitions can be found in the special Java Glossary, created to help you understand the many technical terms associated with the Java language, object-oriented programming, and the World Wide Web.
Java Hello World Program The following program illustrates the traditional Hello World program, written in Java.
public class HelloWorld
{
public static void main (String args[])
{
System.out.println("Hello World\n");
}
}
This program is deceptively simple looking. Aside from the object notation
used to specify the output, it should be nearly self explanatory. Until you
become familiar with the common Java objects and their associated calls,
practical Java programs will appear significantly more complex than this
HelloWorld.java program.
Program OrganizationThe Circle.java program which follows demonstrates a Java program that finds the area of a circle (using a fixed input for the radius) and outputs the calculated value.
// A program to find the area of
// a circle.
import java.io.*;
class Circle
{
public static void main(String argv[])
{
double r = 2.0;
double pi = 3.14159;
double area = 0;
area = pi * r * r;
System.out.println("area: "+ area);
}
}
Compile and run this program several times, using different values for
r, the radius. Modify the program to calculate the circumference
and the area. Don't forget to output both values.
The Echo.java program shown below illustrates simple command line input. It "echos" whatever characters you include on the same line as the name of the Echo.class when you run the compiled program.
/**
This program prints out all
its command-line arguments.
*/
public class Echo
{
public static void main(String[] args)
{
int i = 0;
while(i < args.length)
{
System.out.print(args[i] + " ");
i++;
}
System.out.println();
}
}
The program below, CircleThree.java, calculates the area
of a circle after receiving the value of the radius from the user.
import java.io.*;
import java.util.*;
public class CircleThree
{
public static void main(String f[])
{
double pi = 3.14159;
double area = 0.0;
InputStreamReader is =
new InputStreamReader( System.in );
BufferedReader br = new BufferedReader( is );
StringTokenizer st;
try
{
System.out.print("radius: ");
String s = br.readLine();
st = new StringTokenizer(s);
double r =
new Double(st.nextToken()).doubleValue();
area = pi * r * r;
System.out.println("area: " + area);
}
catch (IOException ioe)
{
System.out.println("IO error:" + ioe);
}
}
}
CommentsJava supports three types of comment delimiters:
/* This is a Java comment. */
/**
This is a Javadoc comment.
It is modeled after C.
*/
/***************************
* This is a Java comment. *
* It is modeled after C. *
***************************/
/* This is another Java comment.
It too is modeled after C. */
// This is a Java comment.
// It is modeled after C++.
Single-line comments are commonly used to document variables or short
sections of code. The text follows the two forward slashes and the
comment terminates at the end of the line. Multi-line comments span
multiple lines. This is typically applied to program or class method
documentation. Documentation comments are used to later generate HTML
descriptions of class and method declarations in a Java program.
The Javadoc tool is supplied with the JDK for this purpose.
Javadoc comments that begin with a /** are special. These comments should only be used before a method or class declaration. They indicate that the comment should be included in automatically generated documentation for that declaration. White Space & IndentationComments and whitespaces are removed by the Java compiler during the tokenization of the source code. Whitespace consists of spaces, tabs, and linefeeds. All occurrences of spaces, tabs, and linefeeds are removed by the Java compiler, as are comments.Since the Java compiler removes whitespace characters, they can be used to inprove the readability of your source code. The indentation style of Java examples on this page reflect the preferences of your instructor, and are not completely consistent with the standard. Variables and IdentifiersThe Java language specification details exactly which characters can and cannot be used to create identifiers (such as variable names, method names, and so on). The basic rules for identifiers are
Except for comments, identifiers, and the contents of character and string literals, all input elements in a program written in the Java programming language are formed from only ASCII characters. ASCII (ANSI X3.4) is the American Standard Code for Information Interchange. The first 128 characters of the Unicode character encoding are the ASCII characters. Unicode & Identifiers. An identifier is an unlimited-length sequence of Unicode letters and digits, the first of which must be a letter. Letters and digits may be drawn from the entire Unicode character set, which supports most writing scripts in use in the world today. This allows programmers to use identifiers in their programs that are written in their native languages. The method Character.isJavaLetter returns true when passed a Unicode character that is considered to be a letter in an identifier. The method Character.isJavaLetterOrDigit returns true when passed a Unicode character that is considered to be a letter or digit in an identifier. Two identifiers are the same only if they have the same Unicode character for each letter or digit; identifiers that have the same external appearance may still be different. An identifier must not be the same as a boolean literal, the null literal, or a keyword in the Java programming language. Special CharactersThe table below lists the special characters which are supported by Java.
KeywordsThe Java language specification lists a group of keywords that can be used only for their intended purpose as listed in the specification.
Java Reserved Keywords As with other languages, Java's keywords cannot be used as identifiers. DeclarationsA declaration introduces an entity into a Java program and includes an identifier that can be used in a name to refer to this entity. A declared entity is one of the following:
Here are some examples of simple declarations: byte j = 60; // set the byte j's value to 60 short k = 24; int l = 30; long m = 12L; long result = 0L; Data TypesJava's primitive data types are very similar to those of C. (The boolean type has been added.) However the implementation of the data types has been substantially cleaned up in several ways.
boolean. 1-bit. May take on the values true and false only. true and false are defined constants of the language and are not the same as True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value. Booleans may not be cast into any other type of variable nor may any other variable be cast into a boolean. true //boolean literal FALSE //boolean literal boolean delivered = false; delivered = true;byte 1 signed byte (two's complement). Covers values from -128 to 127. There are no byte literals. You can use int literals as long as they fit in to 8-bits. You can also use char, long, and floating-point literals if you cast them. byte B1=1, B2=2; byte B3 = (byte) (B1 + B2);The cast is needed because the integer arithmetic is done using more than 8-bit operands, potentially yielding a result larger than 8-bits (which cannot be true for type byte). short. 2 bytes signed (two's complement), -32,768 to 32,767 There are no short literals. You can use, without a cast, int literals as long as they fit in to 16-bits. You can also use char, long, and floating-point literals if you cast them. As with byte, assignments to short must always be cast into the result if the right hand side of the assignment involves any arithmetic. int. 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647. Like all numeric types ints may be cast into other numeric types (byte, short, long, float, double). When lossy casts are done (e.g., int to byte) the conversion is done modulo the length of the smaller type. 10 //decimal literal -256 //decimal literal 07777 //octal literal 0xA5 //hexadecimal literal 0Xa5 //hexadecimal literallong. 8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807. 1047L //decimal literal -207L //decimal literal 07657L //octal literal 0xA5L //hexadecimal literal 0x5CFE12A678BL //hexadecimal literalfloat. 4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Like all numeric types floats may be cast into other numeric types (byte, short, long, int, double). When lossy casts to integer types are done (e.g., float to short) the fractional part is truncated and the conversion is done modulo the length of the smaller type. 1e1f 2.f .3f 3.14f 6.02e+22fdouble. 8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). Valid formats for double literals include a decimal point, an exponent, or both. A suffix of "d" also is used to indicate a double literal. 1e1 2. .3 3.14 6.02e+22dchar. 2 unsigned bytes, Unicode. Unicode can represent up to 34,168 characters. This is beneficial for programmers in non-English speaking countries (programs can be written using their native language). It is also useful for developing cross-cultural applications. Chars are not the same as bytes, ints, shorts or Strings. 'A' //a single character '\n' //a character escape sequence
Type Compatibility & CastingInevitably, there will be times when you have to convert from one data type to another. The process of converting one data type to another is called casting. Casting is often necessary when a function returns a type different than the type you need to perform an operation. For example, the read() member function of the standard input stream (System.in) returns an int. You must cast the returned int type to a char type before storing it, as in the following:char c = (char)System.in.read();The cast is performed by placing the desired type in parentheses to the left of the value to be converted. The System.in.read() function call returns an int value, which then is cast to a char value because of the (char) cast. The resulting char value is then stored in the char variable c. The storage size of the types you are attempting to cast is very important. Not all types can be safely cast to other types. To understand this, consider the outcome of casting a long to an int. A long is a 64-bit value and an int is a 32-bit value. When casting a long to an int, the compiler chops off the upper 32 bits of the long value so that it will fit into the 32-bit int. If the upper 32 bits of the long contain any useful information, that information is lost and the number changes as a result of the cast. Information loss can also occur when you cast between different fundamental types, such as between integer and floating-point numbers. For example, casting a double to a long results in the loss of the fractional information, even though both numbers are 64-bit values. When casting, the destination type should always be equal to or larger in size than the source type. Furthermore, you should pay close attention to casting across fundamental types, such as from floating-point to integer types. float f = 3.155; int i = (int) f; //a castWhat is the value of i in the example cast shown above? If you don't know the answer, write a simple program that will give you the information you need. The table bellow lists the casts that result in no loss of information.
Assignment Operators & StatementsAssignment operators in Java are a notational shortcut. They are a combination of an assignment and an operation where the same variable is the left operand and the place to store the result. For example, the following two expressions are equivalent:i = i + 3; i += 3;In both cases, the value of the identifier i gets increased by 3. Assignment operators are a carryover from C to Java. They were originally intended to help compiler writers generate effecient code by leaving off the repetition of one operand. This allowed for efficient reuse of a quantity already in the computer's register. The various Java assignment operators are listed in the following table:
byte j = 60; // set j's value to 60
short k = 24;
int l = 30;
long m = 12L;
long result = 0L;
result += j; /* result gets 60:
(0 plus 60) */
result += k; /* result gets 84:
(60 plus 24) */
result /= m; /* result gets 7:
(84 divided by 12) */
result -= l; /* result gets -23:
(7 minus 30)) */
result = -result; /* result gets 23:
(-(-23)) */
result %= m; /* result gets 11:
(remainder 23 div by 12) */
Constants/LiteralsProgrammers often use something called symbolic constants, which are simply words that represent values in a program. In the case of your sales tax program, you could choose a word like SALESTAX (no spaces) to represent the current sales tax percentage for your state. Then, at the beginning of your program, you set SALESTAX to be equal to the current state sales tax. In the Java language, such a line of program code might look like this:final float SALESTAX = 0.06; final int TOTALSPACES = 100;In the preceding line, the word final tells Java that this data object is going to be a constant. The word float is the data type, which, in this case, is a floating point. ExpressionsOnce you create variables, you typically want to do something with them. Operators enable you 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. More formally, 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 (constant), and = and / are operators. This expression states that the y variable is divided by 3 using the division operator (/), and the result is stored in x using the assignment operator (=). Notice that the expression was described from right to left. Although this approach of analyzing the expression from right to left is useful in terms of showing the assignment operation, most Java expressions are, in fact, evaluated from left to right. BooleanBoolean operators act on boolean types and return a boolean result. The table below illustrates the Java Boolean operators.
boolean result = isValid & (Count > 10); boolean result = isValid && (Count > 10);The first expression uses the evaluation AND operator (&) to make an assignment. In this case, both sides of the expression are always evaluated, regardless of the values of the variables involved. In the second example, the logical AND operator (&&) is used. This time, the isValid boolean value is first checked. If it is false, the right side of the expression is ignored and the assignment is made. This operator is more efficient because a false value on the left side of the expression provides enough information to determine the false outcome. Although the logical operators are more efficient than the evaluation operators, there still may be times when you want to use the evaluation operators to ensure that the entire expression is evaluated. 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);
}
In this example, the second expression (++y < 15) is evaluated after
the last pass through the loop because of the evaluation AND operator.
If the logical AND operator had been used, the second expression would
not have been evaluated and y would not have been incremented after
the last time around.
The three boolean operators--negation, equal-to, and not-equal-to (!, ==, and !=)--perform exactly as you might expect. 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 and is worth a closer look. 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 : Expression2The 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. OOP DefinitionsThe following definitions relate to object-oriented programming. These definitions are given in general form, but apply to Java.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| |
| Added to the Web: October 27, 1999. Last updated: October 31, 1999. Web page design by Dan Solarek. |
![]() http://cset.sp.utoledo.edu/cset4250/ |