-
7/22/2019 SCJP Guide
1/167
Index
Index 1
Chapter 1 : Java Technology 7
1.1 History of Java 7
1.2 What is Java? 8
1.3 Versions of Java 8
1.4 Code Compatibili ty 10
1.5 Java 5.0 Improvements 11
1.6 Features of Java 12
1.7 Java Applets and Applications 14
1.8 Why Java is important to Internet? 14
1.9 The Java Platform 15
1.10 What Can Java Technology Do? 16
1.11 Writing a Program 16
1.12 Compiling the Program 16
1.13 Interpreting and Running the Program 17
1.14 Comments in Java 17
1.15 Application Structure and Elements 18
Summary 19
Chapter 2 : Data types, variables and Arrays 20
2.1 Data Types 20
2.2 Literals 21
2.3 Java Character Encoding: UTF and Unicode 21
2.4 EscapeSequences 22
2.5 Rules for naming an identifier 22
2.6 Java Language Keywords 23
2.7 Variables 23
2.8 Declaring constants Final variables 24
2.9 Arrays 24
2.10 Multidimensional Arrays 26
2.11 Copying Arrays 27
Summary 28
Questions 28
Chapter 3 : Operators 30
3.1 Operands 30
3.2 Operator 31
3.2.1 Arithmetic Operators 31
3.2.2 Increment and Decrement Operators 33
3.2.3 Relational Operators 34
3.2.4 Bitwise Operators 35
3.2.5 Logical Operators 38
3.2.6 Assignment Operators 4 1
3.2.7 Ternary or Conditional operator 42
3.2.8 The [ ] Operator 43
3.2.9 The . Operator 43
3.2.10 The () Operator 43
3.2.11 The (type) Operator 43
3.2.12 The new Operator 43
3.2.13 The instanceof Operator 43
3.3 Expressions 44
3.4 Statements 44
3.5 Operator Precedence 44
3.6 Type Conversion and Casting 46
3.7 Automatic Type Promotions 49
Summary 50
Questions 50
Chapter 4 : Control flow statements 54
4.1 The while and do-while Statements 54
4.2 The for Statement 55
4.3 The if/else Statements 57
4.4 The switch Statement 60
4.5 Branching Statements 62
4.5.1 The break Statement 62
4.5.2 The continue Statement 63
4.5.3 The return Statement 65
4.6 Exception Handling Statements 65
Summary 66
Questions 66
Chapter 5 : Class Fundamentals and OOP 69
5.1 What Is an Object? 69
5.2 What Is a Class? 70
5.3 What Is a Message? 70
5.4 Features of Object Oriented Programming 71
5.4.1 Encapsulation 71
5.4.2 Inheritance 72
5.4.3 Polymorphism 73
5.4.4 Abstraction 74
5.5 Defining Classes 74
5.6 Creating Objects 7 4
5.7 Defining Methods in a class 75
5.8 Declaring Variables in a Class 80
5.9 Instance and Class Members 83
5.10 Static Initializer 88
5.11 Variable Shadowing 89
-
7/22/2019 SCJP Guide
2/167
5.12 Pass by value and Pass by reference 90
5.13 Access Control 93
5.14 Constructors 97
5.15 The this keyword 99
5.16 Overloading 99
5.17 Recursion 102
5.18 Native Methods 1 03
5.19 Arrays of Objects 103
5.20 Nested and Inner Classes 104
5.21 Command-Line Arguments 108
5.22 Enumerated types 110
5.23 Garbage Collection 113
Summary 114
Questions 115
Chapter 6 : Inheritance 120
6.1 Inheritance Basics 120
6.2 Understanding how Constructors are called 123
6.3 Overriding Methods 12 7
6.4 Dynamic Method Dispatch 131
6.5 Annotations 132
6.6 Hiding Member Variables 134
6.7 Abstract Classes 135
6.8 Abstract Methods 1 36
6.9 Final Classes 138
6.10 Final Methods 13 9
6.11 Access control and Inheritance 14 1
6.12 Anonymous Inner Class 141
6.13 The Object class 143
Summary 146
Questions 147
Chapter 7 : Packages and Interfaces 150
7.1 Packages 150
7.2 Using package members 153
7.3 Interfaces 156
7.4 Static Import 161
7.5 strictfp 16 3
Summary 164
Questions 164
Chapter 8 : Assertions and Exception handling 166
8.1 What is an Exception? 166
8.2 Types of Exceptions 171
8.3 Catching and Handlin g Exceptions 173
8.4 The throwStatement 178
8.5 The throws Clause 180
8.6 Overriding methods that throw exceptions 181
8.7 Javas built in exceptions 182
8.8 Chained Exceptions 186
8.9 Creating Your Own Exception Classes 189
8.10 Assertions 190
Summary 193
Questions 194
Chapter 9 : Multithreaded programming 196
9.1 Multitasking 196
9.2 What Is a Thread? 196
9.3 The Thread class 199
9.4 Using the main thread 2 00
9.5 Creating a thread 201
9.6 The Java Thread Model 203
9.7 Thread priority 205
9.8 Using the Thread yieldmethod. 207
9.9 Stopping a Thread 208
9.10 Determining When a Thread Has Finished 209
9.11 Thread Schedulin g 210
9.12 Thread Synchronization 212
9.13 Interthread Communication 219
9.14 Starvation and Deadlock 222
9.15 Suspending, Resuming & Stopping Threads 222
9.16 ThreadGroup 225
Summary 226
Chapter 10 : String Handling 227
10.1 The String class 227
10.2 The StringBuffer Class 238
10.3 The StringBuil der class 247
Questions 247
Chapter 11 : I/O 249
11.1 I/O Streams 2 49
11.2 Reading console input 255
11.3 Writing console output 256
11.4 System.out.printf() 257
11.5 File class 26 0
11.6 Using File Streams 264
11.7 Scanning text with java.util.Scanner 268
11.8 Redirecting Standard I/O 271
11.9 Working with Random Access Files 272
11.10 Filter Streams 274
-
7/22/2019 SCJP Guide
3/167
11.11 Object Serialization 27 7
Summary 281
Chapter 12 : API classes in java.lang package 282
12.1 Wrapper classes 28 2
12.2 Autoboxing/Unboxing of Wrappers 287
12.3 Math class 289
12.4 System class 296
12.5 Runtime class 298
12.6 Class class 3 00
Summary 300
Questions 301
Chapter 13 : Utility & Legacy classes 304
13.1 Enumeration interface 304
13.2 Vector class 304
13.3 Stack class 306
13.4 Dictionary class 308
13.5 Hashtable class 30 8
13.6 Properties class 3 09
13.7 Formatter class 311
13.8 Date class 3 13
13.9 Calendar class 314
13.10 GregorianCal endar class 315
13.11 TimeZone and SimpleTimeZone classes 316
13.12 Locale class 31 8
13.13 StringTokenizer class 319
13.14 StreamTokenizer class 322
13.15 Random class 324
13.16 BitSet class 325
13.17 Timer and TimerTask classes 325
13.18 Observable class 327
13.19 Currency class 32 9
Chapter 14 : Regular Expression Processing 330
14.1 What is a Regular Expression? 330
14.2 Pattern class 332
14.3 Matcher class 3 32
14.4 String Class RegEx Methods 335
Chapter 15 : API classes in java.text 336
15.1 DateFormat class 336
15.2 SimpleDateFormat class 338
15.3 DateFormatSymbols class 3 40
15.4 NumberFormat class 341
15.5 DecimalFormat class 343
15.6 Format class 345
Summary 347
Chapter 16 : Collections Framework and Generics 348
16.1 What is a Collection? 348
16.2 Generics 348
16.3 What Is a Collections Framework? 350
16.4 Collection Interfaces 351
16.5 The Collection Interface 352
16.6 The Set Interface 35 7
16.7 The List Interface 36 1
16.8 The Queue Interface 3 71
16.9 The Map Interface 373
16.10 Object Ordering 37 8
16.11 The SortedSet Interface 385
16.12 The SortedMap Interface 387
16.13 Relationships Among Generics 388
16.14 Wildcard Types 389
16.15 Defining and Using Generic Methods 390
Answers 392
Chapter 2 392
Chapter 3 393
Chapter 4 394
Chapter 5 395
Chapter 6 397
Chapter 7 399
Chapter 8 399
Chapter 10 400
Chapter 12 400
Chapter 1 : Java Technology
1.1 History of Java
Around 1990 James Gosling , Bill Joy and others at Sun
Microsystems began developi ng alanguage call ed Oak. They wanted
it primarily to control microprocessors embedded inconsumer items
such as cable set-top boxes,VCR's, toasters, and also for personal
dataassistants (PDA).
To serve these goals, Oak needed to be:
Platform independent (since multiple manufacturers
involved)Extremely reliableCompact.
-
7/22/2019 SCJP Guide
4/167
However, as of 1993, interactive TV and PDA markets had failed
to take off. Then the Internetand Web explosion began, so Sun
shifted the target market to Internet applications and changedthe
name of the project to Java.
By 1994 Sun's HotJava browser appeared. Written in Java in only
a few months, it illustrated thepower of applets, programs that run
within a browser, and also the capabilities of Java forspeeding
program development.
Riding along with the explosion of interest and publicity in the
Internet, Java quickly receivedwidespread recognition and
expectations grew for it to become the dominant software forbrowser
and consumer applications.
However, the early versions of Java did not possess the breadth
and depth of capabilitiesneeded for client (i.e. con sumer)
applications. For example, the graphics in Java 1.0 seemedcrude and
clumsy compared to mature software developed with C and other
languages.
Applets became popular and remain common but don't dominate i
nteractive or multimedia
displays on web pages. Many other "plug-in" types of programs
also run within the browserenvironment.
So Java has not succeeded at development of consumer
applications. However, Java'scapabilities grew with the release of
new and expanded versions and it became a very popularlanguage for
development of enterprise, or middleware, applications such as on
line web stores,transactions processing, database interfaces, and
so forth.
Java has also become quite common on small platforms such as
cell phones and PDAs. Java isnow used in several hundred cell phone
models. Over 600 million JavaCards, smart cards withadditional
features provided by Java, have been sold as of the summer of
2004.
1.2 What is Java?
The term Java actual refers to more than just a particular
languag e like C or Pascal. Javaencompasses several parts,
including :
A high level language the Java language is a high level one that
at a glance looks verysimilar to C and C++ but offers many unique
features of its own.Java bytecode - a compiler, Sun's javac,
transforms the Java language source code tobytecode that runs in
the JVM.Java Virtual Machine (JVM) a program, such as Sun's java,
that runs on a given platformand takes the bytecode programs as
input and interprets them just as if it were a physicalprocessor
executing machine code.
Sun provides a set of programming tools such as javac, java and
others in a bundle that it calls aJava Software Development Kit for
each version of the language and for different platforms suchas
Windows, Linux, etc.. Sun also provides a runtime bundl e with just
the JVM when theprogramming tools are not needed.
Note that because of the open nature of Java any or all of these
parts can be replaced by non-Sun components. For example, just as
many different languages can create machine code for agiven
processor, compilers of other languages have been created that
output bytecode to run inthe JVM. S imilarly, many JVMs have been
written by groups outside of Sun.
Java, Open or Closed?
Java is not quite an open language but not quite a proprietary
one either. All the core languageproducts - compiler, virtual
machines (VM), class packages, and other components - are
free.Detailed specifications and source code are made openly
available.
The Java Community Process (JCP) leads the development of new
standards for the language.Other companies and organizations can
legally create a clean sheet compiler and/or a VirtualMachine as
long as it follows the publicly available specificati ons.
Microsoft did this with theVersion 1.1 JVM that it used in its
Internet Explorer browser.
Sun, however, does still assert final say on the specifications
and controls the copyrights tologos, and trademarks.
1.3 Versions of Java
Since its introduction, Sun has released a new version of the
Java language every two years orso. Th ese new versions brought
enhancements, new capabilities and fixes to bugs. Untilrecently,
the versions were numbered 1.x, where x reached up till 4.
(Intermediate revisions werelabeled with a third number - 1.x.y -
as in 1.4.2.) The newest version, however, is called Java 5.0rather
than Java 1.5.
Below is a timeline of the different versions of the basic, or
Standard Edition (SE), of Java alongwith some of the new features
that each one introduced. Thi s edition contains the core
languagepackages (the name for code libraries in Java) and is aimed
for desktop programming.
1995: Version 1.0 of the Java Development Kit (JDK) was released
for free by Sun.8 packages with 212 classesNetscape 2.0-4.0
included Java 1.0.Microsoft and other companies licensed Java.
1997: Version 1.1:23 packages - 504 classesImprovements include
better event handling, inner classes, improved JVM.Microsoft
developed its own 1.1. compatibl e Java Virtual Machine for the
Internet Explorer.Many browsers in use are still compatible only
with 1.1.Swingpackages of greatly improved graphics became
available during this time but notincluded with the core
language.59 packages - 1520 classesCode and tools distributed as
The Software Development Kit (SDK)Java Foundation Classes (JFC),
based on Swing, for improved graphics and userinterfaces, now
included with the core language.Collections API included support
for various lists, sets, and hash maps.76 packages - 1842
classesPerformance enhancements including the Hotspotvirtual
machine.135 packages - 2991 classesImproved IO, XML support,
etc.165 packages, over 3000 classesFaster startup and smaller
memory footprintMetadata
Formatted outputGenericsImproved multithreading features1999:
Version 1.2, also called the Java 2 Platform2000: Version 1.3:2002:
Version 1.4:2004: Version 5.0 (previously numbered 1.5):
Other Editions of Java
In the late 1990s, Sun split off two other more specialized
branches, or editions, of Java. One isaimed at small, embedded
applications and the other for large scale middleware
applications:
Micro Java
Embedded systems such as cell phones and device controllers
typically offer reduced resourcesas compared to desktop PCs. T his
means substantially less disk space or no disk at all, and lessof
other types of nonvolatile memory. It also usual ly means a smaller
display or perhaps nodisplay at all.
For such systems Sun offers slimmed down versions of Java.
JavaCard - extremely limited Java for systems with only 16kb
nonvolatile memory and 512bytes volatileEmbeddedJava - based on
Java 1.1 for 32 bit system with about 512kb each for ROM andRAM.
Individual packages, classes and even methods in the core language
can be thrownout to make room.PersonalJava - based on Java 1.1.8
for larger systems with 2MB ROM and more than 1MB
RAM.Java 2 Platform, Micro Edition (J2ME) - based on the Java 2
Platform, J2ME replaces theJava 1.1 based systems (EmbeddedJava and
PersonalJava but not JavaCard). Thedeveloper will choose from
different configurations to suit the capacity of a given
system.
J2EE - Java 2 Platform, Enterprise Edition
With the Java 2 Platform came a separate version with enhanced
resources targeted atenterprise applications. The Java 2 Enterprise
Edition now provides a wide array of tools forbuilding middleware
software such as for database access applications, online
storefronts, andother services.
Naming Conventions
http://jcp.org/
-
7/22/2019 SCJP Guide
5/167
All of these editions and version n umbers can be a bit
confusing for newcomers. A lso, termschange such as Java
Development Kit becoming Software Development Kit. For this
course,however, you can just use the latest version - Java 5.0 -
and not worry about all these historicalissues.
1.4 Code Compatibility
Sun has maintained good compatibility among codes written with
the different versions.Generally, the newer versions maintain
compatibilty with older code. The approach has been toadd new
features without subtracting any older features. (In some cases,
such as the eventhandling system introduced in Java 1.1, code using
newer classes and techniques should not bemixed in the same program
with older version code.)
Thus far, Java maintains backwards compatibility. A program
written according to Java 1.0 willcompile with a Java 5 compiler.
(Thou gh some obsolete methods will generate "deprecation"warning
messages from the compiler.) The bytecode from a Java 1.0 compiler
will still run in a
Java 5 virtual machine.
1.5 Java 5.0 Improvements
Java 2 Platform, Standard Edition 5.0 (J2SE 5.0) was launched as
the official Java version bySun on September 30, 2004.
Most of the changes fall into the ease of development (EoD)
category. With a few importantexceptions, the changes do not add
new functionality but rather provide an easier way of doingthe same
things you could do before but with less code and better
compiler-time error detection.The most important changes to the
platform include the following:
Quality, Stability, and Comp atibility
The designers of J2SE considered quality, stability, and
compatibility to be the most importantaspect of the new release.
Release 5.0 is the most tested release ever. Great efforts were
madeto ensure compatibility with previous versions of Java. The Sun
engine ers made a public pleafor users worldwide to test their code
with the 5.0 Beta releases and to report any problems thatappeared,
especially any code that worked with earlier versions of Java but
failed under 5.0.
Performance and Scalability
Faster JVM startup time and smaller memory footprint were
important goals. These have beenachieved through careful tuning of
the software and use of class data sharing.
Ease of Development
It is in the EoD area that the most significant changes appear.
In most cases, no newfunctionality was added in the sense that
almost anything you can do with 5.0 you could do with1.4, it just
sometimes took a lot more boilerpla te code (i.e. code that is
repeated frequently) to doit. The exception to this general
statement has to do with the new multithreading andconcurrency
features that provide capabilities previously unavailable.
In many cases, the new EoD features are all about syntax
shortcuts that greatly reduce theamount of code that must be
entered, making coding faster and more error free. Some
featuresenable improved compile-time type checking, thus producing
fewer runtime errors.
Monitoring and Manageability
The 5.0 release includes the ability to remotely monitor and
even manage a running Javaapplication . For example, it is now much
easier to watch memory usage and detect and respond
to a low-memory condition. Many of these features are built
right in to the system, and you canadd additional monitoring and
managing features to your own code.
Improved Desktop Client
The last great theme of the 5.0 release was an improved
experience on the desktop client. Inaddition to better performance
because of a faster startup time and smaller memory footprint,there
is a new, improved Swing look and feel called Ocean, and a new
easy-to-customizeskinnable look and feel called Synth in which you
can use XML configuration files to specify theappearance of every
visual component in the system. In addition, the GTK and XP look
and feel sintroduced in J2SE 1.4.2 have received further
improvements. There is support for OpenGL andbetter performance on
Unix X11 platforms. The Java Web Start and Java Plug-In technologie
s(both used to run Java applications downloaded over the Web) have
been improved.
Other new features in J2SE 5.0 include core XML support,
improvements to Unicode,improvements to Java's database
connectivity package known as JDBC, and an improved,
high-compression format for JAR files that can greatly reduce
download times for applets and othernetworked applications.
1.6 Features of Java
The Java programming language is a high-level language that can
be characterized by all of thefollowing buzzwords:
S imp le Ar ch itect ur e neu tr al Object oriented Portable
Distr ibuted High performance Interpreted Multithreaded
Robust Dynamic Secure
With most programming languages, you either compile or interpret
a program so that you can runit on your computer. Th e Java
programming language is unusua l in that a program is bothcompiled
and interpreted. With the compiler, first you translate a program
into an intermediatelanguage called Java bytecodes the
platform-independent codes interpreted by the interpreteron the
Java platform. T he interpreter parses and runs each Java bytecode
instruction on thecomputer. Co mpilation happens just once;
interpretation occurs each time the program isexecuted. T he
following figure illustrates how this works.
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 development tool or a Web browser that can
runapplets, is an implementation of the Java VM.
Java bytecodes help make "write once, run anywhere" possible.
You can compile your programinto bytecodes on any platform that has
a Java compiler. The bytecodes can then be run on anyimplementation
of the Java VM. That means that as long as a computer has a Java
VM, thesame program written in the Java programming language can
run on Windows 2000, a Solaris
-
7/22/2019 SCJP Guide
6/167
workstation, or on an iMac.
Java was designed to be easy for the professional programmer to
learn and use effectively.
Java frees you from having to worry about many of the most
common causes of programmingerrors.
Because Java is a strictly typed language, it checks your code
at compile-time. It also checks thecode at run-time.
Java virtually eliminates the memory access by managing memory
allocation and deallocation. Infact, deallocation is completely
automatic, because Java provide Garbage Collection for
unusedobjects.
Java supports multithreaded programming which allows you to
write programs that do manythings simultaneously. The Java runtime
system comes with an elegan t yet sophisticatedsolution for
multiprocess synchronization that enables you to construct smoothly
runninginteractive systems.
Operating system upgrades, processor upgrades and changes in
core system resources can allcombine to make a program malfunction.
The Java designers made several hard decisions in theJava language
and Java Virtual Machine in an attempt to alter this situation,
thus making Javaarchitecture neutral.
Java is designed for the distributed environment of the
Internet, because it handles TCP/IPprotocols. Accessing a resource
using a URL is not much different from accessing a file.
Java supports dynamic programming where small fragments of
bytecode may be dynamicallyupdated on a running system.
1.7 Java Applets and Applications
The most common types of programs written in the Java
programming language are applets andapplications. An applet is a
program that adheres to certain conventions that allow it to run
withi na Java-enabled browser. An applet is an application designed
to be transmitted over the Internetand executed by a
Java-compatible Web browser.
An application i s a standalone program that runs directly on
the Java platform. A speci al kind ofapplication known as a
serverserves and supports clients on a network. Examples of
serversare Web servers, proxy servers, mail servers, and print
servers. Another special ized program is aservlet. A servlet can
almost be thought of as an applet that runs on the server side.
JavaServlets are a popular choice for building interactive web
applications, replacing the use of CGIscripts. Se rvlets are
similar to applets in that they are runtime extensions of
applications. Insteadof working in browsers, though, servlets run
within Java Web servers, configuring or tailoring theserver.
1.8 Why Java is important to Internet?
Java provides a firewall between a networked application and
your computer. When you use aJava-compatible web browser, you can
safely download Java applets without fear of viralinfection or
malicious intent. Java achieves this protection by confining a Java
program to theJava execution environment and not allow ing it
access to other parts of the computer. Anotherreason why Java is
important to Internet is due to its portability i. e. Write once
run anywherefeature.
With Java technology, the Internet and private networks become
your computing environment.Coupled with the power of networking,
the Java platform is helping computer users to do thingsthat were
previously unimaginable. For example, users can securely access
their personalinformation and applications when they're far away
from the office by using any computer that'sconnected to the
Internet; soon they'll be able to access tailored applications from
a mobilephone based on the Java platform, or even use smart cards
as a pass key to everything from thecash machine to ski lifts.
Why Java technology? Networks require software that is portable,
modular, and secure -- allareas where Java technology shines,
because it was designed for use on networks from thebeginning.
Businesses are using Java technology because it connects easily
to existing computing systems,lowers computing costs, and speeds
software development. It also lets businesses use theInternet to
securely connect to their customers, suppliers and partners.
And consumers benefit from Java technology because it brings
personal, business, andentertainment services to them -- easily and
securely -- in many locations and on many differentkinds of
appliances and devices at home, at work and on the road.
1.9 The Java Platform
A Javaplatform is the software environment in which a program
runs.
The Java platform has two components:
The Java Virtual Machine (Java VM)The Java Application
Programming Interface (Java API)
The compiler, javac, takes your source file and translates its
text into instructions that the JavaVirtual Machine (Java VM) can
understand. T he compiler converts these instructions into
abytecode file.
The Java interpreter installed on your computer implements the
Java VM. This interpreter takesyour bytecode file and carries out
the instructions by translating them into instructions that
yourcomputer can understand.
The Java compiler and interpreter are case-sensitive.
The Java API is a large collection of ready-made software
components that provide many usefulcapabiliti es, such as graphical
user interface (GUI) widgets. The Java API is grouped intolibraries
of related classes and interfaces; these libraries are known as
packages.
The followi ng figure depicts a program that's running on the
Java platform. As the figure shows,
the Java API and the virtual machine insulate the program from
the hardware.
Native code is code that after you compile it, the compiled code
runs on a specific hardwareplatform. As a platform-independent
environment, the Java platform can be a bit slower than
-
7/22/2019 SCJP Guide
7/167
native code. However, smart compilers, well-tuned interpreters,
and just-in-time bytecodecompilers can bring performance close to
that of native code without threatening portability.
1.10 What Can Java Technology Do?
Every full implementation of the Java platform 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 applets.Networking:
URLs, TCP (Transmission Control Protocol), UDP (User Datagram
Protocol)sockets, and IP (Internet Protocol)
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
appropriatelanguage.Security: Both low level and high level,
including electronic signatures, public and privatekey management,
access control, and certificates.
Software components: Known as JavaBeansTM, can plug into
existing componentarchitectures.Object serialization: Allows
lightweight persistence and communication via RemoteMethod
Invocation (RMI).
Java Database Connectivity (JDBCTM): Provides uniform access to
a wide range ofrelational databases.
The Java platform also has APIs for 2D and 3D graphics,
accessibility, servers, collaboration,telephony, speech, animation,
and more.
Java 2 Runtime Environment (JRE) consists of the virtual
machine, the Java platform coreclasses, and supporting files. The
Java 2 SDK includes the JRE and development tools such ascompilers
and debuggers.
Applicationsare standalone programs.
1.11 Writing a Program
The easiest way to write a simple program is with a text editor.
So, using the text editor of yourchoice, create a text file with
the following text, and be sure to name the text
fileExampleProgram.java. Java programs are case sensitive, so if
you type the code in yourself, payparticular attention to the
capitalization.
//A Very Simple Example
class ExampleProgram {
public static void main(String[] args){
System.out.println("I'm a Simple Program");
}
}
1.12 Compiling the Program
A program has to be converted to a form the Java VM can
understand so any computer with aJava VM can interpret and run the
program
The Java compiler is invoked at the command line on Unix and DOS
shell operating systems asfollows:
javac ExampleProgram.java
1.13 Interpreting and Running the Program
Once your program successfully compiles into Java bytecodes, you
can interpret and runapplications on any Java VM, or interpret and
run applets in any Web browser with a Java VMbuilt in such as
Netscape or Internet Explorer. Interpreting and running a Java
program meansinvoking the Java VM byte code interpreter, which
converts the Java byte codes to platform-dependent machine codes so
your computer can understand and run the program.
The Java interpreter is invoked at the command line on Unix and
DOS shell operating systemsas follows:
java ExampleProgram
At the command line, you should see:
I'm a Simple Program
1.14 Comments in Java
Code comments are placed in source files to describe what is
happening in the code to someonewho might be reading the file, to
comment-out lines of code to isolate the source of a problem
fordebugging purposes, or to generate API documentation. To these
ends, the Java languagesupports three kinds of comments: double
slashes, C-style, and doc comments.
Double Slashes
Double slashes (//) are used in the C/C++ programming language,
and tell the compiler to treateverything from the slashes to the
end of the line as text.
//A Very Simple Example
class ExampleProgram {
public static void main(String[] args){
System.out.println("I'm a Simple Program");
}
}
C-Style Comments
Instead of double slashes, you can use C-style comments (/* */)
to enclose one or more lines ofcode to be treated as text.
/* These are
C-style comments
*/
class ExampleProgram {
public static void main(String[] args){
System.out.println("I'm a Simple Program");
}
}
Doc Comments
To generate documentation for your program, use the doc comments
(/** */) to enclose lines of
-
7/22/2019 SCJP Guide
8/167
text for the javadoc tool to find. T he javadoc tool locates the
doc comments embedded in sourcefiles and uses those comments to
generate API documentation.
/** This class displays a text string at
* the console.
*/
class ExampleProgram {
public static void main(String[] args){
System.out.println("I'm a Simple Program");
}
}
With one simple class, there is no reason to generate API
documentation. API documentationmakes sense when you have an
application made up of a number of complex classes that
needdocumentation. The tool generates HTML files (Web pages) that
describe the class structures
and contain the text enclosed by doc comments.
1.15 Application Structure and Elements
An application i s created from classes. A class is similar to a
RECORD in the Pascal lan guageor a struct in the C language in that
it stores related data in fields, where the fields can bedifferent
types. So you could, for example, store a text string in one fiel
d, an integer in anotherfield, and a floating point in a third
field. The difference between a class and a RECORD or structis that
a class also defines the methods to work on the data.
For example, a very simple class might store a string of text
and define one method to set thestring and another method to get
the string and print it to the console. Methods that work on
thedata are called accessor methods.
Every application need s one class with a main method. This
class is the entry point for theprogram, and is the class name
passed to the java interpreter command to run the application.
The code in the main method executes first when the program
starts, and is the control point fromwhich the controller class
accessor methods are called to work on the data.
It has no fields or accessor methods, but because it is the only
class in the program, it has a main
method.
The public static void keywords mean the Java virtual machine
(JVM) interpreter can call theprogram's main method to start the
program (public) without creating an instance of the class(static),
and the program does not return data to the Java VM interpreter
(void) when it ends.
Summary
In this chapter you learnt the history of Java and how the Java
language has evolved. Java is notonly a programming language its a
platform. Java is important because of its
cross-platformfunctionality. Also Java is a secure language. Java
can be used for simple as well as complexapplications. It can be
used for embedded as well as mobile applications.
Chapter 2 : Data types, variables and Arrays
2.1 Data Types
The Java programming language has two categories of data
types:primitive and reference. Avariable of primitive type contains
a single value of the appropriate size and format for its type:
anumber, a character, or a boolean value.
Arrays, classes, and interfaces are reference types. The value
of a reference type variable, incontrast to that of a primitive
type, is a reference to (an address of) the value or set of
valuesrepresented by the variable.
A reference is called a pointer, or a memory address in other
languages. The Java programminglanguage does not support the
explicit use of addresses like other languages do. Yo u use
thevariable's name instead.
Primitive Data Types
Keyword Description Size/Format
(integers)byte B yte -l ength i ntege r 8 -b it tw o' s c omp
lementshort 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 orfalse)true or false
You can put a literal primitive value directly in your code.
int anInt = 4;
Range of primitive data types
Primitive TypeSize Range of Values
byte 8 bit -27 to 27-1
short 16 bit-215 to 215-1
int 32 bit-231 to 231-1
long 64 bit-263 to 263-1
char 16 bit'\u0000' to '\uffff'(0 to 216-1 )
float 32 bitMax. positi ve value: (2-2-23)*2127. Min. positive
value: 2-149
double 64 bitMax. positi ve value: (2-2-52)*21023. Min. positive
value: 2-1074
2.2 Literals
A specific primitive value in a li ne of code is called a
literal . These will be translated i nto valuesby the compiler and
inserted into the byte code.
Examples of Literal Values and Their Data Types
Literal Data Type
178 int
8864L long37.266 double
37.266D double87.363F float
26.77e3 double
'c' chartrue boolean
false boolean
A series of digits with no decimal poi nt is typed as an
integer. You can specify a long integer byputting an 'L' or 'l'
after the number. 'L' is preferred as it cannot be confused with
the digit '1'. Aseries of digits with a decimal poin t is of type
double. You can specify a float by putting an 'f' or'F' after the
number. A literal character value is any single Unicode character
between singlequote marks. The two boolea n literals are simply
true and false.
Constructing literal numeric values using octal and hexadecimal
formats.
Octal literals begin with zero e.g. 01 3042 (and obviously only
digits 0-7 are allowed).Hexadecimal literals begi n with zero and
an 'x' e.g. 0x23e4A (digits allow ed are 0-9 and a to f,the 'x' and
the letters can be upper or lower case).
Construct a literal value of char type using Java's unicode
escape format for a specified
-
7/22/2019 SCJP Guide
9/167
character code.
Use \u followed by four hexadecimal digits representing the 16
bit unicode character e.g.
char x='\u1234'
Java also supports certain escape codes for special characters
such as '\n' for newline.
2.3 Java Character Encoding: UTF and Unicode
Java uses two closely related encoding systems UTF and Unicode.
Java was designed from theground up to deal with multibyte
character sets and can deal with the vast numbers of charactersthat
can be stored using the Unicode character set. Unicode characters
are stored in two byteswhich allows for up to 65K worth of
characters. This means it can deal with Japanese Chinese,and just
about any other character set known.
Although Unico de can represent almost any character you would
ever likely to use it is not anefficient coding method for
programming. Most of the text data within a program uses
standardASCII, most of which can easily be stored within one byte.
For reasons of compactness Javauses a system called UTF-8 for
string literals, identifiers and other text within programs. This
canresult in a considerable saving by comparison with using Unicode
where every character
requires 2 bytes.
2.4 EscapeSequences
\b /* \u0008: backspace BS */
\t /* \u0009: horizontal tab HT */
\n /* \u000a: linefeed LF */
\f /* \u000c: form feed FF */
\r /* \u000d: carriage return CR */
\" /* \u0022: double quote " */
\' /* \u0027: single quote ' */
\\ /* \u005c: backslash \ */
OctalEscape /* \u0000 to \u00ff: from octal value */
2.5 Rules for naming an identifier
When we learn to program we have to give names or identifiers to
things we create such as files,classes, objects, variables and
attributes (attributes could be numbers, words or even
objects).There are rules which govern what is allowable.
Identifiers must be chosen according to certain rules:
they can contain letters, numbers, the underscore character ( _
) or dollar character ($)they cannot start with a number
they must not include spaces, other special characters or
punctuation marksa Java keyword must not be used.
A convention that is sometimes adopted to make identifiers more
readable is to use a capitalletter to indicate the beginning of a
new word, for example: cubeRoot, firstNumber, this issometimes
called camel hump notation.
Note that Java is case sensitive so A1 and a1 are different
identifiers.
Naming Conventions
Class identifiers begin with a capital letter.
The filename for the class code is the same as the name of the
class, e.g. the code for the classJTRectangle is stored in the file
JTRectangle.java.
Object identifiers start with a lowercase letter.
Attributes identifiers start with a lowercase letter.
2.6 Java Language Keywords
true, false, and null are not keywords but they are reserved
words, so you cannot use them asnames in your programs either.
abstractdouble int strictfp **b oo le an E ls e i nt er fa ce su
pe r
break extends long switchbyte Final native synchronized
case finally new this
catch Float package throw
char For private throws
class goto * protectedtransient
const * If public trycontinueimplementsreturn void
default import short volatile
do instanceof static while
enum****assert***
* indicates a keyword that is not currently used** indicates a
keyword that was added for Java 2
*** new in J2SE 1.4
**** new in J2SE 5.0
2.7 Variables
A variable is an item of data named by an identifier. You must
explicitly provide a name and atype for each variable you want to
use in your program. The variable's name must be a
legalidentifier--an unlimited series of Unicode characters that
begins with a le tter. Yo u use thevariable name to refer to the
data that the variable contains. The variable's type determines
whatvalues it can hold and what ope rations can be performed on it.
To give a variable a type and aname, 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 has scope.
Every variable must have a data type. A variable's data type
determines the values that thevariable can contain and the ope
rations that can be performed on it. Integers can contain
onlyintegral values (both positive and negative). You can perform
arithmetic operations, such asaddition, on integer variables.
Variable names begin with a lowercase letter, and class names
begin with an uppercase letter. Ifa variable name consists of more
than one word, the words are joined together, and each wordafter
the first begins with an uppercase letter, like this: isVisible.
The underscore character (_)is acceptable anywhere in a name, but
by convention is used only to separate words in constants(because
constants are all caps by convention and thus cannot be
case-delimited).
2.8 Declaring constants Final variables
You can declare a variable in any scope to be final. The value
of a final variable cannot changeafter it has been initial ized.
Such variables are similar to constants in other
programminglanguages.
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 in
itializes it, all at once. Subsequentattempts to assign a value to
aFinalVar result in a compiler error. You may, if necessary,
deferinitialization of a final localvariable. Simply declare the
local variable and initialize it later, likethis:
final int blankfinal;
. . .
-
7/22/2019 SCJP Guide
10/167
blankfinal = 0;
A final local variab le that has been declared but not yet
initial ized is called a blank final. Again,once a final local
variable has been initialized, it cannot be set, and any later
attempts to assign avalue to blankfinal result in a compile-time
error.
The following variable declaration defines a constant named PI,
whose value is pi, the ratio ofthe circumference of a circle to its
diameter (3.141592653589793) and cannot be changed:
final double PI = 3.141592653589793;
By convention, the name of constant values are spelled in
uppercase letters.
2.9 Arrays
An array is a structure that holds multiple val ues of the same
type. The l ength of an array isestablished when the array is
created (at runtime). After creation, an array is a
fixed-lengthstructure.
An array elementis one of the values within an array and is
accessed by its position within thearray.
Declaring an Array
This line of code from the sample program declares an array
variable:
int[] anArray; // declare an array of integers
Like declarations for variables of other types, an array
declaration has two components: thearray's type and the array's
name. An array's type is written type[], where type is the data
type ofthe elements contained within the array, and [] indicates
that this is an array. Remember that allof the elements within an
array are of the same type. The sampl e program uses int[], so
thearray called anArraywill be used to hold integer data. Here are
declarations for arrays that holdother types of data:
float[] anArrayOfFloats;
boolean[] anArrayOfBooleans;
Object[] anArrayOfObjects;
String[] anArrayOfStrings;
As with declarations for variables of other types, the
declaration for an array variable does notallocate any memory to
contain the array elements. T he sample program must assign a value
toanArraybefore the name refers to an array.
Creating an Array
You create an array explicitly using Java's new operator. The
next statement in the sampleprogram allocates an array with enough
memory for ten integer elements and assigns the array tothe
variable anArray declared earlier.
anArray = new int[10]; // create an array of integers
In general, when creating an array, you use the new operator,
plus the data type of the arrayelements, plus the number of
elements desired enclosed within square brackets ('[' and ']').
new elementType[arraySize]
If the new statement were omitted from the sample program, the
compiler would print an error likethe following one and compilation
would fail.
ArrayDemo.java:4: Variable anArray may not have been
initialized.
Accessing an Array Element
Now that some memory has been allocated for the array, the
program assigns values to the arrayelements:
anArray[2] = 10;
System.out.print(anArray[2] + " ");
This part of the code shows that to reference an array element,
either to assign a value to it, or toaccess the value, you append
square brackets to the array name. The val ue between the
squarebrackets indicates (either with a variable or some other
expression) the index of the element toaccess. Note that in Java,
array indices begin at 0 and end at the array length minus 1.
Getting the Size of an Array
To get the size of an array, you write
arrayname.length
Be careful: Programmers new to the Java programming language are
tempted to follow lengthwith an empty set of parenthesis. This
doesn't work because length is not a method. length is aproperty
provided by the Java platform for all arrays.
Array Initializers
The Java programming language provides a shortcut syntax for
creating and initializing an array.Here's an example of this
syntax:
boolean[] answers = { true, false, true, true, false };
The length of the array is determined by the number of values
provided between { and }.
Before initialization arrays are always set to contain default
values wherever they are created.
-
7/22/2019 SCJP Guide
11/167
2.10 Multidimensional Arrays
A multi-dimensional arrayof dimension n (i.e., an n-dimensional
array or simply n-D array) is acollection of items which is
accessed via n subscript expressions
The Java programming language does not really support
multi-dimensional arrays. It does,however, support arrays of
arrays. In Java, a two-dimensional array x is really an array of
one-dimensional arrays:
int[][] x = new int[3][5];
When you allocate memory for multidimensional array, you need
only specify the memory for thefirst (leftmost) dimension. You can
allocate remaining dimensions separately.
public class ArrayOfArraysDemo2 {
public static void main(String[] args) {
int[][] aMatrix = new int[3][];
//populate matrix
aMatrix[0]=new int[]{1};
aMatrix[1]=new int[]{2,3};
aMatrix[2]=new int[]{4,5,6};
}
}
2.11 Copying Arrays
Use System 's arraycopymethod to efficiently copy data from one
array into another. T hearraycopymethod requires five
arguments:
public static void arraycopy(Object source, int srcIndex, Object
dest,int destIndex, int length);
The two Object arguments indicate the array to copy from and the
array to copy to. T he threeinteger arguments indicate the starting
location in each the source and the destination array, andthe
number of elements to copy. Thi s diagram illustrates how the copy
takes place:
The following program, ArrayCopyDemo, uses arraycopy to copy
some ele ments from thecopyFrom array to the copyTo array.
public class ArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}
The arraycopymethod call in this example program begins the copy
at element number 2 in thesource array. R ecall that array indices
start at 0, so that the copy begins at the array element 'c'.The
arraycopymethod call puts the copied elements into the destination
array beginning at thefirst element (element 0) in the destination
array copyTo. The copy copies 7 elements: 'c', 'a', 'f', 'f','e',
'i', and 'n'. Effectively, the arraycopymethod takes the "caffein"
out of "decaffeinated", likethis:
Note that the destination array must be allocated before you
call arraycopyand must be largeenough to contain the data being
copied.
Summary
When you declare a variable, you explicitly set the variable's
name and data type. The Javaprogramming language has two categories
of data types: primitive and reference. A variable ofprimitive type
contains a value. The table in the Data Types section shows all of
the primitivedata types along with their sizes and formats. Arrays,
classes, and interfaces are reference types.
You can provide an initial value for a variable within its
declaration by using the assignmentoperator (=). You can declare a
variable as final. The value of a final variable cannot change
afterit's been initialized.
An array is a fixed-length data structure that can contain
multiple objects of the same type. Anarray can contain any type of
object, including arrays. To declare an array, you use the type
ofobject that the array can contain and brackets.
The length of the array must be specified when it is created.You
can use the new operator tocreate an array, or you can use an array
initializer. Once created, the size of the array cannotchange. To
get the length of the array, you use the length attribute.
An element within an array can be accessed by its index. Indices
begin a t 0 and end at the lengthof the array minus 1.
To copy an array, use the arraycopy method in the System
class.
Questions
1. class MCZ11 {
public static void main (String[] args) {
char a = '\c'; // 1
char b = '\r'; // 2
char c = '\"'; // 3
char d = '\b'; // 4
char e = '\''; // 5
}
-
7/22/2019 SCJP Guide
12/167
}
A compile-time error is generated at which line?
a. 1b. 2c. 3d. 4e. 5
f.None of theabove
2. class GRC4 {public static void main(String[] args) {}} //
1
class GRC5 {public static void main(String []args) {}} // 2
class GRC6 {public static void main(String args[]) {}} // 3
What is the result of attempting to compile and run the above
programs?
a. Compile-time error at line 1.b. Compile-time error at line
2.c. Compile-time error at line 3.
d.An attempt to run GRC4 from the command linefails.
e.An attempt to run GRC5 from the command linefails.
f.An attempt to run GRC6 from the command linefails.
g. None of the above
3. Which of these words belongs to the set of Java keywords?
a. qualifiedb. recordc. repeatd. restrictede. labelf. tog.
typeh. untili. valuej. virtualk. xor
l.None of theabove
4. class Identifiers {
int i1; // 1
int _i2; // 2
int i_3; // 3
int #i4; // 4
int $i5; // 5
int %i6; // 6
int i$7; // 7
int 8i; // 8
}
Compile-time errors are generated at which lines?
a. 1b. 2c. 3d. 4e. 5f. 6g. 7h. 8
5. Which of the following represent the full range of type
char?
a. '\u0000' to '\u7fff'b. '\u0000' to '\uffff'c. 0 to 32767d. 0
to 65535e. -32768 to 32767f. -65536 to 65535
6. class MWC101 {
public static void main(String[] args) {
int[] a1 = new int[]; // 1
int a2[] = new int[5]; // 2
int[] a3 = new int[]{1,2}; // 3
int []a4 = {1,2}; // 4
int[] a5 = new int[5]{1,2,3,4,5}; // 5
}
}
Compile-time errors are generated at which lines?
a. 1b. 2c. 3d. 4e. 5
7. class MWC201 {
public static void main(String[] args) {
int[][] a1 = {{1,2,3},{4,5,6},{7,8,9,10}};
System.out.print(a1[0][2]+","+a1[1][0]+","+a1[2][1]);
}
}
What is the result of attempting to compile and run the
program?
-
7/22/2019 SCJP Guide
13/167
a. Prints: 3,4,8b. Prints: 7,2,6c. Compile-time errord. Run-time
errore. None of the above
Chapter 3 : Operators
3.1 Operands
An operand can be:
a numeric variable - integer, floating point or characterany
primitive type variable - numeric and booleanreference variable to
an objecta literal - numeric value, boolean value, or string.an
array element, "a[2]"char primitive, which in numeric operations is
treated as an unsigned two byte integer
3.2 Operator
An operator performs a function on one, two, or three operands.
A n operator that requires oneoperand is called a unary operator.
For example, ++ is a unary operator that increments the valueof its
operand by 1. An operator that requires two operands is a binary
operator. For example, =is a binary operator that assigns the value
from its right-hand operand to its left-hand operand.And finally, a
ternary operatoris one that requires three operands. The Java
programminglanguage 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 theoperator appears before its
operand:
operator op //prefix notation
Postfix notation means that the operator appears afterits
operand:
op operator //postfix notation
All of the binary operators use infix notation, whi ch means
that the operator appears between itsoperands:
op1 operator op2 //infix notation
The ternary operator is also infix; each component of the
operator appears between operands:
op1 ? op2 : op3 //infix notation
In addition to performing the operation, an operator returns a
value. The return value and its typedepend 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-theresult of the arithmetic operation.
The data type returned by an arithmetic operator depends onthe type
of its operands: If you add two integers, you get an integer back.
An ope ration is said toevaluate to its result.
We divide the operators into these categories:
Arithmetic OperatorsIncrement and decrement operatorsRelational
Operators
Bitwise OperatorsLogical OperatorsAssignment
OperatorsConditional or ternary operator
3.2.1 Arithmetic Operators
The Java programming language supports various arithmetic
operators for all floating-point andinteger numbers. These
operators are + (addition), - (subtraction), * (multiplication), /
(division),and % (modulo).
The following table summarizes the binary arithmetic operations
in the Java programminglanguage.
Operator Use Description+ op1 + op2 Adds op1 and op2- op1 op2
Subtracts op2 from op1* op1 * op2 Multipliesop1 by op2
/ op1 / op2
Divides op1 by op2
If floating point arithmetic and op2 = 0.0, then
infinityreturned if op1 is not zero otherwise NaN if op1
iszero.ArthmeticException thrown if op1 & op2 are integer
types and op2 is zero.
% op1 % op2
Computes the remainder of dividing op1 by op2
If floating point arithmetic and op2 = 0.0 or infinity,then NaN
returnedArthmeticException thrown if op1 & op2 are integertypes
and op2 is zero.
public class ArithmeticDemo {
public static void main(String[] args) {
//a few numbers
int i = 37;
int j = 42;
double x = 27.475;
double y = 7.22;
System.out.println("Variable values...");
System.out.p rintln(" i = " + i);
System.out.p rintln(" j = " + j);
System.out.p rintln(" x = " + x);
System.out.p rintln(" y = " + y);
//adding numbers
System.out.println("Adding...");
System.out.p rintln(" i + j = " + (i + j));
System.out.p rintln(" x + y = " + (x + y));
//subtracting numbers
System.out.println("Subtracting...");
System.out.p rintln(" i - j = " + (i - j));
System.out.p rintln(" x - y = " + (x - y));
-
7/22/2019 SCJP Guide
14/167
//multiplying numbers
System.out.println("Multiplying...");
System.out.p rintln(" i * j = " + (i * j));
System.out.p rintln(" x * y = " + (x * y));
//dividing numbers
System.out.println("Dividing...");
System.out.p rintln(" i / j = " + (i / j));
System.out.p rintln(" x / y = " + (x / y));
//computing the remainder resulting from dividing numbers
System.out.println("Computing the remainder...");
System.out.p rintln(" i % j = " + (i % j));
System.out.p rintln(" x % y = " + (x % y));
//mixing types
System.out.println("Mixing types...");
System.out.p rintln(" j + y = " + (j + y));
System.out.p rintln(" i * x = " + (i * x));
}
}
Note that when an integer and a floating-point number are used
as operands to a singlearithmetic operation, the result is floating
poin t. Th e integer is implicitly converted to a floating-point
number before the operation takes place. The foll owing table
summarizes the data typereturned by the arithmetic operators, based
on the data type of the operands. Th e necessaryconversions take
place before the operation is performed.
Data Type ofResult
Data Type of Operands
longNeither operand is a float or a double (integer arithmetic);
at least oneoperand is a long.
intNeither operand is a float or a double (integer arithmetic);
neither operand isa long.
double At least one operand is a double.float At least one
operand is a float; neither operand is a double.
In addition to the binary forms of+ and -, each of these
operators has unary versions that performthe following
operations:
OperatorUse Description+ +op Promotes op to int if it's a byte,
short, orchar- -op Arithmetically negates op
3.2.2 Increment and Decrement Operators
Increment operator (++) increments its operand by 1, and
decrement operator ( --)decrements itsoperand by 1. Either++ or--
can appear before (prefix) or after (postfix) its operand. The
prefixversion, ++op/--op, evaluates to the value of the operand
afterthe increment/decrementoperation. The postfix version,
op++/op--, evaluates the value of the operand before
theincrement/decrement operation.
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-- --opDecrements op by 1; evaluates to the value of op
after it was decremented
3.2.3 Relational Operators
A relational ope rator compares two values and determines the
relationship between them. Forexample, != returns true if the two
operands are unequal. T his table summarizes the
relationaloperators:
Operator Use Returns true if
> op1 > op2 op1 is greater than op2>= op1 >= op2op1
is greater than or equal to op2< op1 < op2 op1 is less than
op2 j)); //false
System.out.p rintln(" j > i = " + (j > i)); //true
System.out.p rintln(" k > j = " + (k > j));
//false, they are equal
//greater than or equal to
System.out.println("Greater than or equal to...");
System.out.println(" i >= j = " + (i >= j)); //false
System.out.println(" j >= i = " + (j >= i)); //true
System.out.println(" k >= j = " + (k >= j)); //true
//less than
System.out.println("Less than...");
System.out.p rintln(" i < j = " + (i < j)); //true
System.out.p rintln(" j < i = " + (j < i)); //false
System.out.p rintln(" k < j = " + (k < j)); //false
//less than or equal to
System.out.println("Less than or equal to...");
System.out.println(" i
-
7/22/2019 SCJP Guide
15/167
System.out.println(" j
-
7/22/2019 SCJP Guide
16/167
Among other things, bitwise manipul ations are useful for
managing sets of boolean flags.
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) {
...
}
A program example is given below:
public class BitwiseDemo {
static final int VISIBLE = 1;
static final int DRAGGABLE = 2;
static final int SELECTABLE = 4;
static final int EDITABLE = 8;
public static void main(String[] args)
{
int flags = 0;
flags = flags | VISIBLE;
flags = flags | DRAGGABLE;
if ((flags & VISIBLE) == VISIBLE) {
if ((flags & DRAGGABLE) == DRAGGABLE) {
System.out.println("Flags are Visible and
Draggable.");
}
}
flags = flags | EDITABLE;
if ((flags & EDITABLE) == EDITABLE) {
System.out.println("Flags are now also Editable.");
}
}
}
3.2.5 Logical Operators
The relational operators you've learned so far (=, !=, ==) are
sufficient when you onlyneed to check one condition. However what
if a particular action is to be taken only if severalconditions are
true? You can use a sequence of if statements to test the
conditions, as follows:
if (x == 2) {
if (y != 2) {
System.out.println("Both conditions are true.");
}
}
This, however, is hard to write and harder to read. It only gets
worse as you add more conditions.Fortunately, Java provides an easy
way to handle multiple conditions: the logic operators. Thereare
three logic operators, &&, || and !.
&& is logical and. && combines two boolean
values and returns a boolean which is true if andonly if both of
its operands are true. For instance
boolean b;
b = 3 > 2 && 5 < 7; // b is true
b = 2 > 3 && 5 < 7; // b is now false
|| is logical or. || combines two boolean variables or
expressions and returns a result that is true ifeither or both of
its operands are true. For instance
boolean b;
b = 3 > 2 || 5 < 7; // b is true
b = 2 > 3 || 5 < 7; // b is still true
b = 2 > 3 || 5 > 7; // now b is false
The last logic operator is ! which means not. It reverses the
value of a boolean expression. Thusif b is true !b is false. If b
is false !b is true.
boolean b;
b = !(3 > 2); // b is false
b = !(2 > 3); // b i s true
These operators allow you to test multiple conditions more
easily. For instance the previousexample can now be written as
if (x == 2 && y != 2) {
System.out.println("Both conditions are true.");
}
The Order of Evaluation of Logic Operators
When Java sees a && operator or a ||, the expression on
the left side of the operator is evaluatedfirst. For example,
consider the following:
boolean b, c, d;
b = !(3 > 2); // b is false
c = !(2 > 3); // c is true
d = b && c; // d is false
When Java evaluates the expression d = b && c;, it first
checks whether b is true. Here b is false,so b && c must be
false regardless of whether c is or is not true, so Java doesn't
bother checkingthe value of c.
On the other hand when faced with an || Java short circuits the
evaluation as soon as itencounters a true value since the resulting
expression must be true. This short circuit evaluationis less
important in Java than in C because in Java the operands of
&& and || must be booleanswhich are unlikely to have side
effects that depend on whether or not they are evaluated. Still
it's
-
7/22/2019 SCJP Guide
17/167
possible to force them. For instance consider this code.
boolean b = (n == 0) || (m/n > 2);
Even if n is zero this line will never cause a division by zero,
because the left hand side is alwaysevaluated first. If n is zero
then the left hand side is true and there's no need to evaluate the
righthand side. Mathematically this makes sense because m/0 is in
some sense infinite which isgreater than two.
This isn't a perfect solution though because m may be 0 or it
may be negative. If m is negativeand n is zero then m/n is negative
infinity which is less than two. And if m is also zero, then m/n
isvery undefined.
Therefore if there's a real chance your program will have a
divide by zero error think carefullyabout what it means and how you
should respond to it. If, upon reflection, you decide that whatyou
really want to know is whether m/n is finite and greater than zero
you should use a line likethis
boolean b = (n != 0) && (m/n > 0);
The short circuit effect with logical operators
The logical operators (&& and ||) have a slightly
peculiar effect in that they perform "short-
circuited" logical AND and logical OR operations. The Java
approach makes sense if youconsider that for an AND, if the first
operand is false it doesn't matter what the second operandevaluates
to, the overall result will be false. Also for a logical OR, if the
first operand has turnedout true, the overall calculation will show
up as true because only one evaluation must return trueto return an
overall true. This can have an effect with those clever compressed
calculations thatdepend on side effects. Take the following
example.
public class MyClass1{
public static void main(String argv[]){
int Output=10;
boolean b1 = false;
if((b1==true) && ((Output+=10)==20))
{
System.out.println("We are equal "+Output);
}
else
{
System.out.println("Not equal! "+Output);
}
}
}
The output will be "Not equal 10". This illustrates that the
Output +=10 calculation was neverperformed because processing
stopped after the first operand was evaluated to be false. If
youchange the value of b1 to true processing occurs as you would
expect and the output is "We areequal 20";.
This may be handy sometimes when you really don't want to
process the other operations if anyof them return false, but it can
be an unexpected side effect if you are not completely familiar
withit.
Avoiding Short Circuits
If you want all of your boolean expressions evaluated regardless
of the truth value of each, thenyou can use & and | instead of
&& and ||. However make sure you use these only on
booleanexpressions. Unlike && and ||, & and | also have
a meaning for numeric types which iscompletely different from their
meaning for booleans.
3.2.6 Assignment Operators
You use the basic assignment operator, =, to assign one value to
another.
The Java programming language also provides several shortcut
assignment operators that allowyou to perform an arithmetic, shift,
or bitwise operation and an assignment operation all with
oneoperator. Suppose you wanted to add a number to a variable an d
assign the result back into thevariable, like this:
i = i + 2;
You can shorten this statement using the shortcut operator+=,
like this:
i += 2;
The two previous lines of code are equivalent.
x operation= y is equivalent to x = x operation y
x and y must be numeric or char types except for "=", which
allows x and y also to be objectreferences. In this case, x must be
of the same type of class or interface as y. If mixed
floating-point and integer types, the rules for mixed types in
expressions apply.
The following table lists the shortcut assignment operators and
their lengthy equivalents:
Operator Use Equivalent to+ = o p1 += op 2 o p1 = o p1 + o
p2
- = o p1 -= op 2 o p1 = o p1 - o p2
* = o p1 *= op 2 o p1 = o p1 * o p2
/ = o p1 /= op 2 o p1 = o p1 / o p2
% = o p1 %= op 2 o p1 = o p1 % o p2
& = o p1 &= op 2 o p1 = o p1 & o p2
| = o p1 |= op 2 o p1 = o p1 | o p2
^ = o p1 = op 2 o p1 = o p1 ^ o p2
> op2
>>>= op1 >>>= op2op1 = op1 >>>
op2
Other Operators
Operator Description?: Shortcut if-else statement. Cond itional
or ternary operator[] Used to declare arrays, create arrays, and
access array elements. Used to form qualified names
(params) Delimits a comma-separated list of parameters
(type) Casts (converts) a value to the specified typenew Creates
a new object or a new array
instanceofDetermines whether its first operand is an instance of
its second operand
3.2.7 Ternary or Conditional operator
The ?: operator is a conditional operator that is short-hand for
an if-else statement:
-
7/22/2019 SCJP Guide
18/167
op1 ? op2 : op3
The ?: operator returns op2 ifop1 is true or returns op3 ifop1
is false.
The value of a variable often depends on whether a particular
boolean expression is or is not trueand on nothing else. For
instance one common operation is setting the value of a variable to
themaximum of two quantities. In Java you might write
if (a > b) {
max = a;
}
else {
max = b;
}
Setting a single variable to one of two states based on a single
condition is such a common useof if-else that a shortcut has been
devised for it, the conditional operator, ?:. Using the
conditionaloperator you can rewrite the above example in a single
line like this:
max = (a > b) ? a : b;
(a > b) ? a : b; is an expression which returns one of two
values, a or b. The condition, (a > b), istested. If it is true
the first value, a, is returned. If it is false, the second value,
b, is returned.Whichever value is returned is dependent on the
conditional test, a > b. The condition can be anyexpression
which returns a boolean value.
The conditional operator only works for assigning a value to a
variable, using a value in amethod invocation, or in some other way
that indicates the type of its second and thirdarguments. For
example, consider the following
if (name.equals("Rumplestiltskin")) {
System.out.println("Give back child");
}
else {
System.out.println("Laugh");
}
This may not be written like this:
name.equals("Rumplestiltskin")
? System.out.println("Give back child")
: System.out.println("Laugh");
First of all, both the second and third arguments are void.
Secondly, no assignment is present toindicate the type that is
expected for the second and third arguments (though you know void
mustbe wrong).
The first argument to the conditional operator must have or
return boolean type and the secondand third arguments must return
values compatible with the value the entire expression can
beexpected to return. You can never use a void method as an
argument to the ? : operator.
3.2.8 The [ ] Operator
You use square brackets to declare arrays, to create arrays, and
to access a particular element inan array. Here's an example of an
array declaration:
float[] arrayOfFloats = new float[10];
The previous code declares an array that can hold ten floating p
oint numbers. Here's how you
would access the 7th item in that array:
arrayOfFloats[6];
Note that array indices begin at 0.
3.2.9 The . Op erator
The dot (.) operator accesses instance members of an object or
class members of a class.
3.2.10 The () Operator
When declaring or calling a method, you list the method's
arguments between ( and ). You canspecify an empty argument list by
using () with nothing between them.
3.2.11 The (type) Operator
Casts (or "converts") a value to the specified type.
3.2.12 The new Operator
You use the new operator to create a new object or a new array.
Here's an example of creating anew Integer object from the Integer
class in the java.langpackage:
Integer anInteger = new Integer(10);
3.2.13 The instanceof Operator
The instanceof operator tests whether its first operand is an
instance of its second.
op1 instanceof op2
op1 must be the name of an object and op2 must be the name of a
class. An obje ct is consideredto be an instance of a class if that
object directly or indirectly descends from that class.
3.3 Expressions
An expression produces a result and returns a value. Examples
include :
i = 2 : the assignment puts 2 into the i variable and returns
the value 2k++ : returns k, then k is incremented by 1x < y :
logical "less than" comparison, returns a Boolean true or false
valuei | j : returns the value of a bitwise OR operation on bits in
the two variables.
Expressions involve at least one operator. A single operator can
have 1, 2 or 3 operands.
3.4 Statements
A statement is essentially any complete sentence that causes
some action to occur. It canencompass multiple operators and
operands, as well as multiple sub-statements. For example,the
statement
int x = 1;
declares a variable x and then assigns the value 1 to it. This
statement
-
7/22/2019 SCJP Guide
19/167
x = 5.3 *(4.1 / Math.cos (0.2*y));
consists of several expressions - multiplication, division, a
method call to a math function - but isstill considered a single
statement.
3.5 Operator Precedence
Highest Precedence
()
++expr --expr +expr -expr ~ !
* / %
+ -
> >>>
< > = instanceof
== !=
&
^
|
&&
||
? :
= += -= *= /= %= &= ^= |= = >>>=
Lowest PrecedenceLowest Precedence
Overriding Operator Precedence
Parenthesis is used to override operator precedence.
Sometimes the default order of evaluation isn't what you want.
For instance, the formula tochange a Fahrenheit temperature to a
Celsius temperature is C = (5/9) (F - 32) where C isdegrees Celsius
and F is degrees Fahrenheit. You must subtract 32 from the
Fahrenheittemperature before you multiply by 5/9, not after. You
can use parentheses to adjust the ordermuch as they are used in the
above formula. The next program prints a table showing
theconversions from Fahrenheit and Celsius between zero and three
hundred degrees Fahrenheitevery twenty degrees.
// Print a Fahrenheit to Celsius table
class FahrToCelsius {
public static void main (String args[]) {
// lower limit of temperature table
double lower = 0.0;
// upper limit of temperature table
double upper = 300.0;
// step size
double step = 20.0;
double fahr = lower;
while (fahr
-
7/22/2019 SCJP Guide
20/167
The following operators have Right to Left associativity. All
otheroperators (see precedence table above) are evaluated left to
right.
=*=/=
%=+=-=
=
>>>=&=^=|=
?:new
(type cast)++x--x+x-x~
3.6 Type Conversion and Casting
Converting one type of data into another must follow the rules
of casting. If a conversion results inthe loss of precision, as in
an int value converted to a short, then the compiler will issue an
errormessage unless an explicit cast is made.
To convert type AA data into type BB data, put the type BB name
in parentheses in front of thetype AA data:
AA a = aData;BB b = (BB)a; // cast type AA to type BB
For example, to convert integer data to floating point:
int i=0;float f;f=(float)i; // Cast int as float
Expressions can promote to a wider type without an explicit
cast:
int i=1;long j=3L; // Literals are int types so require L
suffixj=i; // OK
However, you can not assign a value to a more narrow type
without an explicit cast:
i=j; // Error in assigning long to inti=(int)j; // OK
So a data type with lower precision (fewer bits) can be
converted to a type of higher precisionwithout explicit casting. To
convert a higher precision type to a lower precision, however,
anexplicit cast is required or the compiler will flag an error.
Note that when you cast a value of a wider type down to a more
narrow type, such as an int valueto a byte variable, the upper
bytes will be truncated. That is, the lowest order byte in the int
valuewill be copied to the byte value.
Primitive Type Conversion Table
Below is a table that indicates to which of the other primitive
types you can cast a given primitivedata type. The symbol C
indicates that an explicit cast is required since the precision
isdecreasing. The symbol A indicates that the precision is
increasing so an automatic cast occurswithout the need for an
explicit cast. N indicates that the conversion is not allowed.
int long float double char byte short booleanint - A A* A C C C
N
long C - A* A* C C C Nfloat C C - A C C C N
double C C C - C C C Nchar A A A A - C C Nbyte A A A A C - A
Nshort A A A A C C - N
boolean N N N N N N N -
The * asterisk indicates that the least significant digits may
be lost in the conversion even thoughthe target type allows for
bigger numbers. For example, a large value in an int type value
thatuses all 32 bits will lose some of the lower bits when
converted to float since the exponent uses 8bits of the 32 provided
for float values.
Mixed Types in an Expression
If an expression holds a mix of types, the lower precision or
narrower value operand is convertedto a higher precision or wider
type. This result then must be cast if it goes to a lower
precisiontype:
float x,y=3;int j,i=3;x= i*y; // OK since i will be promoted to
floatj= i*y; // Error since result is a float valuej= (int)(i*y) //
OK
The process of converting a value to a wider or higher precision
integer or floating point type iscalled "numeric promotion". The
Java VM specification states the following rules for promotion inan
expression of two operands, as in x+i:
If either operand is of type double, the other is converted to
double.Otherwise, if either operand is of type float, the other is
converted to float.Otherwise, if either operand is of type long,
the other is converted to long.Otherwise, both operands are
converted to type int.
The program below uses both ints and doubles, for example.
class IntAndDouble {
public static void main (String args[]) {
int i = 10;
double x = 2.5;
double k;
System.out.println("i is " + i);
System.out.println("x is " + x);
k = i + x;
System.out.println("i + x is " + k);
k = i * x;
System.out.println("i * x is " + k);
k = i - x;
System.out.println("i - x is " + k);
k = x - i;
System.out.println("x - i is " + k);
k = i / x;
System.out.println("i / x is " + k);
k = x / i;
System.out.println("x / i is " + k);
}
}
This program produces the following output:
i is 10
x is 2.5
i + x is 12.5
i * x is 25
i - x is 7.5
-
7/22/2019 SCJP Guide
21/167
x - i is -7.5
i / x is 4
x / i is 0.25
Order can make a difference when data types are mixed. For
example,
1 / 2 * 3.5 = 0.03.5 * 1 / 2 = 1.753.5 / 2 = 1.75
You cannot assume that the usual mathematical laws of
commutativity apply when mixing datatypes, especially integer and
floating point types.
1.0 / 2 * 3.5 = 1.753.5 * 1.0 / 2 = 1.751 / 2.0 * 3.5 = 1.753.5
* 1.0 / 2.0 = 1.75
3.7 Automatic Type Promotions
An int divided by an int is an i nt, and a double divide d by a
double is a double , but what about anint divided by a double or a
double divided by an int? When doing arithmetic on unlike types
Java tends to widen the types involved so as to avoid losing
information. After all 3 * 54.2E18 willbe a perfectly valid double
but much too big for any int.
The basic rule is that if either of the variables in a binary
operation (addition, multiplication,subtraction, addition,
remainder) are doubles then Java treats both values as doubles. If
neithervalue is a double but one is a float, then Java treats both
values as floats. If neither is a float or adouble but one is a
long, then Java treats both values as longs. Finally if there are
no doubles,floats or longs, then Java treats both values as an int,
even if there aren't any ints in the equation.Therefore the result
will be a double, float, long or int depending on the types of the
arguments.
In an assignment statement, i.e. if there's an equals sign, Java
compares the type of the left handside to the final type of the
right hand side. It won't change the type of the left hand side,
but it willcheck to make sure that the value it has (double, float,
int or long) on the right hand side can fit inthe type on the left
hand side. Anything can fit in a double. Anything except a double
can fit in afloat. Any integral type can fit in a long, but a float
or a double can't, and ints, shorts, and bytescan fit inside ints.
If the right hand side can fit inside the left hand side, the
assignment takesplace with no further ado.
Assigning lon g values to int variables or double val ues to
float variables can be equall ytroublesome. In fact it's so
troublesome the compiler won't let you do it unless you tell it you
reallymean it with a cast. When it's necessary to force a value
into a particular type, use a cast. To casta variable or a literal
or an expression to a different data type just precede it with the
type inparentheses. For instance:
int i = (int) (9.0/4.0);
A cast lets the compiler know that you're serious about the
conversion you plan to make.
When a value is cast down before assignment, series of
operations takes place to chop the righthand side down to size. For
a conversion between a floating point number and an int or a
long,the fractional part of the floating point number is truncated
(rounded toward zero). This produces
an integer. If the integer is small enough to fit in the left
hand side, the assignment is completed.On the other hand if the
number is too large, then the integer is set to the largest
possible value ofits type. If the floating point number is too
small the integer is set to the smallest possible value ofits
type.
This can be a nasty bug in your code. It can also be hard to
find since everything may workperfectly 99 times out of a hundred
and only on rare occasions will the rounding become aproblem.
However when it does there will be no warning or error message. You
need to be verycareful when assigning floating point values to
integer types.
Summary
This chapter discussed the operators that you can use in Java to
manipulate the values ofvariables. It included all the standard
arithmetic operators, the increment and decrementoperators, the
relational operators, the bit-wise operators, and the shift
operators. Finally itdiscussed the concept of operator precedence
that defined the rules by which the order ofoperators is
evaluated.
Questions
1. class GFM11{
public static void main (String[] args) {
int x,y,z;
System.out.println(x+y+z);
}
}
What is the result of attempting to compile and run the
program?
a. Prints nothing.
b.Prints an undefinedvalue.
c. Prints: nulld. Prints: 0e. Run-time errorf. Compile-time
errorg. None of the above
2. class EBH201 {
public static void main (String[] args) {
int a = 1 || 2 ^ 3 && 5;
int b = ((1 || 2) ^ 3) && 5;
int c = 1 || (2 ^ (3 && 5));
System.out.print(a + "," + b + "," + c);
}
}
What is the result of attempting to compile and run the
program?
a. Prints: 0,0,0b. Prints: 0,0,3c. Prints: 0,3,0d. Prints:
0,3,3e. Prints: 3,0,0f. Prints: 3,0,3g. Prints: 3,3,0h. Prints:
3,3,3i. Run-time errorj. Compile-time errork. None of the above
3. class MCZ24 {
public static void main (String[] args) {
char a = 061; // 1
char b = '\61'; // 2
char c = '\061'; // 3
char d = 0x0031; // 4
char e = '\u0031'; // 5
System.out.print(""+a+b+c+d+e);
}
}
A compile-time error is generated at which line?
a. 1
-
7/22/2019 SCJP Guide
22/167
b. 2c. 3d. 4e. 5
f.None of theabove
4. class EBH012 {
public static void main (String[] args) {
byte x = 3, y = 5;
System.out.print((-x == ~x + 1)+","+(-y == ~y + 1));
}
}
What is the result of attempting to compile and run the
program?
a. Prints: false,falseb. Prints: false,truec. Prints:
true,falsed. Prints: true,truee. Run-time errorf. Compile-time
errorg. None of the above
5. class EBH007{
public static void main (String[] s) {
byte b = 5; System.out.println(b
-
7/22/2019 SCJP Guide
23/167
Chapter 4 : Control flow statements
Without control flow statements, the interpreter executes these
statements in the order theyappear in the file from left to right,
top to bottom. You can use control flow statements in yourprograms
to conditionally execute statements, to repeatedly execute a block
of statements, and tootherwise change the normal, sequential flow
of control.
Statement Type Keyword
looping while, do-while , for
decision making if-else, switch-case
branching break, continue , label:, return
exception handlingtry-catch-finally, throws,throw
In the sections that follow, you will see the following notation
to describe the general form of acontrol flow statement:
control flow statement details {
statement(s)
}
Technically, the braces, { and }, are not required if the block
contains only one statement.However, we recommend that you always
use { and }, because the code is easier to read and ithelps to
prevent errors when modifying code.
4.1 The while and do-while Statements
You use a while statement to continually execute a block of
statements while a condition remainstrue. T he general syntax of
thewhile statement is:
while (expression) {
statement
}
First, the while statement evaluates expression, which must
return a boolean value. If theexpression returns true, then the
while statement executes the statement(s) associated with it.The
while statement continues testing the expression and executing its
block until the expressionreturns false.
public class WhileDemo {
public static void main(String[] args) {
int x=10;
while (x != 0) {
System.out.println(x--);
}
}
}
This program prints numbers from 10 to 1 in the descending
order
The Java programming language provides another statement that is
similar to the whilestatement--thedo-while statement. The gen eral
syntax of the do-while is:
do {
statement(s)
} while (expression);
Instead of evaluating the expression at the top of the loop,
do-while evaluates the expression atthe bottom. T hus the
statements associated with a do-while are executed at least
once.
public class DoWhil