Scrigroup - Documente si articole

Username / Parola inexistente      

Home Documente Upload Resurse Alte limbi doc  

AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Using Java operators


+ Font mai mare | - Font mai mic

Using Java operators

An operator takes one or more arguments and produces a new value. The arguments are in a different form than ordinary method calls, but the effect is the same. You should be reasonably comfortable with the general concept of operators from your previous programming experience. Addition (+), subtraction and unary minus (-), multiplication (*), division (/) and assignment (=) all work much the same in any programming language.

All operators produce a value from their operands. In addition, an operator can change the value of an operand. This is called a side effect. The most common use for operators that modify their operands is to generate the side effect, but you should keep in mind that the value produced is available for your use just as in operators without side effects.

Almost all operators work only with primitives. The exceptions are '=', '==' and ' ', which work with all objects (and are a point of confusion for objects). In addition, the String class supports '+' and '+='.


Operator precedence defines how an expression evaluates when several operators are present. Java has specific rules that determine the order of evaluation. The easiest one to remember is that multiplication and division happen before addition and subtraction. Programmers often forget the other precedence rules, so you should use parentheses to make the order of evaluation explicit. For example:

A = X + Y - 2/2 + Z;

has a very different meaning from the same statement with a particular grouping of parentheses:

A = X + (Y - 2)/(2 + Z);


Assignment is performed with the operator =. It means "take the value of the right-hand side (often called the rvalue) and copy it into the left-hand side (often called the lvalue). An rvalue is any constant, variable or expression that can produce a value, but an lvalue must be a distinct, named variable. (That is, there must be a physical space to store a value.) For instance, you can assign a constant value to a variable (A = ), but you cannot assign anything to constant value - it cannot be an lvalue. (You can't say 4 = A;.)

Assignment of primitives is quite straightforward. Since the primitive holds the actual value and not a handle to an object, when you assign primitives you copy the contents from one place to another. For example, if you say A = B for primitives, then the contents of B is copied into A. If you then go on to modify A, B is naturally unaffected by this modification. This is what you've come to expect as a programmer for most situations.

When you assign objects, however, things change. Whenever you manipulate an object, what you're manipulating is the handle, so when you assign "from one object to another" you're actually copying a handle from one place to another. This means that if you say C = D for objects, you end up with both C and D pointing to the object that, originally, only D pointed to. The following example will demonstrate this.

As an aside, the first thing you see is a package statement for package c03, indicating this book's Chapter 3. The first code listing of each chapter will contain a package statement like this to establish the chapter number for the remaining code listings in that chapter. In Chapter 17, you'll see that as a result, all the listings in chapter 3 (except those that have different package names) will be automatically placed in a subdirectory called c03, Chapter 4's listings will be in c04 and so on. All this will happen via the program shown in Chapter 17, and in Chapter 5 the concept of packages will be fully explained. What you need to recognize at this point is that, for this book, lines of code of the form package c03 are used just to establish the chapter subdirectory for the listings in the chapter.

In order to run the program, you must ensure that the classpath contains the root directory where you installed the source code for this book. (From this directory, you'll see the subdirectories c02, c03, c04, etc.)

For later versions of Java (1.1.4 and on), when your main( ) is inside a file with a package statement, you must give the full package name before the program name in order to run the program. In this case, the command line is:

java c03.Assignment

Keep this in mind any time you're running a program that's in a package.

Here's the example:


// Assignment with objects is a bit tricky

package c03;

class Number

public class Assignment

} ///:~

The Number class is simple, and two instances of it (n1 and n2) are created within main( ). The i value within each Number is given a different value, and then n2 is assigned to n1, and n1 is changed. In many programming languages you would expect n1 and n2 to be independent at all times, but because you've assigned a handle here's the output you'll see:

1: n1.i: 9, n2.i: 47

2: n1.i: 47, n2.i: 47

3: n1.i: 27, n2.i: 27

Changing the n1 object appears to change the n2 object as well! This is because both n1 and n2 contain the same handle, which is pointing to the same object. (The original handle that was in n1 that pointed to the object holding a value of 9 was overwritten during the assignment and effectively lost; its object will be cleaned up by the garbage collector.)

This phenomenon is often called aliasing and it's a fundamental way that Java works with objects. But what if you don't want aliasing to occur in this case? You could forego the assignment and say:

n1.i = n2.i;

This retains the two separate objects instead of tossing one and tying n1 and n2 to the same object, but you'll soon realize that manipulating the fields within objects is messy and goes against good object-oriented design principles. This is a non-trivial topic, so it is left for Chapter 12, which is devoted to aliasing. In the meantime, you should keep in mind that assignment for objects can add surprises.

Aliasing during method calls

Aliasing will also occur when you pass an object into a method:


// Passing objects to methods can be a bit tricky

class Letter

public class PassObject

public static void main(String[] args)

} ///:~

In many programming languages, the method f( ) would appear to be making a copy of its argument Letter y inside the scope of the method. But once again a handle is being passed so the line

y.c = 'z';

is actually changing the object outside of f( ). The output shows this:

1: x.c: a

2: x.c: z

Aliasing and its solution is a complex issue and, although you must wait until Chapter 12 for all the answers, you should be aware of it at this point so you can watch for pitfalls.

Politica de confidentialitate | Termeni si conditii de utilizare



Vizualizari: 632
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved