what is java - angelfire.com  · web viewunlike helloworldapp, however, the applet runs in a...

31
What is Java? Java is a "simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language." [Flanagan, 1996] What does all that mean? Simple: Java was made to look and act much like C and C++, since so many people are already familiar with those languages. However, to simplify matters, several features common to C and C+ + were not included. Among those are pointers, header files, and goto's. Object-Oriented:. “The fundamental idea behind object-oriented languages is to combine into a single unit both data and the functions that operate on that data. Such a unit is called an object." [LaFore, 1995] By using objects, we can model the real world in a more natural fashion, and we also achieve some other useful side effects. Java is not 100% object-oriented like SmallTalk, but it is much more so that C++. Distributed: Java was designed with today's distributed networks in mind. It is capable of network communication and handling socket calls. Interpreted: Java code is compiled into byte-code, which is somewhat similar to a binary executable. Instead of being run by your operating system, though, the byte-code is run by the Java Virtual Machine, a byte-code interpreter. The advantage is that the Java code doesn't have to be directly translated into the system-specific machine code. Instead, the Java Virtual Machine acts as an intermediary which will be the same on every system. So, the end result is code that acts the same on every computer. Robust: Java is a strongly typed language, and so will catch most errors long before run-time. Also, since Java doesn't support pointers, code written in Java is much more reliable. Another feature adding to Java's robustness is its exception handling. When an error occurs, the code is able to deal with it on the fly, allowing for a high rate of recovery.

Upload: dinhtuyen

Post on 15-Dec-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

What is Java?

Java is a "simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language." [Flanagan, 1996]

What does all that mean?

Simple: Java was made to look and act much like C and C++, since so many people are already familiar with those languages. However, to simplify matters, several features common to C and C++ were not included. Among those are pointers, header files, and goto's.

Object-Oriented:. “The fundamental idea behind object-oriented languages is to combine into a single unit both data and the functions that operate on that data. Such a unit is called an object." [LaFore, 1995] By using objects, we can model the real world in a more natural fashion, and we also achieve some other useful side effects. Java is not 100% object-oriented like SmallTalk, but it is much more so that C++.

Distributed: Java was designed with today's distributed networks in mind. It is capable of network communication and handling socket calls.

Interpreted: Java code is compiled into byte-code, which is somewhat similar to a binary executable. Instead of being run by your operating system, though, the byte-code is run by the Java Virtual Machine, a byte-code interpreter. The advantage is that the Java code doesn't have to be directly translated into the system-specific machine code. Instead, the Java Virtual Machine acts as an intermediary which will be the same on every system. So, the end result is code that acts the same on every computer.

Robust: Java is a strongly typed language, and so will catch most errors long before run-time. Also, since Java doesn't support pointers, code written in Java is much more reliable. Another feature adding to Java's robustness is its exception handling. When an error occurs, the code is able to deal with it on the fly, allowing for a high rate of recovery.

Secure: Java was designed with the Internet in mind. As such, it has to be secure to be usable at all. Java applets are not allowed to do any file I/O. Also, the lack of pointers prevents a large amount of potential problems.

Portable: Because Java runs on the Java Virtual Machine, and not the individual system itself, Java code is easily portable to any system capable of running the virtual machine.

Performance: Java is approxiamtely 20 times slower than C. However, it is more than fast enough for most of its more commons uses such as applets and multimedia. Java does allow you, though, to import native C code for the times when speed is essential.

Multithreaded: Java can run several simulateous process threads. This allows the user to easily code programs with can do more than one thing at once. Such multitasking capability is invaluable for use in building GUI's and other such applications.

Dynamic: Java was built to be able to adapt to the continually evolving environment. It can dynamically load in classes when they are needed, and it can even got out over the 'Net to find them.

Page 2: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

What Is Java?

Java is two things: a programming language and a platform.

The Java Programming Language

Java is also unusual in that each Java program is both compiled and interpreted. With a compiler, you translate 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. You can think of Java bytecodes as 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. You 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. For example, the same Java program can run on Windows NT, Solaris, and Macintosh.

The Java Platform

A platform is the hardware or software environment in which a program runs. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other, hardware-based platforms. Most other platforms are described as a combination of hardware and operating system.

The Java platform has two components:

The Java Virtual Machine (Java VM) The Java Application Programming Interface (Java API)

You've already been introduced to the Java VM. It's 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 is grouped into libraries (packages) of related components. The next section, What Can Java Do?, highlights each area of functionality provided by the packages in the Java API.

As a platform-independent environment, Java can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring Java's performance close to that of native code without threatening portability.

What Can Java Do?

Probably the most well-known Java programs are Java applets. An applet is a Java program that adheres to certain conventions that allow it to run within a Java-enabled browser. However, Java is not just for writing cute, entertaining applets for the World Wide Web ("Web"). Java is a

Page 3: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

general-purpose, high-level programming language and a powerful software platform. Using the generous Java API, you can write many types of programs.

The most common Java programs are applications and applets. Applications are standalone programs, such as the HotJava browser. Applets are similar to applications, but they don't run standalone. Instead, applets adhere to a set of conventions that lets them run within a Java-compatible browser.

The most common types of programs are probably applets and applications, where a Java application is a standalone program that runs directly on the Java platform. A special kind of application known as a server serves and supports clients on a network. Examples of servers include Web servers, proxy servers, mail servers, print servers, and boot servers.

Another specialized program is a servlet. Servlets are similar to applets in that they are runtime extensions of applications. Instead of working in browsers, though, servlets run within Java servers, configuring or tailoring the server.

How does the Java API support all of these kinds of programs? With packages of software components that provide a wide range of functionality. The core API is the API included in every full implementation of the Java platform. The core API gives you the following features:

The Essentials: Objects, strings, threads, numbers, input and output, data structures, system properties, date and time, and so on. Applets: The set of conventions used by Java applets. Networking: URLs, TCP and UDP sockets, and IP addresses. Internationalization: Help for writing programs that can be localized for users worldwide. Programs can automatically adapt to specific locales and be displayed in the appropriate language. Security: Both low-level and high-level, including electronic signatures, public/private key management, access control, and certificates. Software components: Known as JavaBeans, can plug into existing component architectures such as Microsoft's OLE/COM/Active-X architecture, OpenDoc, and Netscape's Live Connect. Object serialization: Allows lightweight persistence and communication via Remote Method Invocation (RMI). Java Database Connectivity (JDBC): Provides uniform access to a wide range of relational databases.

Java not only has a core API, but also standard extensions. The standard extensions define APIs for 3D, servers, collaboration, telephony, speech, animation, and more.

If Java is, in fact, yet another computer programming language, you may question why it is so important and why it is being promoted as a revolutionary step in computer programming. The answer isn’t immediately obvious if you’re coming from a traditional programming perspective. Although Java will solve traditional stand-alone programming problems, the reason it is important is that it will also solve programming problems on the World Wide Web. [Eckel 1999]

Page 4: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

The key to making Java feasible for most non-Web development projects is the appearance of speed improvements like so-called “just-in time” (JIT) compilers and possibly even native code compilers.Over time, Sun has released three major versions of Java: 1.0, 1.1 and 2.

To write your first program (Win32), you will need: 1. The JavaTM 2 Platform, Standard Edition. You can download it from

http://java.sun.com/products/jdk/1.2/download-windows.html and consult the installation instructions http://java.sun.com/products/jdk/1.2/install-windows.html

2. A text editor.

The file jdk1_2_2-001-win.exe is the Java 2 SDK software installer. If you downloaded it instead of running it directly from the web site, double-click on the installer's icon in whatever directory you've installed it on your computer. Then follow the instructions the installer provides. When done with the installation, you can delete the download file to recover disk space.

Installed Directory TreeAfter installing both the Java 2 SDK software and documentation, the SDK directory will have the structure shown below. The docs directory is created when you install the SDK documentation bundle. jdk1.2.2 ____________________|___________________________ | | | | | | | | | | | | | | | | bin lib | | | demo | docs | | | LICENSE | | | | src.jar jre | | COPYRIGHT | | __|__ | README | include | |README.html include-old bin lib

Update the PATH variable

You can run the Java 2 SDK software just fine without setting the PATH variable, or you can optionally set it as a convenience.

Should I set the PATH variable?Set the PATH variable if you want to be able to conveniently run the SDK executables (javac.exe, java.exe, javadoc.exe, etc.) from any directory without having to type the full path of the command. If you don't set the PATH variable, you need to specify the full path to the executable every time you run it, such as: C:> \jdk1.2.2\bin\javac MyClass.javaIt's useful to set the PATH permanently so it will persist after rebooting.

How do I set the PATH permanently? To set the PATH permanently, add the full path of the jdk1.2.2\bin directory to the

Page 5: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

PATH variable. Typically this full path looks something like C:\jdk1.2.2\bin. Set the PATH as follows, according to whether you are on Windows NT or Windows 95/98.

Windows NT - To set the PATH permanently:

a. Start the Control Panel, select System, select Environment, and look for "Path" in the User Variables and System Variables. If you're not sure where to add the path, add it to the right end of the "Path" in the User Variables. A typical value for PATH is: C:\jdk1.2.2\bin Capitalization doesn't matter. Click "Set", "OK" or "Apply".

The PATH can be a series of directories separated by semi-colons (;). Microsoft Windows looks for programs in the PATH directories in order, from left to right. You should only have one bin directory for the Java 2 SDK in the path at a time (those following the first are ignored), so if one is already present, you can update it to 1.2.2.

b. The new path takes effect in each new Command Prompt window you open after setting the PATH variable.

Windows 98 and Windows 95 - To set the PATH permanently, open the AUTOEXEC.BAT file and add or change the PATH statement as follows:

a. Start the system editor. Choose "Start", "Run" and enter sysedit, then click OK. The system editor starts up with several windows showing. Go to the window that is displaying AUTOEXEC.BAT.

b. Look for the PATH statement. (If you don't have one, add one.) If you're not sure where to add the path, add it to the right end of the PATH. For example, in the following PATH statement, we have added the bin directory at the right end:

PATH C:\WINDOWS;C:\WINDOWS\COMMAND;C:\JDK1.2.2\BIN Capitalization doesn't matter. The PATH can be a series of directories separated by semi-colons (;). Microsoft Windows searches for programs in the PATH directories in order, from left to right. You should only have one bin directory for the Java 2 SDK in the path at a time (those following the first are ignored), so if one is already present, you can update it to 1.2.2.

c. To make the path take effect in the current Command Prompt window, execute the following: C:> c:\autoexec.batTo find out the current value of your PATH, to see if it took effect, at the command prompt, type: C:> path

Check the CLASSPATH variable

The CLASSPATH variable is one way to tell applications written in the Java programming language (including the SDK tools) where to look for user classes. (The -classpath command-line switch is the preferred way.) If your machine does not have

Page 6: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

the CLASSPATH variable set, you can ignore the rest of this step. To check this, run the set command from the DOS prompt: C:> setIf CLASSPATH does not appear in the list of settings, it is not set. If your CLASSPATH variable is set to some value, you may want to clean up your CLASSPATH settings, so read on.

Should I modify the CLASSPATH variable?

The Java 2 SDK will work fine even if CLASSPATH is set for an earlier version of the SDK software, as long as it contains the current directory ".". However, if your CLASSPATH contains classes.zip (which was only in JDK 1.0.x and JDK 1.1.x), and you don't plan to continue using those earlier versions, you can remove that setting from the CLASSPATH now. In any case, if CLASSPATH is set, it should include the current directory -- this makes it possible to compile and then run classes in the current directory.

How do I modify the CLASSPATH? Use the same procedure you used for the PATH variable in the previous step and either:

Remove the CLASSPATH environment variable entirely. With Java 2 SDK, the default value is ".", the current directory. To include any user classes, use the -classpath command line switch instead with java, javac, javadoc and other tools. This is the recommended approach because it doesn't force one CLASSPATH for all applications.-OR-

If you have applications that require CLASSPATH be set, keep those required user classes in CLASSPATH and include the current directory "." If you're no longer using JDK 1.1.x, remove classes.zip.

Your computer system should now be ready to use the Java 2 SDK. In this step, you'll run some simple commands to make sure it is working properly.

You start the compiler, interpreter, or other tool by typing its name into the Command Prompt window, generally with a filename as an argument. The SDK development tools need to be run from the command line and have no GUI interfaces (except AppletViewer). Double-clicking a tool's file icon, such as java.exe, will not do anything useful. To get started, open the DOS Prompt window (on 95 or 98) or Command Prompt window (on NT) if you haven't already done so.

You can specify the path to a tool either by typing the path in front of the tool each time, or by adding the path to the system as in the previous step. The following assumes the Java 2 SDK is installed at C:\jdk1.2.2 and you have set the path variable. (If you have not, add "C:\jdk1.2.2\bin" ahead of the javac and appletviewer commands.)

Compiling a Java class - To run the compiler on a file HelloWorldApp.java, go to the prompt window and execute this: C:> javac HelloWorldApp.java

Page 7: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

See the next section for a link to the Hello World examples, which include the source code for printing "Hello World".

Running Applets - You can run applets in AppletViewer. Here's an example:

Use cd to change to the TicTacToe directory that contains the html file example1.html that embeds an applet:C:> cd \jdk1.2.2\demo\applets\TicTacToe

Run AppletViewer with the html file: C:> appletviewer example1.htmlThis example lets you interactively play Tic-Tac-Toe.

To create this program, you will: Create a Java source file. A source file contains text, written in the Java programming

language, that you and other programmers can understand. You can use any text editor to create and edit source files.

Compile the source file into a bytecode file. The Java compiler, javac, takes your source file and translates its text into instructions that the Java Virtual Machine (Java VM) can understand. The compiler puts these instructions into a bytecode file.

Run the program contained in the bytecode file. The Java VM is implemented by a Java interpreter, java. This interpreter takes your bytecode file and carries out the instructions by translating them into instructions that your computer can understand.

Page 8: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

Create a Java Source File.Start your favorite text editor. In a new document, type in the following code:

/** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */class HelloWorldApp { public static void main(String[] args) { // Display "Hello World!" System.out.println("Hello World!"); }}

When you are done, save this code to a file HelloWorldApp.java

Be Careful When You Type

Type all code, commands, and file names exactly as shown. The Java compiler and interpreter are case-sensitive, so you must capitalize consistently.

HelloWorldApp helloworldapp

Page 9: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

Compile the Source File.From the Start menu, select the MS-DOS Prompt application (Windows 95/98) or

Command Prompt application (Windows NT). The prompt shows your current directory. When you bring up the prompt for Windows 95/98, your current directory is usually WINDOWS on your C drive (as shown above) or WINNT for Windows NT. To compile your source code file, change your current directory to the directory where your file is located.

Now you can compile. At the prompt, type the following command and press Enter:javac HelloWorldApp.java If your prompt reappears without error messages, congratulations. You have successfully compiled your program.

Run the Program.In the same directory, enter at the prompt:

java HelloWorldApp

Now you should see:

Creating Your First AppletHelloWorldApp is an example of a Java application, a standalone program. Now you will create a Java applet called HelloWorld, which also displays the greeting "Hello world!". Unlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, Netscape Navigator, or Microsoft Internet Explorer.To create this applet, you'll perform the basic steps as before: create a Java source file; compile the source file; and run the program.

a. Create a Java Source File.1. Start text editot. Type the following code into a new document:

Page 10: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

import java.applet.*;import java.awt.*; /** * The HelloWorld class implements an applet that * simply displays "Hello World!". */public class HelloWorld extends Applet { public void paint(Graphics g) { // Display "Hello World!" g.drawString("Hello world!", 50, 25); }}

Save this code to a file called HelloWorld.java.

2. You also need an HTML file to accompany your applet. Type the following code into a new text document:

<HTML><HEAD><TITLE>A Simple Program</TITLE></HEAD><BODY>Here is the output of my program:<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25></APPLET></BODY></HTML>

Save this code to a file called Hello.html.

b. Compile the Source File.At the prompt, type the following command and press Return:

javac HelloWorld.java

The compiler should generate a Java bytecode file, HelloWorld.class.

c. Run the Program.Although you can view your applets using a Web browser, you may find it easier to test your applets using the simple appletviewer application that comes with the JavaTM Platform. To view the HelloWorld applet using appletviewer, enter at the prompt:

appletviewer Hello.html

Now you should see:

Page 11: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

Congratulations! Your applet works.

Page 12: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

Programming Basics

Variables

Like other programming languages, Java allows you to declare variables in your programs. You use variables to hold data. All variables in Java have a type, a name, and scope.

Definition: A variable is a container in your program that is used to hold data of a particular type.

You must explicitly provide a name and a type for each variable you want to use in your program. The variable's name is its identifier. You use the variable name to refer to the data it contains. The variable's type determines what values it can hold and what operations can be performed on it. To give a variable a type and a name, you write a variable declaration, which generally looks like this:

type name

In addition to the name and type that you explicitly give a variable, a variable also has scope. Scope is the life-span of the variable, it determines what sections of code can use the variable. The location of the variable declaration, that is, where the declaration appears in relation to other code elements, determines its scope.

Data Types

All variables in the Java language must have a data type. A variable's data type determines the values that the variable can contain and the operations that can be performed on it.

The Java programming language has two major categories of data types: primitive and reference.

A variable of primitive type contains a single value of the appropriate size and format for its type: a number, character, or boolean value. For example, the value of an int is an integer, the value of a char is a 16-bit Unicode character, and so on.

Arrays, classes, and interfaces are reference types. The value of a reference type variable, in contrast to that of a primitive type, is a reference to the actual value or set of values represented by the variable. A reference is called a pointer or a memory address in other languages. A reference is like your friend's address: The address is not your friend, but it's a way to reach your friend. A reference type variable is not the array or object itself but rather a way to reach it.

Page 13: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

Primitive Data Types Keyword Description Size/Format

(integers)byte Byte-length integer 8-bit two's complementshort Short integer 16-bit two's complementint Integer 32-bit two's complementlong Long integer 64-bit two's complement

(real numbers)float Single-precision floating point 32-bit IEEE 754double Double-precision floating point 64-bit IEEE 754

(other types)

char A single character 16-bit Unicode characterboolean A boolean value (true or false) true or false

Variable Names

A program refers to a variable's value by its name.

In Java, the following must hold true for a variable name:

It must be a legal Java identifier comprised of a series of Unicode characters. Unicode is a character-coding system designed to support text written in diverse human languages. It allows for the codification of up to 65,536 characters, currently 34,168 have been assigned. This allows you to use characters in your Java programs from various alphabets, such as Japanese, Greek, Cyrillic, and Hebrew. This is important so that programmers can write code that is meaningful in their native languages.

It must not be a keyword, a boolean literal (true or false), or the reserved word null.

It must be unique within its scope.

By Convention: Variable names begin with a lowercase letter and class names begin with an uppercase letter. If a variable name consists of more than one word, such as isVisible, the words are joined together and each word after the first begins with an uppercase letter.

Rule #3 implies that variables may have the same name as another variable whose declaration appears in a different scope.

Examples:

int width, height; // multiple variables char ch = 'S'; // comment after declarationint age = 21; // assigning values to variables at

Page 14: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

//declaration

Exercise: DataTypes.java

Output:

Casting Primitive Types Casting is a process of converting a value of one type to a value of another type. Generally no casting is required when assigning a smaller type primitive to a larger type primitive.A type can be assigned to any types to the right of it without casting:

double float long int short byte Explicit cast

Final Variables

Page 15: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

You can declare a variable in any scope to be final, including parameters to methods and constructors. The value of a final variable cannot change after it has been initialized.

To declare a final variable, use the final keyword in the variable declaration before the type:

final int aFinalVar = 0;

The previous statement declares a final variable and initializes it, all at once. Subsequent attempts to assign a value to aFinalVar result in a compiler error. You may, if necessary, defer initialization of a final local variable. Simply declare the local variable and initialize it later, like this:

final int blankfinal; . . . blankfinal = 0;

A final local variable that has been declared but not yet initialized is called a blank final. Again, once a final local variable has been initialized it cannot be set and any later attempts to assign a value to blankfinal result in a compile-time error.

Scope

A variable's scope is the block of code within which the variable is accessible and determines when the variable is created and destroyed. The location of the variable declaration within your program establishes its scope and places it into one of these four categories:

Member variable Local variable Method parameter Exception-handler parameter

Page 16: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

A member variable is a member of a class or an object. It can be declared anywhere in a class but not in a method. The member is available to all code in the class.

You can declare local variables anywhere in a method or within a block of code in a method. The scope of each variable--the code that can access each variable--extends from the declaration of the variable to the end of the main method (indicated by the first right curly bracket } that appears in the program code). In general, a local variable is accessible from its declaration to the end of the code block in which it was declared.

Method parameters are formal arguments to methods and constructors and are used to pass values into methods and constructions. The scope of a method parameter is the entire method or constructor for which it is a parameter.

Exception-handler parameters are similar to method parameters but are arguments to an exception handler rather than to a method or a constructor.

Page 17: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

Operators

The Java programming language provides a set of operators that you use to perform a function on one, two, or three operands. An operator performs a function on either one, two, or three operands. An operators that requires one operand is called a unary operator. For example, ++ is a unary operator that increments the value of its operand by 1. An operator that requires two operands is a binary operators. For example, = is a binary operator that assigns the value from its right-hand operand to its left-hand operand. And finally a ternary operator is one that requires three operands. The Java programming language has one ternary operator, ?:, which is a short-hand if-else statement.

The unary operators support either prefix or postfix notation. Prefix notation means that the operator appears before its operand:

operator op

Postfix notation means that the operator appears after its operand:

op operator

All of the binary operators use infix notation, which means that the operator appears between its operands:

op1 operator op2

The ternary operator is also infix; each component of the operator appears between operands:

expr ? op1 : op2

In addition to performing the operation, an operator also returns a value. The return value and its type depends on the operator and the type of its operands. For example, the arithmetic operators, which perform basic arithmetic operations such as addition and subtraction, return numbers--the result of the arithmetic operation. The data type returned by the arithmetic operators depends on the type of its operands: If you add two integers, you get an integer back. An operation is said to evaluate to its result.

It's useful to divide the operators into these categories:

Arithmetic Operators Relational and Conditional Operators Shift and Logical Operators Assignment Operators Ternary Operator

Page 18: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

Arithmetic Operators The Java language supports various arithmetic operators for all floating-point and integer numbers. These include + (addition), - (subtraction), * (multiplication), / (division), and % (modulo). For example, you can use this Java code to add two numbers:

addThis + toThis

Or you can use the following Java code to compute the remainder that results from dividing divideThis by byThis:

divideThis % byThis

This table summarizes Java's binary arithmetic operations: Operator Use Description

+ op1 + op2 Adds op1 and op2 - op1 - op2 Subtracts op2 from op1 * op1 * op2 Multiplies op1 by op2 / op1 / op2 Divides op1 by op2 % op1 % op2 Computes the remainder of dividing op1 by op2

Note:  The Java language extends the definition of the + operator to include string concatenation.

The + and - operators have unary versions that perform the following operations:

Operator Use Description+ +op Promotes op to int if it's a byte, short, or char - -op Arithmetically negates op

There also are two short cut arithmetic operators, ++ which increments its operand by 1, and -- which decrements its operand by 1. Either ++ or -- can appear before (prefix) or after (postfix) its operand. The prefix version, ++op/--op, evaluates to the value of the operand after the increment/decrement operation. The postfix version, op++/op--, evaluates the value of the operand before the increment/decrement operation.

Page 19: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

The short cut increment/decrement operators are summarized in the following table:

Operator Use Description++ op++ Increments op by 1; evaluates to the value of op before it was incremented ++ ++op Increments op by 1; evaluates to the value of op after it was incremented -- op-- Decrements op by 1; evaluates to the value of op before it was decremented -- --op Decrements op by 1; evaluates to the value of op after it was decremented

Relational and Conditional Operators A relational operator compares two values and determines the relationship between them. For example, != returns true if the two operands are unequal.

This table summarizes Java's relational operators: Operator Use Returns true if

op1 > op2 op1 is greater than op2 >= op1 >= op2 op1 is greater than or equal to op2 < op1 < op2 op1 is less than op2 <= op1 <= op2 op1 is less than or equal to op2 == op1 == op2 op1 and op2 are equal != op1 != op2 op1 and op2 are not equal

Relational operators often are used with the conditional operators to construct more complex decision-making expressions. One such operator is &&, which performs the boolean and operation. For example, you can use two different relational operators along with && to determine if both relationships are true. The following line of code uses this technique to determine if an array index is between two boundaries. It determines if the index is both greater than 0 and less than NUM_ENTRIES (which is a previously defined constant value):

0 < index && index < NUM_ENTRIES

Note that in some instances, the second operand to a conditional operator may not be evaluated. Consider this code segment:

(numChars < LIMIT) && (...)

The && operator will return true only if both operands are true. So, if numChars is greater than LIMIT, the left-hand operand for && is false and the return value of && can be determined without evaluating the right-hand operand. In such a case, Java will not evaluate the right-hand operand. This has important implications if the right-hand operand has side effects such as reading from a stream, updating a value, or making a calculation.

The operator & is similar to && if both of its operands are of boolean type. However, & always evaluates both of its operands and returns true if both are true. Likewise, | is

Page 20: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

similar to || if both of its operands are boolean. This operator always evalutes both of its operands and returns false if they are both false.

Java supports five binary and one unary conditional operators, shown in the following table: Operator Use Returns true if&& op1 && op2 op1 and op2 are both true, conditionally evaluates op2 || op1 || op2 either op1 or op2 is true, conditionally evaluates op2 ! ! op op is false & op1 & op2 op1 and op2 are both true, always evaluates op1 and op2| op1 | op2 either op1 or op2 is true, always evaluates op1 and op2

^ op1 ^ op2 if op1 and op2 are different--that is if one or the other of the operands is true but not both

Shift and Logical Operators A shift operator allows you to perform bit manipulation on data. This table summarizes the shift operators available in the Java programming language.

Operator Use Operation>> op1 >> op2 shift bits of op1 right by distance op2 << op1 << op2 shift bits of op1 left by distance op2 >>> op1 >>> op2 shift bits of op1 right by distance op2 (unsigned)

Each shift operator shifts the bits of the left-hand operand over by the number of positions indicated by the right-hand operand. The shift occurs in the direction indicated by the operator itself. For example, the following statement shifts the bits of the integer 13 to the right by one position:

13 >> 1;

The binary representation of the number 13 is 1101. The result of the shift operation is 1101 shifted to the right by one position--110 or 6 in decimal. Note that the bit farthest to the right falls off the end into the bit bucket.

The Java programming language also provides these four operators that perform logical functions on their operands: Operator Use Operation

& op1 & op2 bitwise and | op1 | op2 bitwise or ^ op1 ^ op2 bitwise xor ~ ~op2 bitwise complement

The & operation performs the logical "and" function on each parallel pair of bits in each operand. The "and" function sets the resulting bit to 1 if both operands are 1, as shown in this table:

op1 op2 Result

Page 21: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

0 0 00 1 01 0 01 1 1

Suppose you were to "and" the values 12 and 13:

12 & 13

The result of this operation is 12. Why? Well, the binary representation of 12 is 1100, and the binary representation of 13 is 1101. The "and" function sets the resulting bit to 1 if both operand bits are 1, otherwise, the resulting bit is 0. So, if you line up the two operands and perform the "and" function, you can see that the two high-order bits (the two bits farthest to the left of each number) of each operand are 1. Thus the resulting bit in the result is also 1. The low-order bits evaluate to 0 because either one or both bits in the operands are 0:

1101 & 1100 ------ 1100

The | operator performs the inclusive or operation and ^ performs the exclusive or operation. Inclusive or means that if either of the two bits are 1 then the result is 1. The following table shows the results of your inclusive or operations:

op1

op2 Result

0 0 00 1 11 0 11 1 1

Exclusive or means that if the two operand bits are different the result is 1, otherwise the result is 0. The following table shows the results of your exclusive or operation.

op1

op2 Result

0 0 00 1 11 0 11 1 0

And finally, the complement operator inverts the value of each bit of the operand: if the operand bit is 1 the result is 0 and if the operand bit is 0 the result is 1.

Among other things, bitwise manipulations are useful for managing sets of boolean flags. Suppose for example, that you had several boolean flags in your program that indicated the state of various components in your program: is it visible, is it draggable, and so on. Rather than define a separate boolean variable to hold each flag, you could define a single variable, flags, for all of them. Each

Page 22: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

bit within flags would represent the current state of one of the flags. You would then use bit manipulations to set and get each flag.

First, set up constants that indicated the various flags for your program. These flags should each be a different power of two to ensure that the "on" bit doesn't overlap with another flag. Define a variable, flags, whose bits would be set according to the current state of each flag. The following code sample initializes flags to 0 which means that all flags are false (none of the bits are set).

static final int VISIBLE = 1;static final int DRAGGABLE = 2;static final int SELECTABLE = 4;static final int EDITABLE = 8;

int flags = 0;

To set the "visible" flag when something became visible you would use this statement:

flags = flags | VISIBLE;

To test for visibility, you could then write:

if ((flags & VISIBLE) == VISIBLE) { ...}

Expressions, Statements, and Blocks

This section discusses how to combine operators and variables into sequences known as expressions. You will also learn how to construct statements and statement blocks.

Style and Indentation

Java does not impose any specific style.

Import java.applet.*;public class am_i_readable extends Applet { public void init() {System.out.println("Can you guess what I do?");}}

import java.applet.*;

public class am_i_readable extends Applet { public void init() {

Page 23: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

System.out.println("Can you guess what I do?"); } }

Control Flow Statements

Programs use control flow statements to conditionally execute statements, to loop over statements, or to jump to another area in the program.

Page 24: What is Java - angelfire.com  · Web viewUnlike HelloWorldApp, however, the applet runs in a Java-enabled Web browser such as HotJava, ... If a variable name consists of more than

References:[LaFore, 1995] Robert LaFore, "Object-Oriented Programming in C++," The Waite Group Press, 1995, p.6.[Flanagan, 1996] David Flanagan, "Java in a Nutshell," O'Reilly & Associates, Inc., 1996, p.xii.[Eckel, 1999] Bruce Eckel. “Thinking in Java”. Prentice Hall PTR, 1999, p.68