OCP-Java-11-Programmer-I-1Z0-815-Fundamentals-Study-Guide
OCP-Java-11-Programmer-I-1Z0-815-Fundamentals-Study-Guide
1Z0-815
Hanumant Deshmukh
Hanumant Deshmukh
4A Agroha Nagar, A B Road,
Dewas, MP 455001
INDIA
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by
any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under the
relevant laws of copyright, without the prior written permission of the Author. Requests for permission should be
addressed to [email protected]
Limit of Liability/Disclaimer of Warranty: The author makes no representations or warranties with respect to the
accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limi-
tation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional
materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with
the understanding that the author is not engaged in rendering legal, accounting, or other professional services. If
professional assistance is required, the services of a competent professional person should be sought. The author shall
not be liable for damages arising herefrom. The fact that an organization or website is referred to in this work as
a citation and/or a potential source of further information does not mean that the author endorses the information
the organization or Web site may provide or recommendations it may make. Further, readers should be aware that
Internet Web sites listed in this work may have changed or disappeared between when this work was written and
when it is read.
TRADEMARKS: Oracle and Java are registered trademarks of Oracle America, Inc. All other trademarks are the
property of their respective owners. The Author is not associated with any product or vendor mentioned in this book.
Finally, I am also thankful for the following readers for their help in improving the content of this
book through suggestions and by reporting errors:
1. Zheng-Yu Wang
I believe you have already got your feet wet with Java programming and are now getting serious
about your goal of being a professional Java programmer. First of all, let me commend your decision
to consider Java certification as a step towards achieving that goal. I can assure you that working
towards acquiring Oracle’s Java Certification will be very rewarding. Irrespective of whether
you get extra credit for being certified in your job hunt or not, you will be able to speak with
confidence in technical interviews and the concepts that this certification will make you learn, will
improve your performance on the job.
The Java SE 11 Programmer I exam (Exam code 1Z0-815), aka OCPJP-I exam, is the first
of the two exams that you need to pass in order to become an Oracle Certified Professional - Java
SE 11 Developer. This exam focuses on the fundamental aspects of Java and is not particularly
tough to pass. If you go through a decent book and practice a few good mock exams, you should
be able to pass it with a couple of months of preparation. However, the topics covered in this
certification form the groundwork for the second step of professional certification, i.e., the Java SE
11 Programmer II exam (Exam code 1Z0-816), aka OCPJP-II exam. The OCPJP-II is a very
tough exam. It is a lot tougher than the OCPJP-I exam. You will have trouble passing that exam
if your fundamentals are weak. For this reason, it is very important to not think of just passing
the OCPJP-I exam with the bare minimum marks required (63%) but to set a score of 90% as your
target. My objective with this book is to help you achieve 90% plus score on the OCPJP-1 exam.
team from our website Enthuware.com. It is priced quite reasonably (only 9.99 USD) and has stood
the test of time.
0.1 Who is this book for? iii
3. Do you know basic OS commands such as dir, cd, and mkdir (or if you are a Linux/Mac user
- Do you know how to use ls, cd, and md)?
4. Can you write a simple Hello World program in Java and run it from the command line?
6. Do you know what loops (such as for loop and while loop) are and what they are used for?
If you answered no to any of the above, this book is not for you. It would be better if you
go through a programming book or a computer book for beginners first, and then come back to
this book. Alternatively, be open to google a term if you are not sure about it at any time before
proceeding further while reading this book.
1. Focus on concepts - I believe that if you get your basic concepts right, everything else
falls in place nicely. While working with Java beginners, I noticed several misconceptions,
misunderstandings, and bad short cuts that would affect their learning of complex topics
later. I have seen so many people who manage to pass the exam but fail in technical interviews
because of this reason. In this book, I explain the important stuff from different perspectives.
This does increase the length of the book a bit but the increase should be well worth your
time.
iv Chapter 0. Introduction
2. No surgical cuts - Some books try to stick very close to the exam objectives. So close that
sometimes a topic remains nowhere close to reality and the reader is left with imprecise and,
at times, incorrect knowledge. This strategy is good for answering multiple choice questions
appearing on the OCPJP-I exam but it bites the reader during technical interviews and while
writing code on the job. I believe that answering multiple choice questions (MCQs) should
not be your sole objective. Learning the concepts correctly is equally important. For this
reason, I go beyond the scope of exam objectives as, and when, required. Of course, I mention
it clearly while doing so.
3. Exercises - “Write a lot of code” is advice that you will hear a lot. While it seems quite
an easy task for experienced programmers, I have observed that beginners are often clueless
about what exactly they should be writing. When they are not sure about what exactly a test
program should do, they skip this important learning step altogether. In my training sessions,
I give code writing exercises with clear objectives. I have done the same in this book. Instead
of presenting MCQs or quizzes at the end of a topic or chapter, I ask you to write code that
uses the concepts taught in that topic or chapter.
Besides, a question in the real exam generally requires knowledge of multiple topics. The
following is a typical code snippet appearing in the exam:
int i = 10;
Long n = 20;
float f = 10.0;
String s = (String) i+n++;
To determine whether this code compiles or not, you need to learn four topics - wrappers,
operators, String class, and casting. Thus, presenting an MCQ at the end of a topic, that
focuses only on that one topic, creates a false sense of confidence. I believe it is better to
focus on realistic MCQs at the end of your preparation.
4. Not being pedantic - If you are preparing for the OCPJP-I exam, I believe you have
already been through many academic exams in your life. You already know what to expect
in an exam. So, I won’t advise you on the amount of water you should drink before the
exam to avoid a restroom break, or on how much sleep you should get before the exam, or to
check the exam center location a day before. If you have not taken any computer-based exam
containing multiple choice questions, I strongly suggest you use Enthuware’s exam simulator
to get familiar with this style. It closely mimics the user interface of the real exam.
concept better when you actually type the code instead of just reading it. If you have already had
a few years of Java development experience, you may go through the chapters in any order.
This book uses certain typographic styles in order to help you quickly identify important informa-
tion. These styles are as follows:
Code font - This font is used to differentiate between regular text and Java code appearing within
regular text. Code snippets containing multiple lines of code are formatted as Java code within
rectangular blocks.
Red code font - This font is used to show code that doesn’t compile. It could be because of
incorrect syntax or some other error.
Output code font - This font is used to show the output generated by a piece of code on the
command line.
Bold font - I have highlighted important words, terms, and phrases using bold font to
help you mentally bookmark them. If you are cruising through the book, the words in bold will
keep you oriented besides making sure you are not missing anything important. Note -
Note
Things that are not completely related to the topic at hand are explained in notes. I have used
notes to provide additional information that you may find useful on the job or for technical
interviews but will most likely not be required for the exam.
Exam Tip:
Exam Tip
Exam Tips contain points that you should pay special attention to during the exam. I have
also used them to make you aware of the tricks and traps that you will encounter in the exam.
If you need any clarification, have any doubt about any topic, or want to report an error, feel free
to ask on our dedicated forum for this book - http://enthuware.com/forum. If you are reading this
book on an electronic device, you will see this icon beside every topic title. Clicking on this icon
will take you to an existing discussion on that particular topic in the same forum. If the existing
discussion addresses your question, great! You will have saved time and effort. If it doesn’t, post
your question with the topic title in the subject line. We use the same mechanism for addressing
concerns about our mock exam questions and have received tremendous appreciation from the users
about this feature.
vi Chapter 0. Introduction
1. While discussing a rule of the language, I may have to refer to some terms and concepts for
the sake of completeness and technical accuracy. For example, let’s say we are talking about
public classes in a file. If I state that you cannot have more than one public class in a file,
it is fine for the purpose of the exam but it is technically incorrect because you can have any
number of public nested classes in a file. Thus, it would be better to state that you cannot
have more than one top-level class in a file. How about one public top-level class and one
public interface? Nope, you can’t do that either. Thus, the statement is still incorrect. The
correct statement would be that you cannot have more than one public top-level reference
type in a file. As you can see, it is imperative for me to mention the meaning of the terms
reference type, nested class, and top level class, even though you won’t be tested on them in
the exam. If you absolutely do not want to spend any time learning about anything that is
not part of the exam, then this book is not for you. I have tried to stick to the objectives
as much as possible but, if I believe you need to know something, I talk about it even if it is
beyond the scope of the exam.
2. I have noticed that many of the certification aspirants are new Java programmers who
are either in school or want to start their career with Java programming. They want to
get certified because they ultimately want to land a job as a Java programmer. These
programmers will be facing a lot of technical interviews as well. I want these programmers
to do well on technical interviews.
Certification may get you a foot in the door but you will need to back it up with
strong knowledge of fundamentals in the interview. Therefore, if I believe that something
is important for you to know or that something will be helpful to you in your technical
interview, irrespective of whether it will be asked in the exam or not, I discuss it.
3. Official exam objectives are neither detailed nor exhaustive. They list top level topics that
you need to study but leave out finer details. You will be asked questions that require you to
know those concepts.
4. Oracle adds new questions to the exam before formally adding a new topic in the official
exam objectives. These questions may not be included in your final score, i.e., your answers
on such questions are not counted towards your score on the exam. However, test takers
do not know if a question is unscored and so, they must attempt it as if it will be counted
towards their final score.
Since we, at Enthuware, conduct classroom training as well, we get to interact with a
lot of test takers. We receive feedback from test takers about getting questions on topics that
0.5 General tips for the exam vii
are not there in the exam objectives. After receiving such multiple reports, we may decide to
add that topic to our content. We clearly specify the reason for their inclusion.
5. Official exam objectives are not constant. Although not frequently, Oracle does add and
remove topics from the objectives from time to time. This may render some of the content
not relevant for the exam. I will update the content as soon as possible.
If you are interested in getting your basics right, then I suggest you do not worry too much about
the exam objectives while following this book. Even if you spend a little more time (not more than
10%, I promise) in your preparation because of this extra content, it will be worth your while.
1. Code Formatting - You may not find nicely formatted code in the exam. For example, you
may expect a piece of code nicely formatted like this:
if(flag){
while(b<10){
}
}else if(a>10) {
invokeM(a);
}
else{
System.out.println(10);
}
But you may get the same code formatted like this:
if(flag){
while(b<10){ }
} else
if(a>10) { invokeM(a); }
else { System.out.println(10); }
They do this most likely to save space. But it may also happen inadvertently due to variations
in display screen size and resolution.
2. Assumptions - Several questions give you partial code listings, aka “code snippets”. For
example, what will the following code print?
ArrayList al = new ArrayList();
al.remove(0);
System.out.println(al);
Obviously, the code will not compile as given because it is just a code fragment. You have to
assume that this code appears in a valid context such as within a method of a class. You also
viii Chapter 0. Introduction
3. Tricky Code - You will see really weird looking code in the exam. Code that you may never
even see in real life. You will feel as if the exam is about puzzles rather than Java programming.
To some extent, that is correct. If you have decided to go through the certification, there is
no point in questioning the relevance. If you feel frustrated, I understand. Please feel free to
vent out your anger on our forum and get back to work!
4. Number of correct options - Every question in the exam will tell you exactly how many
options you have to select to answer that question correctly. Remember that there is no
negative marking. In other words, marks will not be deducted for answering a question
incorrectly. Therefore, do not leave a question unanswered. If you don’t know the answer,
select the required number of options anyway. There is a slight chance that you will have
picked the correct answer.
5. Eliminate wrong options - Even better than not leaving a question unanswered is make
intelligent guesses by eliminating obviously incorrect options. You may see options that are
contradictory to each other. This makes it a bit easy to narrow down the correct options.
That’s about it. Hope this book helps you become a better Java programmer besides getting
you the certification.
Exam Details
Duration: 180 Minutes
Number of Questions: 80
Passing Score: 63%
Format: Multiple Choice
Exam Price: USD 245 (varies by country)
Exam Objectives
Understanding Java Technology and environment
1. Declare and initialize variables (including casting and promoting primitive data types)
4. Utilize polymorphism to cast and call methods, differentiating object type versus reference
type
Handling Exceptions
1. Describe the advantages of Exception handling and differentiate among checked exceptions,
unchecked exceptions, and Errors
2. Create a try-catch block and determine how exceptions alter normal program flow
1. Use Java operators including the use of parenthesis to override operator precedence
2. Use Java control statements including if, else, break and continue
3. Create and use do/while loops, while loop, and for looping statements including nested loops
1. Declare and instantiate Java objects, and explain objects’ lifecycles (including creation, deref-
erencing by reassignment, and garbage collection)
Applying Encapsulation
Understanding Modules
thank you,
Hanumant Deshmukh
xii Chapter 0. Introduction
1. Kickstarter for Beginners
This section is for Java beginners. It does not directly relate to any exam objective but is meant
to provide a solid grounding that will help you to easily understand the concepts taught in later
chapters. The concepts covered in this section are important because they repeat over and over
throughout this book. If we get these repetitions over with now, you will be happier later on!
2 Chapter 1. Kickstarter for Beginners
This was unimaginable to me in the US, where everything just fits. I could buy a bolt
from one shop and a nut from another, and it would work perfectly. Everything, from screws, nuts,
and bolts, to wood panels, electrical parts, packing boxes, is standardized. One can easily replace
a part with another built by a totally different company. You just have to specify the right “size”.
This experience led me to a potential cause of why some OOP learners find OOP concepts
confusing. Especially, beginners from non-western background find it really tough to grasp the
fundamental concepts because they do not know the rationale behind so many rules of OOP. This
is reflected in their application design.
In the US, and I imagine in other developed countries as well, things are extremely well de-
fined. Products clearly specify how they should be used and in what cases they will fail. People
can and do rely on these specifications because products work as expected and fail as defined. At
the same time, people expect products to come with detailed specifications. Ready to assemble
furniture is a prime example of how detailed these specifications can be. It’s because of detailed
and clear specifications that people feel comfortable in buying complicated ready-to-assemble
furniture.
In short, people know exactly what they are getting when they acquire something. I think
of it as the society being naturally “object-oriented”.
Object orientation is just a name for the same natural sense of things fitting nicely with
each other. A piece of code is not much different from the physical things I mentioned earlier.
If you code it to a specification, it will fit just as nicely as your .16 inch nut on a .16 inch bolt,
irrespective of who manufactured the nut and who manufactured the bolt. The point here is that
the source of the concept of object-oriented programming is the physical world. If you want to
grasp OOP really well, you have to start thinking of your piece of code as a physical component...a
“thing” that has a well defined behavior and that can be replaced with another component that
adheres to the same behavior. You would not be happy if you bought a tire that doesn’t fit on
1.1 Key points in OOP 3
your car’s wheel even though you bought same ’size’, would you? You should think about the same
issues when you develop your software component. Someone somewhere is going to use it and they
won’t be happy if it fails at run time with an exception that you didn’t say it would throw in a
particular situation.
1.1.2 API
You probably know that API stands for Application Programming Interface. But do you
understand what it really means? This goes back to my previous observation about relating pro-
gramming concepts to real life. When you operate a switch do you really care about what exists
inside the switch? Do you really care how it works? You just connect the switch to a light bulb
and press it to switch the bulb on or off. It is the same with a car. A car provides you with a few
controls that allow you to turn, accelerate, and brake. These controls are all you need to know how
to drive a car.
You should think about developing software components in the same way. A software com-
ponent doesn’t necessarily mean a bunch of classes and packages bundled together in jar file. A
software component could be as simple as a single class with just one method. But while developing
even the smallest and the simplest of software components, you should think about how you expect
the users to use it. You should think about various ways a user can use the component. You should
also think about how the component should behave when a user doesn’t use it the way it is expected
to be used. In other words, you should specify an interface to your component, even before you
start coding for it. Here, by interface, I do not mean it in the strict sense of a Java interface but
a specification that details how to interact with your component. In a physical world, the user’s
manual of any appliance is basically its interface. In the software world, the specification of the
publicly usable classes, methods, fields, enums, et cetera of a software component is its interface.
As an application programmer, if you want to use a component developed by someone else, you
need to worry only about the interface of that component. You don’t need to worry about what
else it might contain and how it works. Hence the phrase ‘Application Programming Interface’.
In the Java world, a collection of classes supplied by a provider for a particular purpose is called
a library and the JavaDoc documentation for those classes describes its API. When you install the
Java Runtime Environment (JRE), it includes a huge number of classes and packages. These
are collectively called the standard Java library and the collection of its public classes and interfaces
is called the Java API.
The Java API contains a huge amount of ready-made components for doing basic programming
activities such as file manipulation, data structures, networking, dates, and formatting. When you
write a Java program, you actually build upon the Java API to achieve your goal. Instead of writing
all the logic of your application from scratch, you make use of the functionality already provided
to you, free of cost, by the Java library and only write code that is specific to your needs. This
saves a lot of time and effort. Therefore, a basic understanding of the Java API is very important
for a Java programmer. You don’t need to know by heart all the classes and their methods. It is
practically impossible to know them all, to be honest. But you should have a broad idea about
what the Java API provides at a high level so that when the need arises, you know where to look for
the details. For example, you should know that the standard Java library contains a lot of classes
for manipulating files. Now, when you actually need to manipulate a file, you should be able to go
through the relevant Java packages and find a Java class that can help you do what you want to
4 Chapter 1. Kickstarter for Beginners
do.
The OCPJP 11 Part 1 exam requires that you know about only a few packages and classes
of the Java API. I will go through them in detail in this book.
If you keep the above discussion in mind, I believe it will be very easy for you to grasp the
concepts that I am going to talk about throughout this book.
1. To help componentize the code - As discussed earlier in the API section, while writing
Java code, you should think about developing components instead of writing just pro-
grams. The difference between the two is in the way they allow themselves to be used
interchangeably. Can you imagine a 3 pin socket that has the ground pin on the left instead
of on the top? No one makes such a thing because it won’t allow any other plug to be
plugged in. In that sense, Components are like generic Lego blocks. You can mix and match
the blocks with basic functionality and build even bigger blocks. You can take out one block
and replace it with another block that has the same connectors. It is the same with software
components.
A program, on the other hand, is a monolithic pile of code that tries to do everything
without exposing generic and clear interfaces. Once you start using a program, it is almost
impossible to replace it with another one without impacting all other pieces that work
with that program. It is very much like a proprietary connector that connects a device to
a computer. You have to buy the whole new PC card to support that connector. If the
connector wire goes missing, you are dependent on the maker of that proprietary connector to
provide you with a replacement, at which point, you will wish that you had bought a device
with a USB connector instead. Only a few companies can pull this stunt off on their customers.
Java is designed with this in mind. You will see that many seemingly confusing rules
are there precisely because they promote the development of interchangeable components.
For example, an overriding method cannot throw a more generic exception than the one
declared by the overridden method. On the other hand the constructor of a subclass cannot
throw only a more specific exception than the one thrown by the constructor of the superclass.
Think about that.
2. To eliminate the scope for bugs - Java designers have tried to limit or eliminate features
that increase the possibility of bugs in a piece of code. Pointer arithmetic and goto are
examples of that. They have also tried to add features that help writing bug-free code.
Automatic Garbage Collection and Generics are examples of that.
6 Chapter 1. Kickstarter for Beginners
3. Make life easier for the programmer - Many older languages such as C/C++ were
built with the flexibility and power to do various kinds of things. Putting restrictions on what
a programmer can do was thought of as a bad idea. On the contrary, how to add features
that will let the programmer do more and more was the focus. Every new language added
more new features. For example, C++ has pointer arithmetic, global functions, operator
overloading, extern declarations, preprocessor directives, unsigned data types, and so many
other “features” that Java simply does not have. These are some really powerful tools in
the hands of a C++ programmer. So, why doesn’t Java have them? Java has actually
gone in reverse with respect to features. Java does not have a lot of features that are found
in languages that came before Java. The reason is simple. Java follows the philosophy
of making life simpler for the programmer. Having more and more features is not
necessarily a good thing. For example, having pointer arithmetic and manual allocation and
deallocation of objects is powerful but it makes life hell for the programmer. Thus, unlike
C++, there is no need to allocate memory in Java because all objects are created on the
heap. Why should a programmer have to worry about something that can be taken care of
by the language? Instead of focusing on mastering complicated features, the programmers
should be spending more time in developing business logic. Thus, unlike C++, there is no
need to deallocate memory in Java because Java performs garbage collection automatically.
Furthermore, the cost of maintaining complicated code cascades very quickly. A piece of
code is written once but is read and is overwritten numerous times. What is “clever” for one
programmer becomes a nightmare for the one who follows that programmer.
Java has therefore, introduced several restrictions (I consider them features, actually)
that make Java development substantially simpler overall. For example, in C++, there is no
restriction on the file name in which a class exists. But in Java, a public class has to be in a
file by that name. This is a restriction that doesn’t seem to make sense at first because after
compilation all classes are in the class files with the same names as that of the classes. But
when you think about the organization of your source code and the ease of locating the code
for a class, it makes perfect sense. Forcing every class to be coded in its own independent
file would have been impractical and letting any class to be in a file by any name would have
been too chaotic. So, forcing a public class to be in a file by that name is a nice balance.
Then there is a matter of a “judgement call”. Java designers are a bunch of smart
people. Some things may not make complete sense from a purely logical or technical
1.2 Why is something so 7
perspective but that’s how they designed those things anyway. They made the decisions
based on their experience and wisdom. For example, it is technically possible to design a
compiler that can figure out the value of a non-final local variable with 100% certainty in the
following code but the Java compiler does not flag an error for “unreachable code” here:
int x = 0;
if(x==0){
throw new Exception();
}
x = 20; //unreachable code here but no compilation error
Sometimes there is a logical explanation for a seemingly confusing rule but the reason is not
very well known. For example, the following code compiles fine even though the compiler
knows that the code is unreachable:
class ConditionalCompilation {
public static final boolean DEBUG = false;
public void method(){
if(DEBUG){
System.out.println("debug statement here");
} //works
}
}
But a similar code causes the compiler to flag “unreachable code” error:
class ConditionalCompilation{
public static final boolean DEBUG = false;
public void method(){
while(DEBUG){ //doesn’t work
System.out.println("debug statement here");
}
}
}
The reason is that historically, developers have used the combination of a boolean variable and
an ‘if’statement to include or exclude debug statements from the compiled code. A developer
has to change the value of the flag at just one place to eliminate all debug statements. The
‘if’statement in the code above works because Java designers decided to permit this type of
unreachable code so that conditional compilation could occur.
In conclusion, if you ever find yourself in a situation where you have to explain the reason behind
a weird Java rule or concept, one of the above four would be your best bet. For example, reason
3 answers the question that you asked in the previous section, “why does Java allow fields and
methods to be defined in an interface?”. Why doesn’t Java allow multiple inheritance? Reason 3.
Why are all objects in Java rooted under Object class?. Reason 3.
8 Chapter 1. Kickstarter for Beginners
As you can see, a declaration provides only partial information. You can’t make use of partial
information. The definition makes it complete and thus, usable.
In terms of variables, Java doesn’t have a distinction between declaration and definition because
all the information required to define a variable is included in the declaration itself. For example,
as a cookie cutter. Just as you create cookies out of dough using a cookie cutter, you create objects
out of memory space using a class.
To access an object, you need to know exactly where that object resides in memory. In other
words, you need to know the “address” of an object. Once you know the address, you can call
methods or access fields of that object. It is this “address” that is stored in a reference variable.
If you have trouble understanding this concept, try to imagine the relationship between a Tele-
vision (TV) and a Remote. The TV is the object and the Remote is the reference variable pointing
to that object. Just like you operate the TV using the remote, you operate on an object using a
reference pointing to that object. Notice that I did not say, ”you operate on an object using its
reference”. That’s because an object doesn’t have any special reference associated with it. Just as
a TV can have multiple remotes, an object can have any number of references pointing to it. One
reference is as good as any other for the purpose of accessing that object. There is no difference
between two references pointing to the same object except that they are two different references.
In other words, they are mutually interchangeable.
Now, think about what happens when the batteries of a remote die. Does that mean the
TV stops working? No, right? Does that mean the other remote stops working? Of course not!
Similarly, if you lose one reference to an object, the object is still there and you can use another
reference, if you have it, to access that object.
What happens when you take one remote to another room for operating another TV? Does it mean
the other remote stops controlling the other TV? No, right? Similarly, if you change one reference
to point to some other object, that doesn’t change other references pointing to that object.The
following picture illustrates the situation:
10 Chapter 1. Kickstarter for Beginners
Let me now move to an example that is closer to the programming world. Let’s say, you have
the following code:
String str = "hello";
"hello" is the actual object that resides somewhere in the program’s memory. Here, str is the
remote and "hello" is the TV. You can use str to invoke methods on the "hello" object.
A program’s memory can be thought of as a long array of bytes starting with 0 to NNNN, where
NNNN is the location of last byte of the array. Let’s say, within this memory, the object "hello"
resides at the memory location 2222. Therefore, the variable str actually contains just 2222. It
doesn’t contain "hello". It is no different from an int variable that contains 2222 in that sense.
But there is a fundamental difference in the way Java treats reference variables and non-
reference variables (aka primitive variables).If you print an int variable containing 2222, you
will see 2222 printed. However, if you try to print the value str, you won’t see 2222. You will see
"hello". This is because the JVM knows that str is defined as a reference variable and it needs
to use the value contained in this variable to go to the memory location and do whatever you want
to do with the object present at that location. In case of an int (or any other primitive variable),
the JVM just uses the value contained in the variable as it is. Since this is an important concept,
let me give you another example to visualize it. Let us say Paul has been given 2222 dollars and
Robert has been given bank locker number 2222. Observe that both Paul and Robert have the same
number but Paul’s number denotes actual money in his hands while Robert doesn’t have actual
money at all. Robert has an address of the location that has money. Thus, Paul is like a primitive
variable while Robert is like a reference variable.
1.4 Object and Reference 11
Another important point is that you cannot make a reference variable point to a memory location
directly. For example, you can set the int variable to 2250 but you can’t do that to str i.e. you
can’t do str = 2250. It will not compile. You can set str to another string and if that new string
resides at a memory location 2250, str will indeed contain 2250 but you can’t just store the address
of any memory location yourself in any reference variable.
As a matter of fact, there is no way in Java to see and manipulate the exact value contained in
a reference variable. You can do that in C/C++ but not in Java because Java designers decided
not to allow messing with the memory directly.
You can have as many references to an object as you want. When you assign one reference to
another, you basically just copy the value contained in one reference into another. For example, if
you do String str2 = str; you are just copying 2222 into str2. Understand that you are not
copying "hello" into str2. There is only one string containing "hello" but two reference variables
referring to it. Figure 1 illustrates this more clearly.
If you later do str = "goodbye"; you will just be changing str to point to a different string
object. It does not affect str2. str2 will still point to the string "hello".
The question that should pop into your head now is what would a reference variable contain if
it is not pointing at any object? In Java, such a variable is said to be null. After all, as discussed
above, a reference variable is no different from a primitive variable in terms of what it contains.
12 Chapter 1. Kickstarter for Beginners
Both contain a number. Therefore, it is entirely possible that a reference that is not pointing to any
object may actually contain the value 0. However, it would be wrong to say so, because a reference
variable is interpreted differently by the JVM. A particular implementation of JVM may even store
a value of -1 in the reference variable if it does not point to any object. For this reason, a reference
variable that does not point to any object is just null. At the same time, a primitive variable can
never be null because the JVM knows that a primitive variable can never refer to an object. It
contains a value that is to be interpreted as it is. Therefore,
String str = null; //Okay
int n = 0; //Okay
String str = 0; //will not compile
int n = null; //will not compile.
//But the numberOfAccounts fields does not belong to the instance, it belongs to the
Account class
Account.numberOfAccounts = Account.numberOfAccounts + 1;
//the following line accesses the same class field and therefore, numberOfAccounts is
incremented to 2
Account.numberOfAccounts = Account.numberOfAccounts + 1;
1. static is considered a non object-oriented feature because as you can see in the above code,
static fields do not belong to an object. So, why does Java have it? Check out the “Why is
something so?” section.
2. Here is a zinger from Java designers - even though static fields belong to a class and should be
accessed through the name of the class, for example, Account.numberOfAccounts, it is not an
error if you access it through a variable of that class, i.e., acct1.numberOfAccounts. Accessing
it this way doesn’t change its behavior. It is still static and belongs to the class. Therefore,
acct2.numberOfAccounts will also refer to the same field as acct1.numberOfAccounts. This
style only causes confusion and is therefore, strongly discouraged. Don’t write such code.
Ideally, they should have disallowed this usage with a compilation error.
3. Just like fields, methods can be static as well. A static method belongs to the class and can
be accessed either using the name of the class or through a variable of that class.
4. The opposite of static is instance. There is no keyword by that name though. If a class
member is not defined as static, it is an instance member.
System.out.println(this.str);
}
}
public static void main(String[] args){
Test t = new Test();
t.print();
}
}
In the above class, it is the main method that calls the print method but there could also be
another class, which could make use of the same print method to print hello a 100 times. When
the print method is called, it creates the variable i to keep track of the number of times the while
loop has iterated. This variable needs to be kept somewhere as long as the print method runs.
Similarly, it uses the variable str to print the string that you want the print method to print.
The question is, what happens when the print method ends? The variable i has served its
purpose and is not required anymore. It is not used anywhere except within this method. Therefore,
it need not be kept longer than the execution of the print method. But the variable str still can be
used whenever the print method is called. Therefore, the value of str needs to be kept irrespective
of the execution lifetime of the print method.
It should now be clear that a program needs two kinds of memory spaces to keep the stuff. One
for temporary stuff that can be cleaned up as soon as a method call ends and one for permanent
stuff that remains in use for longer than a single method call. The space for storing the temporary
stuff is called Stack space and the space for storing all other stuff is called Heap space. The
reason why they are called Stack and Heap will be clear soon.
In Java, each thread is given a fixed amount of stack space. In the above example, when you
execute the program, a main thread is created with a fixed amount of stack space. All this space
is initially empty. This is represented by the following figure.
When this thread invokes the main method, all the temporary variables created by this method
1.6 Stack and Heap 15
are kept on this stack. In the above example, the main method gets one reference variable named
args and inside the method it creates another reference variable named t. (Note that since args
and t are a reference variables, they contain the address of the location where actual objects referred
to by args and t respectively reside). Therefore, as the following figure shows, the stack fills up by
the amount of space required by these reference variables.
Step 2 - Stack has two variables and heap has one Test object
Before the main method ends, it calls the print method on the reference t. Since print is an
instance method, a variable named “this” is automatically put on the stack for it so that the
method can access the instance fields on this object. The variable this is also a reference variable
and it contains the address of the location where Test object actually resides. The print method
creates one more temporary variable i. This variable is also kept on the same stack on top of this.
Thus, the stack fills up a little more by amount of space required for storing two variables. This is
represented by the following figure.
16 Chapter 1. Kickstarter for Beginners
Step 3 - Two more variables i and this are added to the stack
When the print method ends, the space used for this and i is reverted back to the stack and
the stack is thus emptied out a little as shown in the following figure.
The control goes back to the main method. This method also ends and the space used for storing
args and t is cleaned up. There is nothing left on the stack any more at this point. Thus, the stack
is completely empty again.The following figure shows the final state of the stacks and the heap.
1.6 Stack and Heap 17
Step 5 stack is empty again but the heap still has Test object
As you can observe, the stack space looks like a stack of chips that are kept one on top of the
other. The temporary variables created by a method are added on top of the stack one by one
as and when they are created. As soon as the method ends, all those variables are removed from
the top. Observe that they are removed only after the method ends. If the method calls another
method, then the variables created by the called method are pushed on to the same stack on top
of the variables stored by the caller method. When a thread dies, its stack space is reverted back
to the JVM. Since this space behaves like a stack, it is called stack space.
The heap space, on the other hand, is, well, like a heap! Objects lie in a heap as they please.
JVM goes a great length to organize the heap space. Organization of heap space is an advanced
topic and is very important when you do performance analysis of an application. But it is not
relevant for certification exams and so I will not be discussing it. From the program perspective,
there is not much of an organization in a heap.
Whenever any object is created anywhere in the code (i.e. whether in a method or in a class),
the JVM allocates space for that object on the heap and puts its contents in that space. In Java,
a program never releases this space explicitly. It is managed by the JVM. Again, recall that an
object can only be accessed using its reference. For a method to access an object, it must use a
reference that points to that object. It could get that reference either from a variable kept on its
stack space (if the object was created in this method itself) or through a reference to another object
whose reference is kept on the stack space (if that object has a reference to the required object).
In either case, a method has to start with a reference that exists on its stack space. If there is no
reference on any stack space through which an object can be accessed directly or indirectly, that
object is considered garbage. It is cleaned up automatically by the JVM using a garbage collector.
18 Chapter 1. Kickstarter for Beginners
Note
Recall from our discussion on References and Objects that a reference is merely a variable
that stores the address of the location where the actual object is stored. In that sense, a
reference variable is no different than an int variable. They both store a number. A reference
variable stores a number that indicates the memory location when you can find the actual
object, while an int variable stores a number that is interpreted as a number. It doesn’t
indicate anything else. If you create a variable in a method, whether a reference variable or
a primitive variable, it is kept on the stack but when you create an object, that object is
stored on the heap.
Typically, an object is created using the new keyword. But Java treats Strings as
special and so you can create String objects even without the new keyword. Thus, whether
you do “hello” or new String(“hello”), in both the cases, a String object containing “hello”
is created on the heap.
Points to remember:
1. Local variables are always kept on the stack. Objects are always stored in the heap. (An
optimizing JVM may allocate an object on the stack space, but it is an internal detail of the
JVM and you need not worry about it. For all we care, objects are always on the heap.)
2. JVM may have several threads. Each thread is given a fixed amount of stack space that is
dedicated completely and exclusively to that thread. No one but that thread can access its
stack space. This is called ”stack semantics”. A thread accesses its stack space by creating
and using variables. There is no other special way of accessing the stack space.
3. Heap space is shared among all threads. Any thread can use space on a heap by creating
objects. Since heap space is shared, it is possible for one thread to access objects created by
another if it has a reference to that object. This is called ”heap semantics”.
4. Stack space is limited for a program. So if you have a huge chain of method calls where each
method creates a lot of temporary variables (recursion is a good example), it is possible to
run out of stack space. In Java, the default stack space size is 64KB but it can be changed at
the time of executing the program using command line option -Xss . Heap space is unlimited
from the program’s perspective. It is limited only by the amount of space available on your
machine.
5. Only temporary variables i.e. variable created in a method (also known as local variables and
automatic variables) are created on the stack space. Everything else is created on the heap
space. If you have any doubt, ask yourself this question - is this a temporary variable created
in a method? Yes? Then it is created on the stack. No? Then it is on the heap. Actual
objects are ALWAYS created on the heap.
6. When a method is invoked by a thread, it uses the thread’s stack space to keep its temporary
variables.
1.7 Conventions 19
7. Variables added to the stack space by a method are removed from the stack when that method
ends. Everything else created by a method is left on the heap even after the method ends.
1.7 Conventions
1.7.1 What is a Convention?
You add a 15% tip to your bill at a restaurant. There is no law about that. Nobody is going to
put you in jail if you add nothing for a tip. But you still do it because it is a convention. A lot of
things in the world are based on convention. In India, you drive on the left side of the road. This
is a convention. It has nothing to do with being technically correct. Indeed, people are fine driving
on the right side of the road in the US. But if you drive on the right side of the road in India, you
will cause accidents because that is not what other people expect you to do.
It is the same in the programming world. As a programmer, you are a part of the programmer
community. The code that you write will be read by others and while developing your code, you
will read and use code written by others. It saves everyone time and effort in going through a piece
of code if it follows conventions. It may sound ridiculous to name loop variables as i, j, or k,
but that is the convention. Anyone looking at a piece of code with a variable i will immediately
assume that it is just a temporary variable meant to iterate through some loop.
If you decide to use a variable named i for storing some important program element, your
program will work fine but it will take other people time to realize that and they will curse you for
it.
If you are still unconvinced about the importance of conventions in programming, let me put it
another way. If I ask you to write some code in an interview and if you use a variable named hello
as a loop variable, I will not hire you. I can assure you that most interviewers will not like that
either. Conventions are that important.
(a) Class names start with an uppercase letter. For example, ReadOnlyArrayList is a good
name but Readonlyarraylist is not.
(b) Package names are generally in all lowercase but they also may be in camel case starting
with a lower case letter. For example, datastructures is a good package name but
DataStructures is not.
(c) variable names start with a lower case and may include underscores. For example,
current account is a good variable name.
2. Naming - Names should be meaningful. A program with a business purpose should not have
variables with names such as foo, bar, and fubar. Although, such nonsensical names are
used for illustrating or explaining code in sample programs where names are not important.
20 Chapter 1. Kickstarter for Beginners
3. Package names use a reverse domain name combined with a group name
and/or application name. For example, if you work at Bank of America’s
Fixed Income Technologies division and if you are developing an application named
FX Blotter, all your packages for this application may start with the name
com.bofa.fit.fxblotter. The full class name for a class named ReadOnlyArrayList could
be - com.bofa.fit.fxblotter.dataStructures.ReadOnlyArrayList.
The reason for using a reverse domain name is that it makes it really easy to come
up with globally unique package names. For example, if a developer in another
group also creates his own ReadOnlyArrayList, the full name of his class could be
com.bofa.derivatives.dataStructures.ReadOnlyArrayList. There would be no problem
if a third developer wants to use both the classes at the same time in his code because their
full names are different. The important thing is that the names turned out to be different
without any of the programmers ever communicating with each other about the name of their
classes. The names are unique globally as well because the domain names of companies are
unique globally.
System.out.println("Hello 1 2 3 testing...");
In the above code, accounting.Account is the fully qualified class name of the class. This long
name is the name that you need to use to refer to this class from a class in another package. Of
course, you can “import” accounting package and then you can refer to this class by its short name
Account. The purpose of packages is to organize your classes according to their function to ease
their maintenance. It is no different from how you organize a physical file cabinet where you keep
your tax related papers in one drawer and bills in another.
1.8 Compilation and Execution 21
Packaging is meant solely for ease of maintenance. The Java compiler and the JVM don’t really
care about it. You can keep all your classes in one package for all that matters.
Let us create Account.java file and put it in your work folder (for example, c:\javatest).
Copy the above mentioned code in the file and compile it as follows:
c:\javatest\>javac Account.java
You should see Account.class in the same folder. Now, let us try to run it from the same folder:
c:\javatest>java Account
Of course, you need to use the long name to refer to the class, so, let’s try this:
c:\javatest>java accounting.Account
Okay, now delete the Account.class file and compile the Java code like this:
c:\javatest\>javac -d . Account.java
| c:
| javatest
Acccount.java
| accounting
Account.class
What is going on? Well, by default the Java compiler compiles the Java source file and puts the class
file in the same folder as the source file. But the Java command that launches the JVM expects the
class file to be in a directory path that mimics the package name. In this case, it expects the Ac-
counting.class file to be in a directory named accounting. The accounting directory itself may lie
anywhere on your file system but then that location must be on the classpath for the JVM to find it.
One of the many command line options that javac supports is the -d option. It directs
22 Chapter 1. Kickstarter for Beginners
the compiler to create the directory structure as per the package name of the class and put the
class file in the right place. In our example, it creates a directory named accounting in the current
directory and puts the class file in that directory. The dot after -d in the javac command tells the
compiler that the dot, i.e., the current directory is the target directory for the resulting output.
You can replace dot with any other directory and the compiler will create the new package based
directory structure there. For example, the command c:\javatest\>javac -d c:\myclassfiles
Account.java will cause the accounting directory to be created in c:\myclassfiles folder.
Now, at the time of execution you have to tell the JVM where to find the class that you
are asking it to execute. The -classpath (or its short form -cp) option is meant exactly for that
purpose. You use this option to specify where your classes are located. You can specify multiple
locations here. For example, if you have a class located in c:\myclassfiles directory and if
that class refers to another class stored in c:\someotherdirectory, you should specify both the
locations in the classpath like this:
c:\>java -classpath c:\myclassfiles;c:\someotherdirectory accounting.Account
Observe that when you talk about the location of a class, it is not the location of the class file that
you are interested in but the location of the directory structure of the class file. Thus, in the above
command line, c:\myclassfiles should contain the accounting directory and not Account.class
file. Account.class should be located inside the accounting directory. The JVM searches in all
the locations specified in the -classpath option for classes.
Note
Note: On *nix based systems, you need to use colon (:) instead of semi-colon (;) and forward
slash (/) instead of back slash (\).
Note
The Java command scans the current directory for class files (and packages) by default, so,
there is usually no need to specify “dot” in the -classpath option. I have specified it explicitly
just to illustrate the use of the -classpath option.
Contents of B.java:
1.8 Compilation and Execution 23
package p2;
public class B{
}
Open a command prompt, cd to c:\javatest, and compile A.java. You will get a compilation
error because class A depends on class B. Obviously, the compiler will not be able to find B.class
because you haven’t compiled B.java yet! Thus, you need to compile B.java first. Of course,
as explained before, you will need to use the -d . option while compiling B.java to make javac
create the appropriate directory structure along with the class file in c:\javatest directory. This
will create B.class in c:\javatest\p2 directory. Compilation of A.java will now succeed. The
point is that if you have two classes where one class depends on the other, you need to compile the
source file for the independent class first and the source file for the dependent class later. However,
most non-trivial Java applications are composed of multiple classes coded in multiple source files.
It is impractical to determine the sequence of compilation of the source files manually. Moreover,
it is possible for two classes to be circularly dependent on each other. Which source file would you
compile first in such a case?
Fortunately, there is a simple solution. Just let the compiler figure out the dependencies by
specifying all the source files that you want to compile at once. Here is how:
javac -d . A.java B.java
But again, specifying the names of all the source files would also be impractical. Well, there is a
solution for this as well:
javac -d . *.java
By specifying *.java, you are telling the compiler to compile all Java files that exist in the current
directory. The compiler will inspect all source files, figure out the dependencies, create class files
for all of them, and put the class files in an appropriate directory structure as well. Isn’t that neat?
If your Java source files refer to some preexisting class files that are stored in another directory,
you can state their availability to javac using the same -classpath (or -cp) option that we used
for executing a class file using the java command.
I strongly advise that you become comfortable with the compilation process by following
the steps outlined above.
}
}
You can execute this file directly from the command line using the following command:
java TestClass.java
The only restriction with this approach is that your Java code must not refer to code in
any other Java file. You can have as many classes in the file as you want but the first class that
appears in the file must contain the main method because that is the main method that the JVM
will pick to execute.
Although this compilation cum execution technique is not on the exam, I have included
it here because it will save you a lot of time while trying out various concepts using single file
programs. You have to be careful about distinguishing between compilation failure and exception
at run time though. If you see error: compilation failed on the console, it is a compilation
error, otherwise, it is an exception during execution.
Go to the command prompt, cd to c:\javatest directory and run the following command:
This command tells the jar utility to create accounting.jar file and include the entire di-
rectory named accounting in it along with its internal files and directories. You should now have
the directory structure shown below:
1.8 Compilation and Execution 25
| c:
| javatest
Acccount.java
| accounting
Account.class
acccounting.jar
Assuming that you are still in c:\javatest directory on your command prompt, you can now run
the class through the jar file like this:
Note that you must maintain the package structure of the class while creating the jar file.
If you open accounting.jar in WinZip or 7zip, you will see that this jar contains Ac-
count.class under accounting directory.
Besides the class files, the Jar file allows you to keep information about the contents of the
jar file within the jar file itself. This information is kept in a special file is called MANIFEST.MF
and is kept inside the META-INF folder of the jar file. (This is just like airlines using a “manifest”
to document the cargo or a list of passengers on a flight.) For example, you can specify the entry
point of an application which will allow you to run a Jar file directly (from the command line or
even by just double clicking the jar file in your file explorer) without having to specify the class
name containing the main method on the command line. Typical contents of this file are as follows
-
Manifest-Version: 1.0
Main-Class: accounting.Account
Created-By: 11.0.2 (Oracle Corporation)
You can actually go ahead and create mymanifest.txt file with just one line Main-Class:
accounting.Account in c:\javatest directory (make sure there is a new line at the end of the
file) and use the following command to create the jar:
c is for create, v is for verbose (i.e. display detailed information on command line), f is for
the output file, and m is the name of the file the contents of which have to be included in the
jar’s manifest. Notice that the name of the manifest file on the command line is not important.
Only the contents of the file are important. This command will automatically add a file named
MANIFEST.MF inside the META-INF folder of the jar file.
Once you have this information inside the jar file, all you need to do to run the program is
to execute the following command on the command line:
java -jar accounting.jar
26 Chapter 1. Kickstarter for Beginners
Note
Although packaging classes into Jar files is not on the exam as such, you will need to know
about it from the perspective of execution of modules, which is on the exam.
1. First and foremost, it is the compiler’s job to check whether the code follows the syntactical
rules of the language. This means, it will generate an error upon encountering any syntactical
mistake. For example, Java requires that the package statement, if present, must be the
first statement in the Java code file. If you try to put the package statement after an import
statement, the compiler will complain because such a code will be syntactically incorrect. You
will see several such rules throughout this book. Yes, you will need to memorize all those. If
you use an IDE such as Eclipse, NetBeans, or IntelliJ, you should stop using it because you
need to train your brain to spot such errors instead of relying on the IDE. Using Notepad to
write and using the command line to compile and run the test programs is very helpful in
mastering this aspect of the exam.
2. Besides being syntactically correct, the compiler wants to make sure that the code is
logically correct as well. However, the compiler is limited by the fact that it cannot
execute any code and so, it can never identify all the logical errors that the code may
have. Even so, if, based on the information present in the code, the compiler determines
that something is patently wrong with the code, it raises an error. It is this category of
errors that causes the most frustration among beginners. For example, the statement byte
b = 200; is syntactically correct but the compiler does not like it. The compiler knows
that the value 200 is too big to fit into a byte and it believes that the programmer is
making a logical mistake here. On the other hand, the compiler okays the statement int i
= 10/0; even though you know just by looking at the code that this statement is problematic.
3. The JVM is the ultimate guard that maintains the integrity and type safety of the Java virtual
machine at all times. Unlike the compiler, the JVM knows about everything that the code
tries to do and it throws an exception (I am using the word exception in a general sense
here and not referring to the java.lang.Exception class) as soon as it determines that the
action may damage the integrity or the type safety of the JVM. Thus, any potentially illegal
activity that escapes the compiler will be caught by the JVM and will result in an exception
to be thrown at run time. For example, dividing a number by zero does not generate any
meaningful integral value and that is why the JVM throws an exception if the code tries to
divide an integral value by zero.
1.9 Nomenclature 27
Honestly, this is not an easy topic to master. The only way to get a handle on this is to know about
all the cases where this distinction is not so straightforward to make. If you follow this book, you
will learn about all such rules, their exceptions, and the reasons behind them, that are required for
the exam.
1.9 Nomenclature
During your programming career you will be reading a lot. It could be books, articles, blogs, manu-
als, tutorials, and even discussion forums. You will also be interacting with other Java developers in
various roles such as interviewers, team members, architects, and colleagues. To make the most out
of these interactions, it is very important to form a clear and precise understanding of commonly
used terms.
I will explain the commonly used phrases, names, and terminology in the Java world.
1. Class - Unless stated otherwise or unless clear from the context, the term class includes
class, interface, and enum. Usually, people mean “type” when they say “class”. You should,
however, always try to be precise and use the term class only for class.
2. Type - Type refers to classes, interfaces, enums, and also primitive types (byte, char, short,
int, long, float, double, and boolean).
3. Primitive types - byte, char, short, int, long, float, double, and boolean are called primitive
types because they just hold data and have no behavior. You can perform operations on them
but you cannot call methods on them. They do not have any property or state other than
the data value that they contain. You access them directly and never through references.
4. Reference types - Classes, Interfaces, and Enums are called reference types because you
always refer to them through references and never directly. Unlike primitive types, reference
types have behavior and/or state.
5. Top-level reference types - Classes, interfaces, or enums that are defined directly under a
package are called top-level classes, interfaces, or enums.
6. Nested reference types - Classes, interfaces, and enums that are defined inside another
class, interface, or an enum are called nested classes, interfaces, or enums.
7. Inner reference types - Non-static nested classes, interfaces, and enums that are called
inner classes, interfaces, or enums.
8. Local reference types - Nested reference types that are defined inside a method (or inside
another code block but not directly inside a class, interface, or enum) are called local classes,
interfaces, or enums.
9. Anonymous classes - This is a special case of a nested class where just the class definition
is present in the code and the complete declaration is automatically inferred by the compiler
through the context. An anonymous class is always a nested class and is never static.
28 Chapter 1. Kickstarter for Beginners
10. Compile time vs run time (i.e. execution time) - You know that there are two steps
in executing Java code. The first step is to compile the Java code using the Java compiler to
create a class file and the second step is to execute the JVM and pass the class file name as
an argument. Anything that happens while compiling the code such as generation of compiler
warnings or error messages is said to happen during “compile time”. Anything that happens
while executing the program is said to happen during the “run time”. For example, syntax
errors such as a missing parentheses, braces, or a semicolon are caught at compile time while
any exception that is generated while executing the code is thrown at run time. It is kind of
obvious but I have seen many beginners posting questions such as, “why does this code throw
the following exception when I try to compile it?”, when they really mean, “why does this code
generate the following error message while compilation?” Another common question is, “why
does this code throw an exception even after successful compilation?” Successful compilation
is not a guarantee for successful execution! Although the compiler tries to prevent a lot of
bugs by raising warnings and error messages while compilation, successful compilation really
just means that the code is syntactically correct.
11. Compile-time constants - Normally, it is the JVM that sets the values of variables when a
program is executed. The compiler does not execute any code and it has no knowledge of the
values that a variable might take during the execution of the program. Even so, in certain
cases, it is possible for the compiler to figure out the value of a variable. If a compiler can
determine the value that a variable will take during the execution of the program, then that
variable is actually a compile-time constant. For example, if you define an int variable as
final int x = 10; then x is a compile time constant because the compiler knows tha x will
always have a value of 10 at run time. Similarly, literals such as the numbers 1, 2, and 3, or
the characters written in code within single quotes such as ’a’, or boolean values true and
false, are all compile time constants because the compiler knows that these values will never
change.
I will refer to these terms and will also discuss the details of these terms throughout the course
so, it will be helpful if you keep the basic idea of these terms in mind.
Java letters include uppercase and lowercase ASCII Latin letters A-Z ( \u0041-\u005a ), and
a-z ( \u0061-\u007a ), and, for historical reasons, the ASCII underscore ( or \u005f ) and dollar
sign ( $ or \u0024 ). The “Java digits” include the ASCII digits 0-9 ( \u0030-\u0039 ).
Note
Older versions of the exam tested candidates on identifying valid identifiers. However, the
current exam has moved away a bit from making the candidate a human compiler and does
not include this topic. You should still have a basic idea about what an identifier is though
because this concept applies to all kind of names in Java.
30 Chapter 1. Kickstarter for Beginners
This is the end of sample. If you liked it, please purchase the full version from
http://enthuware.com/815/amazon.php