Now that you’ve learned how to declare and initialize variables, you probably want to know how to do something with them. Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.
As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.
Operator Precedence
Operators
Precedence
postfix
expr++ expr—
unary
++expr —expr +expr –expr ~ !
multiplicative
* / %
additive
+ –
shift
<< >> >>>
relational
< > <= >= instanceof
equality
== !=
bitwise AND
&
bitwise exclusive OR
^
bitwise inclusive OR
|
logical AND
&&
logical OR
||
ternary
? :
assignment
= += -= *= /= %= &= ^= |= <<= >>= >>>=
In general-purpose programming, certain operators tend to appear more frequently than others; for example, the assignment operator “
=
” is far more common than the unsigned right shift operator “>>>
“. With that in mind, the following discussion focuses first on the operators that you’re most likely to use on a regular basis, and ends focusing on those that are less common. Each discussion is accompanied by sample code that you can compile and run. Studying its output will help reinforce what you’ve just learned.
Variables
As you learned in the previous lesson, an object stores its state in fields.
int cadence = 0;
int speed = 0;
int gear = 1;
The What Is an Object? discussion introduced you to fields, but you probably have still a few questions, such as: What are the rules and conventions for naming a field? Besides
int
, what other data types are there? Do fields have to be initialized when they are declared? Are fields assigned a default value if they are not explicitly initialized? We’ll explore the answers to such questions in this lesson, but before we do, there are a few technical distinctions you must first become aware of. In the Java programming language, the terms “field” and “variable” are both used; this is a common source of confusion among new developers, since both often seem to refer to the same thing.
The Java programming language defines the following kinds of variables:
Having said that, the remainder of this tutorial uses the following general guidelines when discussing fields and variables. If we are talking about “fields in general” (excluding local variables and parameters), we may simply say “fields”. If the discussion applies to “all of the above”, we may simply say “variables”. If the context calls for a distinction, we will use specific terms (static field, local variables, etc.) as appropriate. You may also occasionally see the term “member” used as well. A type’s fields, methods, and nested types are collectively called its members.
- Instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in “non-static fields”, that is, fields declared without the
static
keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); thecurrentSpeed
of one bicycle is independent from thecurrentSpeed
of another.
- Class Variables (Static Fields) A class variable is any field declared with the
static
modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked asstatic
since conceptually the same number of gears will apply to all instances. The codestatic int numGears = 6;
would create such a static field. Additionally, the keywordfinal
could be added to indicate that the number of gears will never change.
- Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example,
int count = 0;
). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
- Parameters You’ve already seen examples of parameters, both in the
Bicycle
class and in themain
method of the “Hello World!” application. Recall that the signature for themain
method ispublic static void main(String[] args)
. Here, theargs
variable is the parameter to this method. The important thing to remember is that parameters are always classified as “variables” not “fields”. This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you’ll learn about later in the tutorial.
Naming
- Variable names are case-sensitive. A variable’s name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign “
$
“, or the underscore character “_
“. The convention, however, is to always begin your variable names with a letter, not “$
” or “_
“. Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it’s technically legal to begin your variable’s name with “_
“, this practice is discouraged. White space is not permitted.
- Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named
cadence
,speed
, andgear
, for example, are much more intuitive than abbreviated versions, such ass
,c
, andg
. Also keep in mind that the name you choose must not be a keyword or reserved word.
- If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names
gearRatio
andcurrentGear
are prime examples of this convention. If your variable stores a constant value, such asstatic final int NUM_GEARS = 6
, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.
Java Language Keywords
Here’s a list of keywords in the Java programming language. You cannot use any of the following as identifiers in your programs. The keywordsconst
andgoto
are reserved, even though they are not currently used.true
,false
, andnull
might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs.
abstract
continue
for
new
switch
assert
***
default
goto
*
package
synchronized
boolean
do
if
private
this
break
double
implements
protected
throw
byte
else
import
public
throws
case
enum
****
instanceof
return
transient
catch
extends
int
short
try
char
final
interface
static
void
class
finally
long
strictfp
**
volatile
const
*
float
native
super
while
*
not used
**
added in 1.2
***
added in 1.4
****
added in 5.0
Object-Oriented Programming Concepts
If you’ve never used an object-oriented programming language before, you’ll need to learn a few basic concepts before you can begin writing any code. This lesson will introduce you to objects, classes, inheritance, interfaces, and packages. Each discussion focuses on how these concepts relate to the real world, while simultaneously providing an introduction to the syntax of the Java programming language.
What Is an Object?
An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner.
What Is a Class?
A class is a blueprint or prototype from which objects are created. This section defines a class that models the state and behavior of a real-world object. It intentionally focuses on the basics, showing how even a simple class can cleanly model state and behavior.
What Is Inheritance?
Inheritance provides a powerful and natural mechanism for organizing and structuring your software. This section explains how classes inherit state and behavior from their superclasses, and explains how to derive one class from another using the simple syntax provided by the Java programming language.
What Is an Interface?
An interface is a contract between a class and the outside world. When a class implements an interface, it promises to provide the behavior published by that interface. This section defines a simple interface and explains the necessary changes for any class that implements it.
What Is a Package?
A package is a namespace for organizing classes and interfaces in a logical manner. Placing your code into packages makes large software projects easier to manage. This section explains why this is useful, and introduces you to the Application Programming Interface (API) provided by the Java platform.
Questions and Exercises: Object-Oriented Programming Concepts
Use the questions and exercises presented in this section to test your understanding of objects, classes, inheritance, interfaces, and packages.
What Is an Interface?
As you’ve already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object’s interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the “power” button to turn the television on and off.
In its most common form, an interface is a group of related methods with empty bodies. A bicycle’s behavior, if specified as an interface, might appear as follows:
To implement this interface, the name of your class would change (tointerface Bicycle {void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
ACMEBicycle
, for example), and you’d use theimplements
keyword in the class declaration:
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.class ACMEBicycle implements Bicycle {// remainder of this class implemented as before
}
Note: To actually compile theACMEBicycle
class, you’ll need to add thepublic
keyword to the beginning of the implemented interface methods. You’ll learn the reasons for this later in the lessons on Classes and Objects and Interfaces and Inheritance.
Questions and Exercises: Object-Oriented Programming Concepts
Questions
- Real-world objects contain ___ and ___.
- A software object’s state is stored in ___.
- A software object’s behavior is exposed through ___.
- Hiding internal data from the outside world, and accessing it only through publicly exposed methods is known as data ___.
- A blueprint for a software object is called a ___.
- Common behavior can be defined in a ___ and inherited into a ___ using the ___ keyword.
- A collection of methods with no implementation is called an ___.
- A namespace that organizes classes and interfaces by functionality is called a ___.
- The term API stands for ___?
Exercises
Check your answers.
- Create new classes for each real-world object that you observed at the beginning of this trail. Refer to the Bicycle class if you forget the required syntax.
- For each new class that you’ve created above, create an interface that defines its behavior, then require your class to implement it. Omit one or two methods and try compiling. What does the error look like?
Answers to Questions and Exercises: Object-Oriented Programming Concepts
Answers to Questions
- Real-world objects contain state and behavior.
- A software object’s state is stored in fields.
- A software object’s behavior is exposed through methods.
- Hiding internal data from the outside world, and accessing it only through publicly exposed methods is known as data encapsulation.
- A blueprint for a software object is called a class.
- Common behavior can be defined in a superclass and inherited into a subclass using the extends keyword.
- A collection of methods with no implementation is called an interface.
- A namespace that organizes classes and interfaces by functionality is called a package.
- The term API stands for Application Programming Interface.
Answers to Exercises
- Your answers will vary depending on the real-world objects that you are modeling.
- Your answers will vary here as well, but the error message will specifically list the required methods that have not been implemented.
What Is a Package?
A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.
The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the “Application Programming Interface”, or “API” for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a
String
object contains state and behavior for character strings; aFile
object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; aSocket
object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work.
The Java Platform API Specification contains the complete listing for all packages, interfaces, classes, fields, and methods supplied by the Java Platform 6, Standard Edition. Load the page in your browser and bookmark it. As a programmer, it will become your single most important piece of reference documentation.
What Is Inheritance?
Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example,
Bicycle
now becomes the superclass ofMountainBike
,RoadBike
, andTandemBike
. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:
A hierarchy of bicycle classes.
The syntax for creating a subclass is simple. At the beginning of your class declaration, use the
extends
keyword, followed by the name of the class to inherit from:class MountainBike extends Bicycle {This gives// new fields and methods defining a mountain bike would go here
}
MountainBike
all the same fields and methods asBicycle
, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.
What Is a Class?
In the real world, you’ll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
The following
Bicycle
class is one possible implementation of a bicycle:
The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fieldsclass Bicycle {int cadence = 0;
int speed = 0;
int gear = 1;void changeCadence(int newValue) {
cadence = newValue;
}void changeGear(int newValue) {
gear = newValue;
}void speedUp(int increment) {
speed = speed + increment;
}void applyBrakes(int decrement) {
speed = speed – decrement;
}void printStates() {
System.out.println(“cadence:”+cadence+” speed:”+speed+” gear:”+gear);
}
}
cadence
,speed
, andgear
represent the object’s state, and the methods (changeCadence
,changeGear
,speedUp
etc.) define its interaction with the outside world.
You may have noticed that the
Bicycle
class does not contain amain
method. That’s because it’s not a complete application; it’s just the blueprint for bicycles that might be used in an application. The responsibility of creating and using newBicycle
objects belongs to some other class in your application.
Here’s a
BicycleDemo
class that creates two separateBicycle
objects and invokes their methods:
The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:class BicycleDemo {
public static void main(String[] args) {// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();// Invoke methods on those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3