Please send all questions & assignments to:
dsolarek@eng.utoledo.edu

 

Java
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:

  • Simple: Java has the bare bones functionality needed to implement its rich feature set. It does not add lots of syntactic sugar or unnecessary features.
  • Object-Oriented: Almost everything in Java is either a class, a method or an object. Only the most basic primitive operations and data types (int, for, while, etc.) are at a sub-object level.
  • Platform Independent: Java programs are compiled to a byte code format that can be read and run by interpreters on many platforms including Windows 95, Windows NT, and Solaris 2.3 and later.
  • Safe: Java code can be executed in an environment that prohibits it from introducing viruses, deleting or modifying files, or otherwise performing data destroying and computer crashing operations.
  • High Performance: Java can be compiled on the fly with a Just-In-Time compiler (JIT) to code that rivals C++ in speed.
  • Multi-Threaded: Java is inherently multi-threaded. A single Java program can have many different things processing independently and continuously.

Learning Objectives

The 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:
  • identify the differences between Java and JavaScript
  • describe the Java Virtual Machine
  • explain the differences between running Java server-side and client-side
  • explain the similarities and differences between Java, JDK, and J++
  • describe the proper syntax for Java declarations, statements, variable names, expressions, and comments
  • explain Unicode and its relationship to Java
  • create simple server-side Java programs
  • compile Java programs using the JDK javac utility
  • debug common errors in Java programs

History and Language Standards

Java 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 Standards

In 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:

  • the Java Language specification
  • the Java Virtual MachineTMSpecification, and
  • the Java API Core Class LibraryTM Specifications.

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 Basics

Java Virtual Machine

The 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.

Applet
An applet is a very small program written in the Java programming Language that can only be used as part of a Web Page (client-side). The Browser you are using must be capable of running Java Applets. They are used to bring a Web page to Life.
Application
A computer program, written in Java, that executes independently of a Java-enabled browser. Applications normally run on the server and use the Java interpreter included in provided as part of the Java Development Kit (JDK).
HotJava
A Web browser designed by Sun Microsystems to execute applets written in the Java programming language. Sun's HotJava was the first Web browser that supported Java applets and it is also a Web browser written entirely in Java. While HotJava was indeed the first browser to offer Java support, browsers like Netscape, Internet Explorer, and Oracle PowerBrowser have added their own built-in Java capabilities.
Java Foundation Classes
The Java Foundation Classes (JFC) are a comprehensive set of GUI components and services which dramatically simplify the development and deployment of commercial-quality desktop and Internet/Intranet applications.
JavaBeans
JavaBeans is a portable, platform-independent component model written in the Java programming language. JavaBeans components, or Beans, are reusable software components that can be manipulated visually in a builder tool. Beans can be combined to create traditional applications, or their smaller web-oriented brethren, applets. In addition, applets can be designed to work as reusable Beans.
Javadoc
Javadoc is the tool for generating API documentation in HTML format from doc comments in source code.

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 Organization

The 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);
    }
  }
 }

Comments

Java supports three types of comment delimiters:
  • the traditional /* and */ of C
  • the // of C++
  • a new variant that starts with /** and ends with */
A variety of comments are illustrated below:
 /* 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 & Indentation

Comments 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 Identifiers

The 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
  • Identifiers must start with a letter, underscore, or dollar sign.
  • Any letter other than the first letter can be a digit.
  • The identifier must not be one of the Java keywords.
Unicode. Programs written in the Java programming language supported by JDK release 1.1.7 and the Java 2 platform, v1.2 use the Unicode character encoding, version 2.1, as specified in The Unicode Standard, Version 2.0, ISBN 0-201-48345-9, and the update information for Version 2.1 of the Unicode Standard. Programs written in the Java programming language used version 2.0.14 of the Unicode Standard in JDK releases 1.1 through 1.1.6 and used version 1.1.5 of the Unicode Standard in JDK release 1.0.

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 Characters

The table below lists the special characters which are supported by Java.

Description Representation
Backslash \\
Continuation \
Backspace \b
Carriage return \r
Form feed \f
Horizontal tab \t
Newline \n
Single quote \'
Double quote \"
Unicode character \udddd
Octal character \ddd

An example of a Unicode character literal is \u0048, which is a hexadecimal representation of the character H. This same character is represented in octal as \110.

Keywords

The Java language specification lists a group of keywords that can be used only for their intended purpose as listed in the specification.

abstract boolean breakbyte byvalue
case cast catchchar class
const continue defaultdo double
else extends falsefinal finally
float for futuregeneric goto
int interface longnative new
null operator outerpackage private
protected public restreturn short
static super switchsynchronized this
throw throws transienttrue try
var void volatile while  

Java Reserved Keywords

As with other languages, Java's keywords cannot be used as identifiers.

Declarations

A 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:
  • A package, declared in a package declaration
  • An imported type, declared in a single-type-import declaration or a type-import-on-demand declaration
  • A class, declared in a class type declaration
  • An interface, declared in an interface type declaration
  • A member of a reference type, one of the following:
    • A field, one of the following:
      • A field declared in a class type
      • A constant field declared in an interface type
      • The field length, which is implicitly a member of every array type
    • A method, one of the following:
      • A method (abstract or otherwise) declared in a class type
      • A method (always abstract) declared in an interface type
  • A parameter, one of the following:
    • A parameter of a method or constructor of a class
    • A parameter of an abstract method of an interface
    • A parameter of an exception handler declared in a catch clause of a try statement
  • A local variable, one of the following:
    • A local variable declared in a block
    • A local variable declared in a for statement
Constructors are also introduced by declarations, but use the name of the class in which they are declared rather than introducing a new name.

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 Types

Java'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.
  1. Where C and C++ leave a number of issues to be machine and compiler dependent (for instance the size of an int) Java specifies everything.
  2. Java prevents casting between arbitrary variables. Only casts between numeric variables and between sub and superclasses of the same object are allowed.
  3. All numeric variables in Java are signed.
The Java primitive data types are described in the paragraphs which follow. When appropriate, example literals for each type are shown.

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 literal
long. 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 literal 
float. 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+22f
double. 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+22d
char. 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 & Casting

Inevitably, 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 cast
What 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.

From Type To Type
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float double

Assignment Operators & Statements

Assignment 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:

Description Operator
Simple =
Addition +=
Subtraction -=
Multiplication *=
Division /=
Modulus %=
AND &=
OR |=
XOR ^=

The examples shown below illustrate several variable declarations, intializations and assignment statements which use the various Java assignment operators.
 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/Literals

Programmers 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.

Expressions

Once 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.

Boolean

Boolean operators act on boolean types and return a boolean result. The table below illustrates the Java Boolean operators.

Description Operator
Evaluation AND &
Evaluation OR |
Evaluation XOR ^
Logical AND &&
Logical OR ||
Negation !
Equal-to ==
Not-equal-to !=
Conditional ?:

The evaluation operators (&, |, and ^) evaluate both sides of an expression before determining the result. The logical operators (&& and ||) avoid the right-side evaluation of the expression if it is not needed. To better understand the difference between these operators, take a look at the following two expressions:
 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 : 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.

OOP Definitions

The following definitions relate to object-oriented programming. These definitions are given in general form, but apply to Java.
class
In object-oriented programming, a class is a template definition of the methods and variables in a particular kind of object. Thus, an object is a specific instance of a class; it contains real values instead of variables.

The class is one of the defining ideas of object-oriented programming. Among the important ideas about classes are:

  • A class can have subclasses that can inherit all or some of the characteristics of the class. In relation to each subclass, the class becomes the superclass.
  • Subclasses can also define their own methods and variables that are not part of their superclass.
  • The structure of a class and its subclasses is called the class hierarchy.
constructor (in OOP sense)
A procedure that is used for creating and initializing objects. In Java, a constructor is called after the object has been created and is used mainly to initialize the object's internal state.
destructor
A function provided by a class in C++ and some other object-oriented languages to delete an object, the inverse of a constructor.
encapsulation
Language mechanism for restricting access to some of the object's components.
inheritance
In object-oriented programming, inheritance is the concept that when a class of objects is defined, any subclass that is defined can inherit the definitions of one or more general classes. This means for the programmer that an object in a subclass need not carry its own definition of data and methods that are generic to the class (or classes) of which it is a part. This not only speeds up program development; it also ensures an inherent validity to the defined subclass object (what works and is consistent about the class will also work for the subclass).
instance
An individual object of a certain class. While a class is just the type definition, an actual usage of a class is called an "instance." Each instance of a class can have different values for its instance variables, i.e., its state.
instance variable
Local variable defined in each instance of the class. Instance variables of different instances are independent.
message
A name and a list of parameter values. Objects in Java communicate by sending messages to each other.
method
In object-oriented programming, a method is a programmed procedure that is defined as part of a class and included in any object of that class. A class (and thus an object) can have more than one method. A method in an object can only have access to the data known to that object, which ensures data integrity among the set of objects in an application. A method can be re-used in multiple objects.
object
In object-oriented programming an object is a self-contained entity that consists of both data and procedures to manipulate the data.
object-oriented programming
A type of programming in which programmers define not only the data type of a data structure, but also the types of operations (functions) that can be applied to the data structure. In this way, the data structure becomes an object that includes both data and functions. In addition, programmers can create relationships between one object and another. For example, objects can inherit characteristics from other objects.

One of the principal advantages of object-oriented programming techniques over procedural programming techniques is that they enable programmers to create modules that do not need to be changed when a new type of object is added. A programmer can simply create a new object that inherits many of its features from existing objects. This makes object-oriented programs easier to modify.

state
How something is; its configuration, attributes, condition, or information content. The state of a system is usually temporary (i.e., it changes with time) and volatile (i.e., it will be lost or reset to some initial state if the system is switched off).
subclass
In object-oriented programming, a class that is derived from a superclass by inheritance. The subclass contains all the features of the superclass, but may have new features added or redefine existing features.
    Click on the button at left to return to the calling page.

 

There have been visitors since 11/26/2003

Added to the Web: October 27, 1999.
Last updated: October 31, 1999.
Web page design by Dan Solarek.

http://cset.sp.utoledo.edu/cset4250/