Home > Articles > Programming > Java

The ABCs of Java

This chapter is from the book

Expressions and Operators

An expression is a statement that can convey a value. Some of the most common expressions are mathematical, such as in the following source code example:

int x = 3;
int y = x;
int z = x * y;

All three of these statements can be considered expressions—they convey values that can be assigned to variables. The first assigns the literal 3 to the variable x. The second assigns the value of the variable x to the variable y. The multiplication operator * is used to multiply the x and y integers, and the expression produces the result of the multiplication. This result is stored in the z integer.

An expression can be any combination of variables, literals, and operators. They also can be method calls, because methods can send back a value to the object or class that called the method.

The value conveyed by an expression is called a return value, as you have learned. This value can be assigned to a variable and used in many other ways in your Java programs.

Most of the expressions in Java use operators like *.

New Term

Operators are special symbols used for mathematical functions, some types of assignment statements, and logical comparisons.

Arithmetic

There are five operators used to accomplish basic arithmetic in Java. These are shown in Table 3.3.

Table 3.3 Arithmetic Operators

Operator

Meaning

Example

+

Addition

3 + 4

-

Subtraction

5 - 7

*

Multiplication

5 * 5

/

Division

14 / 7

%

Modulus

20 % 7


Each operator takes two operands, one on either side of the operator. The subtraction operator also can be used to negate a single operand—which is equivalent to multiplying that operand by -1.

One thing to be mindful of when using division is the kind of numbers you're dealing with. If you store a division operation into an integer, the result will be truncated to the next lower whole number because the int data type can't handle floating-point numbers. As an example, the expression 31 / 9 results in 3 if stored as an integer.

Modulus division, which uses the % operator, produces the remainder of a division operation. Using 31 % 9 results in 4 because 31 divided by 9 leaves a remainder of 4.

Note that many arithmetic operations involving integers produce an int regardless of the original type of the operands. If you're working with other numbers, such as floating-point numbers or long integers, you should make sure that the operands have the same type you're trying to end up with.

Listing 3.1 is an example of simple arithmetic in Java.

Listing 3.1 The Source File Weather.java

 1: class Weather {
 2:   public static void main(String[] arguments) {
 3:     float fah = 86;
 4:     System.out.println(fah + " degrees Fahrenheit is ...");
 5:     // To convert Fahrenheit into Celsius
 6:     // Begin by subtracting 32
 7:     fah = fah - 32;
 8:     // Divide the answer by 9
 9:     fah = fah / 9;
10:     // Multiply that answer by 5
11:     fah = fah * 5;
12:     System.out.println(fah + " degrees Celsius\n");
13: 
14:     float cel = 33;
15:     System.out.println(cel + " degrees Celsius is ...");
16:     // To convert Celsius into Fahrenheit
17:     // Begin by multiplying it by 9
18:     cel = cel * 9;
19:     // Divide the answer by 5
20:     cel = cel / 5;
21:     // Add 32 to the answer
22:     cel = cel + 32;
23:     System.out.println(cel + " degrees Fahrenheit");
24:   }
25: }

If you run this Java application, it produces the following output:

86.0 degrees Fahrenheit is ...
30.0 degrees Celsius

33.0 degrees Celsius is ...
91.4 degrees Fahrenheit

In Lines 3–12 of this Java application, a temperature in Fahrenheit is converted to Celsius using the arithmetic operators:

  • Line 3: The floating-point variable fah is created with a value of 86.

  • Line 4: The current value of fah is displayed.

  • Line 5: The first of several comments for the benefit of people trying to figure out what the program is doing. These comments are ignored by the Java compiler.

  • Line 7: fah is set to its current value minus 32.

  • Line 9: fah is set to its current value divided by 9.

  • Line 11: fah is set to its current value multiplied by 5.

  • Line 12: Now that fah has been converted to a Celsius value, fah is displayed again.

A similar thing happens in Lines 14–23, but in the reverse direction. A temperature in Celsius is converted to Fahrenheit.

This program also makes use of System.out.println() in several statements. The System.out.println() method is used in an application to display strings and other information to the standard output device, which usually is the screen.

System.out.println() takes a single argument within its parentheses: a string. To present more than one variable or literal as the argument to println(), you can use the + operator to combine these elements into a single string.

You learn more about this use of the + operator later today.

More About Assignment

Assigning a value to a variable is an expression, because it produces a value. Because of this feature, you can string assignment statements together the following way:

x = y = z = 7;

In this statement, all three variables end up with the value of 7.

The right side of an assignment expression always is calculated before the assignment takes place. This makes it possible to use an expression statement as in the following code example:

int x = 5;
x = x + 2;

In the expression x = x + 2, the first thing that happens is that x + 2 is calculated. The result of this calculation, 7, is then assigned to x.

Using an expression to change a variable's value is an extremely common task in programming. There are several operators used strictly in these cases.

Table 3.4 shows these assignment operators and the expressions they are functionally equivalent to.

Table 3.4 Assignment Operators

Expression

Meaning

x += y

x = x + y

x -= y

x = x - y

x *= y

x = x * y

x /= y

x = x / y


CAUTION

These shorthand assignment operators are functionally equivalent to the longer assignment statements for which they substitute. However, if either side of your assignment statement is part of a complex expression, there are cases where the operators are not equivalent. For example, if x equals 20 and y equals 5, the following two statements do not produce the same value:

x = x / y + 5;
x /= y + 5;

CAUTION

When in doubt, simplify an expression by using multiple assignment statements and don't use the shorthand operators.

Incrementing and Decrementing

Another common task is to add or subtract one from an integer variable. There are special operators for these expressions, which are called increment and decrement operations.

New Term

Incrementing a variable means to add 1 to its value, and decrementing a variable means to subtract 1 from its value.

The increment operator is ++ and the decrement operator is --. These operators are placed immediately after or immediately before a variable name, as in the following code example:

int x = 7;
x = x++;

In this example, the statement x = x++ increments the x variable from 7 to 8.

These increment and decrement operators can be placed before or after a variable name, and this affects the value of expressions that involve these operators.

New Term

Increment and decrement operators are called prefix operators if listed before a variable name, and postfix operators if listed after a name.

In a simple expression such as standards--;, using a prefix or postfix operator produces the same result, making the operators interchangeable. When increment and decrement operations are part of a larger expression, however, the choice between prefix and postfix operators is important.

Consider the following two expressions:

int x, y, z;
x = 42;
y = x++;
z = ++x;

These two expressions yield very different results because of the difference between prefix and postfix operations. When you use postfix operators as in y=x++, y receives the value of x before it is incremented by one. When using prefix operators as in z = ++x, x is incremented by one before the value is assigned to z. The end result of this example is that y equals 42, z equals 44, and x equals 44.

If you're still having some trouble figuring this out, here's the example again with comments describing each step:

int x, y, z; // x, y, and z are all declared
x = 42;   // x is given the value of 42
y = x++;   // y is given x's value (42) before it is incremented
       // and x is then incremented to 43
z = ++x;   // x is incremented to 44, and z is given x's value

CAUTION

As with shorthand operators, increment and decrement operators can produce results you might not have expected when used in extremely complex expressions. The concept of "assigning x to y before x is incremented" isn't precisely right, because Java evaluates everything on the right side of an expression before assigning its value to the left side. Java stores some values before handling an expression in order to make postfix work the way it has been described in this section. When you're not getting the results you expect from a complex expression that includes prefix and postfix operators, try to break the expression into multiple statements to simplify it.

Comparisons

Java has several operators that are used when making comparisons between variables, variables and literals, or other types of information in a program.

These operators are used in expressions that return Boolean values of true or false, depending on whether the comparison being made is true or not. Table 3.5 shows the comparison operators.

Table 3.5 Comparison Operators

Operator

Meaning

Example

==

Equal

x == 3

!=

Not equal

x != 3

<

Less than

x < 3

>

Greater than

x > 3

<=

Less than or equal to

x <= 3

>=

Greater than or equal to

x >= 3


The following example shows a comparison operator in use:

boolean hip;
int age = 33;
hip = age < 25;

The expression age < 25 produces a result of either true or false, depending on the value of the integer age. Because age is 33 in this example (which is not less than 25), hip is given the Boolean value false.

Logical Operators

Expressions that result in Boolean values such as comparison operations can be combined to form more complex expressions. This is handled through logical operators. These operators are used for the logical combinations AND, OR, XOR, and logical NOT.

For AND combinations, the & or && logical operators are used. When two Boolean expressions are linked by the & or && operators, the combined expression returns a true value only if both Boolean expressions are true.

Consider this example, taken directly from the film Harold & Maude:

boolean unusual = (age < 21) & (girlfriendAge > 78);

This expression combines two comparison expressions: age < 21 and girlfriendAge > 78. If both of these expressions are true, the value true is assigned to the variable unusual. In any other circumstance, the value false is assigned to unusual.

The difference between & and && lies in how much work Java does on the combined expression. If & is used, the expressions on either side of the & are evaluated no matter what. If && is used and the left side of the && is false, the expression on the right side of the && never is evaluated.

For OR combinations, the | or || logical operators are used. These combined expressions return a true value if either Boolean expression is true.

Consider this Harold & Maude–inspired example:

boolean unusual = (grimThoughts > 10) || (girlfriendAge > 78);

This expression combines two comparison expressions: grimThoughts > 10 and girlfriendAge > 78. If either of these expressions is true, the value true is assigned to the variable unusual. Only if both of these expressions are false will the value false be assigned to unusual.

Note the use of || instead of |. Because of this usage, if grimThoughts > 10 is true, unusual is set to true and the second expression is never evaluated.

The XOR combination has one logical operator, ^. This results in a true value only if both Boolean expressions it combines have opposite values. If both are true or both are false, the ^ operator produces a false value.

The NOT combination uses the ! logical operator followed by a single expression. It reverses the value of a Boolean expression the same way that a minus symbol reverses the positive or negative sign on a number.

For example, if age < 30 returns a true value, !(age < 30) returns a false value.

These logical operators can seem completely illogical when encountered for the first time. You get plenty of chances to work with them in subsequent chapters, especially on Day 5.

Operator Precedence

When more than one operator is used in an expression, Java has an established precedence to determine the order in which operators are evaluated. In many cases, this precedence determines the overall value of the expression.

For example, consider the following expression:

y = 6 + 4 / 2;

The y variable receives the value 5 or the value 8, depending on which arithmetic operation is handled first. If the 6 + 4 expression comes first, y has the value of 5. Otherwise, y equals 8.

In general, the order from first to last is the following:

  • Increment and decrement operations

  • Arithmetic operations

  • Comparisons

  • Logical operations

  • Assignment expressions

If two operations have the same precedence, the one on the left in the actual expression is handled before the one on the right. Table 3.6 shows the specific precedence of the various operators in Java. Operators farther up the table are evaluated first.

Table 3.6 Operator Precedence

Operator

Notes

. [ ] ()

Parentheses (()) are used to group expressions; period (.) is used for access to methods and variables within objects and classes (discussed tomorrow); square brackets ([ ]) are used for arrays. (This operator is discussed later in the week.)

++ -- ! ~ instanceof

The instanceof operator returns true or false based on whether the object is an instance of the named class or any of that class's subclasses (discussed tomorrow).

new (type)expression

The new operator is used for creating new instances of classes; () in this case is for casting a value to another type. (You learn about both of these tomorrow.)

* / %

Multiplication, division, modulus.

+ -

Addition, subtraction.

<< >> >>>

Bitwise left and right shift.

< > <= >=

Relational comparison tests.

== !=

Equality.

&

AND

^

XOR

|

OR

&&

Logical AND

||

Logical OR

? :

Shorthand for if...then...else (discussed on Day 5).

= += -= *= /= %= ^=

Various assignments.

&= |= <<= >>= >>>=

More assignments.


Returning to the expression y = 6 + 4 / 2, Table 3.6 shows that division is evaluated before addition, so the value of y will be 8.

To change the order in which expressions are evaluated, place parentheses around the expressions that should be evaluated first. You can nest one set of parentheses inside another to make sure that expressions evaluate in the desired order—the innermost parenthetic expression is evaluated first.

The following expression results in a value of 5:

y = (6 + 4) / 2

The value of 5 is the result because 6 + 4 is calculated before the result, 10, is divided by 2.

Parentheses also can be useful to improve the readability of an expression. If the precedence of an expression isn't immediately clear to you, adding parentheses to impose the desired precedence can make the statement easier to understand.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020