0% found this document useful (0 votes)
127 views63 pages

SCJP Notes

Java is an object-oriented programming language created in the early 1990s by James Gosling and colleagues at Sun Microsystems. It is designed to be compiled to bytecode that is run on a Java Virtual Machine, making it portable across various operating systems. The goals of Java included being object-oriented, allowing programs to run on multiple platforms, providing network support, securely executing remote code, and having an easy to use syntax. Key characteristics of Java include object orientation, platform independence through just-in-time compilation to bytecode, and automated memory management.

Uploaded by

Vijaya Lakshmi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views63 pages

SCJP Notes

Java is an object-oriented programming language created in the early 1990s by James Gosling and colleagues at Sun Microsystems. It is designed to be compiled to bytecode that is run on a Java Virtual Machine, making it portable across various operating systems. The goals of Java included being object-oriented, allowing programs to run on multiple platforms, providing network support, securely executing remote code, and having an easy to use syntax. Key characteristics of Java include object orientation, platform independence through just-in-time compilation to bytecode, and automated memory management.

Uploaded by

Vijaya Lakshmi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Java is an object-oriented uniformity and simplicity available without charge,

programming language than C/C++. The first with revenue being


developed by James public implementation generated by specialized
Gosling and colleagues at was Java 1.0 in 1995. It products such as the Java
Sun Microsystems in the made the promise of Enterprise System. Sun
early 1990s. Unlike "Write Once, Run distinguishes between its
conventional languages Anywhere", with free Software Development Kit
which are generally runtimes on popular (SDK) and Runtime
designed either to be platforms. It was fairly Environment (JRE) which
compiled to native secure and its security is a subset of the SDK, the
(machine) code, or to be was configurable, primary distinction being
interpreted from source allowing for network and that in the JRE the
code at runtime, Java is file access to be limited. compiler is not present.
intended to be compiled The major web browsers
Philosophy
to a bytecode, which is soon incorporated it into
then run (generally using their standard There were five primary
JIT compilation) by a Java configurations in a secure goals in the creation of
Virtual Machine. "applet" configuration. the Java language:
popular quickly. New
The language itself
versions for large and 1. It should use the object-
borrows much syntax
small platforms (J2EE and oriented programming
from C and C++ but has a
J2ME) soon were designed methodology.
simpler object model and
with the advent of "Java 2. It should allow the
fewer low-level facilities.
2". Sun has not same program to be
Java is only distantly
announced any plans for executed on multiple
related to JavaScript,
a "Java 3". operating systems.
though they have similar
3. It should contain built-
names and share a C-like In 1997, Sun approached
in support for using
syntax. the ISO/IEC JTC1
computer networks.
standards body and later
History 4. It should be designed to
the Ecma International to
execute code from remote
Java was started as a formalize Java, but it soon
sources securely.
project called "Oak" by withdrew from the
5. It should be easy to use
James Gosling in June process. Java remains a
by selecting what was
1991. Gosling's goals proprietary de facto
considered the good parts
were to implement a standard that is
of other object-
virtual machine and a controlled through the
orientedlanguages.
language that had a Java Community Process.
familiar C-like notation Sun makes most of its
but with greater Java implementations
the code that operates on Software reusability has
that data, or vice versa. met with mixed practical
To achieve the goals of
This separation into results, with two main
networking support and
coherent objects provides difficulties: the design of
remote code execution,
a more stable foundation truly generic objects is
Java programmers
for a software system's poorly understood, and a
sometimes find it
design. The intent is to methodology for broad
necessary to use
make large software communication of reuse
extensions such as
projects easier to manage, opportunities is lacking.
CORBA, Internet
thus improving quality Some open source
Communications Engine,
and reducing the number communities want to help
or OSGi.
of failed projects. ease the reuse problem,
Objectorientation by providing authors with
Another primary goal of ways to disseminate
The first characteristic, OO programming is to information about
object orientation ("OO"), develop more generic generally reusable objects
refers to a method of objects so that software and object libraries.
programming and can become more
language design. reusable between Platformindependence
Although there are many projects. A generic
interpretations of OO, one "customer" object, for The second characteristic,
primary distinguishing example, should have platform independence,
idea is to design software roughly the same basic means that programs
so that the various types set of behaviors between written in the Java
of data it manipulates are different software language must run
combined together with projects, especially when similarly on diverse
their relevant operations. these projects overlap on hardware. One should be
Thus, data and code are some fundamental level able to write a program
combined into entities as they often do in large once and run it anywhere.
called objects. An object organizations. In this
can be thought of as a sense, software objects This is achieved by most
self-contained bundle of can hopefully be seen Java compilers by
behavior (code) and state more as pluggable compiling the Java
(data). The principle is to components, helping the language code "halfway"
separate the things that software industry build to bytecode (specifically
change from the things projects largely from Java bytecode)—
that stay the same; often, existing and well-tested simplified machine
a change to some data pieces, thus leading to a instructions specific to the
structure requires a massive reduction in Java platform. The code is
corresponding change to development times. then run on a virtual
machine (VM), a program and JNI interfaces and into native code like a
written in native code on had added platform- more traditional
the host hardware that specific features of their compiler, skipping
interprets and executes own. In response, bytecodes entirely. This
generic Java bytecode. Microsoft no longer ships achieves good
Further, standardized Java with Windows, and performance, but at the
libraries are provided to in recent versions of expense of portability.
allow access to features of Windows, Internet Another technique, known
the host machines (such Explorer cannot support as just-in-time
as graphics, threading Java applets without a compilation (JIT),
and networking) in third-party plug-in. translates the Java
unified ways. Note that, However, Sun and others bytecodes into native
although there's an have made available Java code at the time that the
explicit compiling stage, run-time systems at no program is run which
at some point, the Java cost for those and other results in a program that
bytecode is interpreted or versions of Windows. executes faster than
converted to native interpreted code but also
machine instructions by The first implementations incurs compilation
the JIT compiler. of the language used an overhead during
interpreted virtual execution. More
There are also machine to achieve sophisticated VMs use
implementations of Java portability. These dynamic recompilation, in
compilers that compile to implementations which the VM can analyze
native object code, such produced programs that the behavior of the
as GCJ, removing the ran more slowly than running program and
intermediate bytecode programs compiled to selectively recompile and
stage, but the output of native executables, for optimize critical parts of
these compilers can only instance written in C or the program. Dynamic
be run on a single C++, so the language recompilation can
architecture. suffered a reputation for achieve optimizations
poor performance. More superior to static
Sun's license for Java recent JVM compilation because the
insists that all implementations produce dynamic compiler can
implementations be programs that run base optimizations on
"compatible". This significantly faster than knowledge about the
resulted in a legal dispute before, using multiple runtime environment and
with Microsoft after Sun techniques. the set of loaded classes.
claimed that the JIT compilation and
Microsoft implementation The first technique is to dynamic recompilation
did not support the RMI simply compile directly allow Java programs to
take advantage of the that programmers should responsible for managing
speed of native code be spared the burden of the object's lifecycle. The
without losing portability. having to perform program or other objects
manual memory can reference an object by
Portability is a technically management. In some holding a reference to it
difficult goal to achieve, languages the (which, from a low-level
and Java's success at that programmer allocates point of view, is its
goal has been mixed. memory to create any address on the heap).
Although it is indeed object stored on the heap When no references to an
possible to write and is responsible for object remain, the Java
programs for the Java later manually garbage collector
platform that behave deallocating that memory automatically deletes the
consistently across many to delete any such objects. unreachable object,
host platforms, the large If a programmer forgets freeing memory and
number of available to deallocate memory or preventing a memory
platforms with small writes code that fails to leak. Memory leaks may
errors or inconsistencies do so in a timely fashion, still occur if a
led some to parody Sun's a memory leak can occur: programmer's code holds
"Write once, run the program will consume a reference to an object
anywhere" slogan as a potentially arbitrarily that is no longer needed
"Write once, debug large amount of memory. —in other words, they
everywhere". In addition, if a region of can still occur but at
memory is deallocated higher conceptual levels.
Platform-independent twice, the program can
Java is however very become unstable and may The use of garbage
successful with server- crash. Finally, in non collection in a language
side applications, such as garbage collected can also affect
Web services, servlets, environments, there is a programming paradigms.
and Enterprise JavaBeans, certain degree of If, for example, the
as well as with Embedded overhead and complexity developer assumes that
systems based on OSGi, of user-code to track and the cost of memory
using Embedded Java finalize allocations. allocation/recollection is
environments. low, they may choose to
In Java, this potential more freely construct
Automatic garbage problem is avoided by objects instead of pre-
collection automatic garbage initializing, holding and
collection. The reusing them. With the
One idea behind Java's programmer determines small cost of potential
automatic memory when objects are created, performance penalties
management model is and the Java runtime is (inner-loop construction
of large/complex objects), disadvantageous: the public class Hello extends
this facilitates thread- programmer is freed from Applet
isolation (no need to performing low-level
{
synchronize as different tasks, but at the same
public void
threads work on different time loses the option of
paint(Graphics gc)
object instances) and writing lower level code.
data-hiding. The use of {
transient immutable Syntax gc.drawString("Hello,
value-objects minimizes world!", 65, 95);
side-effect programming. The syntax of Java is }
largely derived from C++. }
Comparing Java and C++, However, unlike C++,
it is possible in C++ to which combines the This applet will simply
implement similar syntax for structured, draw the string "Hello,
functionality (for generic, and object- world!" in the rectangle
example, a memory oriented programming, within which the applet
management model for Java was built from the will run. This is a slightly
specific classes can be ground up to be virtually better example of using
designed in C++ to fully object-oriented: Java's OO features in that
improve speed and lower everything in Java is an the class explicitly extends
memory fragmentation object with the exceptions the basic "Applet" class,
considerably), with the of atomic datatypes that it overrides the
possible cost of extra (ordinal and real "paint" method and that
development time and numbers, boolean values, it uses import statements.
some application and characters) and
complexity. In Java, everything in Java is <!-- Hello.html -->
garbage collection is written inside a class. <html>
built-in and virtually <head>
invisible to the developer. Applet <title>Hello World
That is, developers may Applet</title>
have no notion of when Java applets are </head>
garbage collection will programs that are <body>
take place as it may not embedded in other <applet code="Hello"
necessarily correlate with applications, typically in a width="200"
any actions being Web page displayed in a height="200">
explicitly performed by Web browser. </applet>
the code they write. //Hello.java </body>
Depending on intended import java.applet.Applet; </html>
application, this can be import java.awt.Graphics;
beneficial or An applet is placed in an
HTML document using "text/html"); client. The service()
the <applet> HTML PrintWriter pw = method declares that it
element. The applet tag response.getWriter(); throws the exceptions
has three attributes set: pw.println("Hello, ServletException and
code="Hello" specifies the world!"); IOException if a problem
name of the Applet class pw.close(); prevents it from
and width="200" } responding to the request.
height="200" sets the }
pixel width and height of The
the applet. (Applets may The import statements setContentType(String)
also be embedded in direct the Java compiler method in the response
HTML using either the to include all of the public object is called to set the
object or embed element, classes and interfaces MIME content type of the
although support for from the java.io and returned data to
these elements by Web javax.servlet packages in "text/html". The
browsers is inconsistent. the compilation. The getWriter() method in the
Hello class extends the response returns a
Servlet GenericServlet class; the PrintWriter object that is
GenericServlet class used to write the data
Java servlets are server- provides the interface for that is sent to the client.
side Java EE components the server to forward The println(String)
that generate responses requests to the servlet method is called to write
to requests from clients. and control the servlet's the "Hello, world!" string
lifecycle. to the response and then
// Hello.java the close() method is
import java.io.*; The Hello class overrides called to close the print
import javax.servlet.*; the writer, which causes the
service(ServletRequest, data that has been
public class Hello extends ServletResponse) method written to the stream to
GenericServlet defined by the Servlet be returned to the client.
interface to provide the
{
code for the service Swing application
public void
request handler. The
service(ServletRequest
service() method is passed Swing is the advanced
request, ServletResponse
a ServletRequest object graphical user interface
response)
that contains the request library for the Java SE
throws ServletException,
from the client and a platform.
IOException
ServletResponse object
{
used to create the // Hello.java
response.setContentType(
response returned to the import javax.swing.*;
title bar is selected to until all of the Swing top-
public class Hello extends WindowConstants.DISPOS level windows have been
JFrame { E_ON_CLOSE—this causes disposed.
Hello() { the JFrame to be disposed
setDefaultCloseOperation of when the frame is Look and feel
(WindowConstants.DISPO closed (as opposed to
SE_ON_CLOSE); merely hidden), which The default look and feel
add(new JLabel("Hello, allows the JVM to exit and of GUI applications
world!")); the program to terminate. written in Java using the
pack(); Next a new JLabel is Swing toolkit is very
} created for the string different from native
"Hello, world!" and the applications. It is possible
public static void add(Component) method to specify a different look
main(String[] args) { inherited from the and feel through the
new Container superclass is pluggable look and feel
Hello().setVisible(true); called to add the label to system of Swing. Clones of
} the frame. The pack() Windows, GTK and Motif
} method inherited from are supplied by Sun. Apple
the Window superclass is also provides an Aqua
The import statement called to size the window look and feel for Mac OS
directs the Java compiler and layout its contents. X. Though prior
to include all of the public implementations of these
classes and interfaces The main() method is look and feels have been
from the javax.swing called by the JVM when considered lacking, Swing
package in the the program starts. It in Java SE 6 addresses this
compilation. The Hello instantiates a new Hello problem by using more
class extends the JFrame frame and causes it to be native widget drawing
class; the JFrame class displayed by calling the routines of the underlying
implements a window setVisible(boolean) platforms. Alternatively,
with a title bar with a method inherited from third party toolkits such
close control. the Component superclass as wx4j or SWT may be
with the boolean used for increased
The Hello() constructor parameter true. Note that integration with the
initializes the frame by once the frame is native windowing system.
first calling the displayed, exiting the
setDefaultCloseOperation main method does not Lack of OO purity and
(int) method inherited cause the program to facilities
from JFrame to set the terminate because the
default operation when AWT event dispatching Java's primitive types are
the close control on the thread remains active not objects. Primitive
types hold their values in browser plugins. Sun also The Java programming
the stack rather than distributes a superset of language has includes
being references to the JRE called the Java 2 five simple arithmetic
values. This was a SDK (more commonly operators like are +
conscious decision by known as the JDK), which (addition), -
Java's designers for includes development (subtraction), *
performance reasons. tools such as the Java (multiplication), /
Because of this, Java is not compiler, Javadoc, and (division), and %
considered to be a pure debugger. (modulo). The following
object-oriented table summarizes them:
Scjp:
programming language.
However, as of Java 5.0, 1. Source file's elements
SCJP java Programmer
autoboxing enables (in order)
certification Exam And
programmers to write as Training. This site is  Package
if primitive types are their entirely independent of declaration
wrapper classes, and Sun Microsystems Inc, The
freely interchange Sun Certified Java  Import statements
between them for Programmers Exam
improved flexibility. Java  Class definitions
(SCJP) is the
designers decided not to internationally 2. Importing packages
implement certain recognized java doesn't recursively import
features present in other certification exam. This sub-packages.
OO languages, including: site offers free mock Exam
preparation questions, 3. Sub-packages are really
* multiple inheritance practice tests, tutorials, different packages,
* operator overloading certification faq and happen to live within an
* class properties sample code. This site enclosing package.
* tuples contains a very detailed Classes in sub-packages
tutorial organized by cannot access classes in
Java Runtime topic. At the end of the enclosing package with
Environment tutorial you can learn default access.
from your mistakes and
The Java Runtime apply your concepts on 4. Comments can appear
Environment or JRE is the the free mock exams java anywhere. Can't be
software required to run certification practice nested. No matter what
any application deployed tests. type of comments.
on the Java Platform.
End-users commonly use Chapter 1: Language 5. At most one public class
a JRE in software Fundamentals  (Next: definition per file. This
packages and Web Chapter 2)
class name should match
the file name. If there are 11. Unicode characters
more than one public can appear anywhere in
class definitions, compiler the source code. The
will accept the class with following code is valid.
the file's name and give
an error at the line where ch\u0061r a = 'a';
the other class is defined.
char \u0062 = 'b';
6. It's not required having
a public class definition in char c = '\u0063';
a file. Strange, but true. J
In this case, the file's 12. Java has 8 primitive
name should be different data types.
from the names of classes
and interfaces (not public
obviously).

7. Even an empty file is a


valid source file.

8. An identifier must
begin with a letter, dollar
sign ($) or underscore (_).
Subsequent characters
may be letters, $, _ or
digits.

9. An identifier cannot
have a name of a Java
keyword. Embedded
keywords are OK. true,
false and null are literals
(not keywords), but they
can't be used as
identifiers as well.

10. const and goto are


reserved words, but not
used.
d S In Mi Max Value
at i iti n
a z al V
T e V al
y ( al ue
p b ue
e i
t
s
)

b 1 fal   fa true
o se lse
ol
ea
n

by 8 0 - 127 (27 - 1)
te 12
8
(-
27
)

sh 1 0 - 215 - 1
or 6 215
t

ch 1 '\ '\ '\uFFFF'


ar 6 u0 u0 (216 - 1)
00 00
0' 0'
(0
)

in 3 0 - 231 - 1
t 2 231

lo 6 0L - 263 - 1
n 4 263
g

fl 3 0. 1. 3.4028235E
o 2 0F 4E 38
at -
45

d 6 0. 4. 1.79769313
o 4 0 9E 48623157E
u - 308
bl 32
e 4
 Accessible
anywhere in the
class.

 Automatically
13. All numeric data types initialized before
are signed. char is the invoking any
only unsigned integral constructor.
type.
 Static variables
are initialized at
14. Object reference
class load time.
variables are initialized to
null.  Can have the same
name as the class.
15. Octal literals begin
with zero. Hex literals b. Automatic variables
begin with 0X or 0x. method local Must be
initialized explicitly. (Or,
16. Char literals are single compiler will catch it.)
quoted characters or Object references can be
unicode values (begin initialized to null to make
with \u). the compiler happy. The
following code won't
17. A number is by default compile. Specify else part
an int literal, a decimal or initialize the local
number is by default a variable explicitly.
double literal.
public String testMethod (
18. 1E-5d is a valid double int a) {
literal, E2d is not (since it
starts with a letter, String tmp;
compiler thinks that it's
an identifier) if ( a > 0 ) tmp =
"Positive";
19. Two types of
variables. return tmp;

a. Member variables }
Array.length returns int i[][] = { {1,2}, new
· Can have the same name array's size. (Use Vectors int[2] }; // Correct
as a member variable, for dynamic purposes).
resolution is based on int i[] = { 1, 2, 3, 4, } ; //
scope. 24. Array size is never Correct
specified with the
20. Arrays are Java reference variable, it is 28. Array indexes start
objects. If you create an always maintained with with 0. Index is an int
array of 5 Strings, there the array object. It is data type.
will be 6 objects created. maintained in
array.length, which is a 29. Square brackets can
21. Arrays should be final instance variable. come after datatype or
before/after variable
 Declared. (int[] a; 25. Anonymous arrays name. White spaces are
String b[]; Object can be created and used fine. Compiler just ignores
[]c; Size should not like this: new int[] {1,2,3} them.
be specified now) or new int[10]
 Allocated 30. Arrays declared even
(constructed). ( a 26. Arrays with zero as member variables also
= new int[10]; c = elements can be created. need to be allocated
new args array to the main memory explicitly.
String[arraysize] ) method will be a zero
element array if no static int a[];
 Initialized. for (int command parameters are
i = 0; i < a.length; specified. In this case static int b[] = {1,2,3};
a[i++] = 0) args.length is 0.
public static void
22. The above three can
27. Comma after the last main(String s[]) {
be done in one step.
initializer in array
declaration is ignored. System.out.println(a[0]);
int a[] = { 1, 2, 3 }; (or )
// Throws a null pointer
int[] i = new int[2] { 5, exception
int a[] = new int[] { 1, 2,
10}; // Wrong
3 }; But never specify the
System.out.println(b[0]);
size with the new
int i[5] = { 1, 2, 3, 4, 5}; // // This code runs fine
statement.
Wrong
System.out.println(a); //
23. Java arrays are static
int[] i[] = {{}, new int[] Prints 'null'
arrays. Size has to be
{} }; // Correct
specified at compile time.
System.out.println(b); //
Prints a string which is static public void mechanism for reclaiming
returned by toString main(String[] s) memory from objects that
are no longer in use, and
} 35. args array's name is making the memory
not important. args[0] is available for new objects.
31. Once declared and the first argument.
allocated (even for local args.length gives no. of 43. An object being no
arrays inside methods), arguments. longer in use means that
array elements are it can't be referenced by
automatically initialized 36. main method can be any 'active' part of the
to the default values. overloaded. program.

32. If only declared (not 37. main method can be 44. Garbage collection
constructed), member final. runs in a low priority
array variables default to thread. It may kick in
null, but local array 38. A class with a when memory is too low.
variables will not default different main signature No guarantee.
to null. or w/o main method will
compile. But throws a 45. It's not possible to
33. Java doesn't support runtime error. force garbage collection.
multidimensional arrays Invoking System.gc may
formally, but it supports 39. A class without a main start garbage collection
arrays of arrays. From the method can be run by process.
specification - "The JVM, if its ancestor class
number of bracket pairs has a main method. (main 46. The automatic
indicates the depth of is just a method and is garbage collection
array nesting." So this can inherited) scheme guarantees that a
perform as a reference to an object is
multidimensional array. 40. Primitives are passed always valid while the
(no limit to levels of array by value. object is in use, i.e. the
nesting) object will not be deleted
41. Objects (references) leaving the reference
34. In order to be run by are passed by reference. "dangling".
JVM, a class should have a The object reference itself
main method with the is passed by value. So, it 47. There are no
following signature. can't be changed. But, the guarantees that the
object can be changed via objects no longer in use
public static void the reference. will be garbage collected
main(String args[]) and their finalizers
42. Garbage collection is a executed at all. gc might
not even be run if the being garbage collected. list that can be thrown by
program execution does this method.
not warrant it. Thus any 51. We can set the
memory allocated during reference variables to 54. finalize is called only
program execution might null, hinting the gc to once for an object. If any
remain allocated after garbage collect the exception is thrown in
program termination, objects referred by the finalize, the object is still
unless reclaimed by the variables. Even if we do eligible for garbage
OS or by other means. that, the object may not collection (at the
be gc-ed if it's attached to discretion of gc)
48. There are also no a listener. (Typical in case
guarantees on the order of AWT components) 55. gc keeps track of
in which the objects will Remember to remove the unreachable objects and
be garbage collected or listener first. garbage-collects them,
on the order in which the but an unreachable object
finalizers are called. 52. All objects have a can become reachable
Therefore, the program finalize method. It is again by letting know
should not make any inherited from the Object other objects of its
decisions based on these class. existence from its finalize
assumptions. method (when called by
53. finalize method is gc). This 'resurrection'
49. An object is only used to release system can be done only once,
eligible for garbage resources other than since finalize is called
collection, if the only memory. (such as file only one for an object.
references to the object handles and network
are from other objects connections) The order in 56. finalize can be called
that are also eligible for which finalize methods explicitly, but it does not
garbage collection. That are called may not reflect garbage collect the
is, an object can become the order in which objects object.
eligible for garbage are created. Don't rely on
collection even if there it. This is the signature of 57. finalize can be
are references pointing to the finalize method. overloaded, but only the
the object, as long as the method with original
objects with the protected void finalize() finalize signature will be
references are also throws Throwable { } called by gc.
eligible for garbage
collection. In the descendents this 58. finalize is not
method can be protected implicitly chained. A
50. Circular references do or public. Descendents finalize method in sub-
not prevent objects from can restrict the exception class should call finalize
in super class explicitly as of statement. checking is done at
its last action for proper compile and runtime to
functioning. But compiler x = 5; y = 0; y = x++; Result ensure type-safety.
doesn't enforce this check. will be x = 6, y = 5
2. Arithmetic operators -
*, /, %, +, -
59. x = 5; y = 0; y = ++x; Result
System.runFinalization will be x = 6, y = 6 · Can be applied to all
can be used to run the numeric types.
finalizers (which have not Implicit narrowing
been executed before) for conversion is done, when · Can be applied to only
the objects eligible for applied to byte, short or the numeric types, except
garbage collection. char. '+' - it can be applied to
Strings as well.
Chapter 2 Operators 1.2 Unary minus and
and assignments unary plus + -
· All arithmetic operations
The Java programming + has no effect than to are done at least with
language has included stress positivity. 'int'. (If types are smaller,
five simple arithmetic promotion happens.
operators like + - negates an expression's Result will be of a type at
(addition), - value. (2's complement least as wide as the wide
(subtraction), * for integral expressions) type of operands)
(multiplication), /
1.3 Negation !
(division) · Accuracy is lost silently
Inverts the value of a when arithmetic
1. Unary operators
boolean expression. overflow/error occurs.
1.1 Increment and Result is a nonsense value.
1.4 Complement ~
Decrement operators ++
-- · Integer division by zero
Inverts the bit pattern of
throws an exception.
an integral expression.
We have postfix and
(1's complement - 0s to 1s
prefix notation. In post-fix · % - reduce the
and 1s to 0s)
notation value of the magnitude of LHS by the
variable/expression is magnitude of RHS.
Cannot be applied to non-
modified after the value is (continuous subtraction)
integral types.
taken for the execution of
statement. In prefix 1.5 Cast () · % - sign of the result
notation, value of the entirely determined by
variable/expression is Persuades compiler to sign of LHS
modified before the value allow certain
is taken for the execution assignments. Extensive · 5 % 0 throws an
ArithmeticException. that object is called. changes the sign of a
("Vel" + 3 will work.) negative number to be
· Floating point positive. So don't use it
calculations can produce · Be aware of associativity with negative numbers, if
NaN (square root of a when multiple operands you want to preserve the
negative no) or Infinity are involved. sign. Also don't use it with
( division by zero). Float types smaller than int.
and Double wrapper System.out.println( 1 + 2 (Since types smaller than
classes have named + "3" ); // Prints 33 int are promoted to an int
constants for NaN and before any shift operation
infinities. System.out.println( "1" + and the result is cast
2 + 3 ); // Prints 123 down again, so the end
· NaN's are non-ordinal result is unpredictable.)
3. Shift operators - <<, >>,
for comparisons. x ==
>>>
Float.NaN won't work. · Shift operators can be
Use Float.IsNaN(x) But · << performs a signed left applied to only integral
equals method on shift. 0 bits are brought in types.
wrapper objects(Double from the right. Sign bit
or Float) with NaN values (MSB) is preserved. Value · -1 >> 1 is -1, not 0. This
compares Nan's correctly. becomes old value * 2 ^ x differs from simple
where x is no of bits division by 2. We can
· Infinities are ordinal. X shifted. think of it as shift
== operation rounding down.
Double.POSITIVE_INFINI · >> performs a signed
TY will give expected right shift. Sign bit is · 1 << 31 will become the
result. brought in from the left. minimum value that an
(0 if positive, 1 if negative. int can represent. (Value
· + also performs String Value becomes old value / becomes negative, after
concatenation (when any 2 ^ x where x is no of bits this operation, if you do a
operand in an expression shifted. Also called signed right shift sign bit
is a String). The language arithmetic right shift. is brought in from the left
itself overloads this and the value remains
operator. toString method · >>> performs an negative.)
of non-String object unsigned logical right
operands are called to shift. 0 bits are brought in · Negative numbers are
perform concatenation. In from the left. This represented in two's
case of primitives, a operator exists since Java complement notation.
wrapper object is created doesn't provide an (Take one's complement
with the primitive value unsigned data type and add 1 to get two's
and toString method of (except char). >>> complement)
can be cast to RHS type.
· Shift operators never · If x instanceof Y is not
shift more than the · LHS should be an object allowed by compiler, then
number of bits the type of reference expression, Y y = (Y) x is not a valid
result can have. ( i.e. int variable or an array cast expression. If x
32, long 64) RHS operand reference. instanceof Y is allowed
is reduced to RHS % x and returns false, the
where x is no of bits in · RHS should be a class above cast is valid but
type of result. (abstract classes are fine), throws a
an interface or an array ClassCastException at
int x; type, castable to LHS runtime. If x instanceof Y
object reference. Compiler returns true, the above
x = x >> 33; // Here error if LHS & RHS are cast is valid and runs fine.
actually what happens is unrelated.
4.3 Equality comparisons
x >> 1
- ==, !=
· Can't use java.lang.Class
4. Comparison operators -
or its String name as RHS. · For primitives it's a
all return boolean type.
straightforward value
4.1 Ordinal comparisons - · Returns true if LHS is a comparison. (promotions
<, <=, > , >= class or subclass of RHS apply)
class
· Only operate on numeric
· For object references,
types. Test the relative · Returns true if LHS this doesn't make much
value of the numeric implements RHS sense. Use equals method
operands. interface. for meaningful
comparisons. (Make sure
· Arithmetic promotions · Returns true if LHS is an that the class implements
apply. char can be array reference and of equals in a meaningful
compared to float. type RHS. way, like for X.equals(Y)
4.2 Object type to be true, Y instance of X
· x instanceof must be true as well)
comparison - instanceof
Component[] - legal.
· Tests the class of an · For String literals, ==
object at runtime. · x instanceof [] - illegal. will return true, this is
Checking is done at Can't test for 'any array of because of compiler
compile and runtime any type' optimization.
same as the cast operator.
· Returns false if LHS is 5. Bit-wise operators - &,
· Returns true if the object null, no exceptions are ^, |
denoted by LHS reference thrown.
· Operate on numeric and · That's why there's no · Simple assignment =.
boolean operands. logical XOR operator.
Both bits need to be · op= calculate and assign
· & - AND operator, both known to calculate the operators extended
bits must be 1 to produce result. assignment operators.
1.
· Short-circuiting doesn't · *=, /=, %=, +=, -=
· | - OR operator, any one change the result of the
bit can be 1 to produce 1. operation. But side effects · x += y means x = x + y.
might be changed. (i.e. But x is evaluated only
· ^ - XOR operator, any some statements in RHS once. Be aware.
one bit can be 1, but not might not be executed, if
both, to produce 1. short-circuit happens. Be · Assignment of reference
careful) variables copies the
· In case of booleans true reference value, not the
7. Ternary operator
is 1, false is 0. object body.
· Format a = x ? b : c ;
· Can't cast any other type · Assignment has value,
to boolean. · x should be a boolean value of LHS after
expression. assignment. So a = b = c =
6. Short-circuit logical
0 is legal. c = 0 is executed
operators - &&, ||
· Based on x, either b or c first, and the value of the
· Operate only on boolean is evaluated. Both are assignment (0) assigned
types. never evaluated. to b, then the value of that
assignment (again 0) is
· RHS might not be · b will be assigned to a if assigned to a.
evaluated (hence the x is true, else c is assigned
name short-circuit), if the to a. · Extended assignment
result can be determined operators do an implicit
only by looking at LHS. · b and c should be cast. (Useful when applied
assignment compatible to to byte, short or char)
· false && X is always a.
false. byte b = 10;
· b and c are made
· true || X is always true. identical during the b = b + 10; // Won't
operation according to compile, explicit cast
· RHS is evaluated only if promotions. required since the
the result is not certain expression evaluates to an
8. Assignment operators. int
from the LHS.
b += 10; // OK, += does an final public static void Type of Ope Ass
implicit cast from int to main(String args[]) { Operators rat ocia
byte ors tivit
int i = 0; y
9. General
Postfix [] . Left
· In Java, No overflow or i = i++;
operators (par to
underflow of integers ame Righ
happens. i.e. The values i = i++;
ters t
wrap around. Adding 1 to ) ++
the maximum int value i = i++;
--
results in the minimum
value. System.out.println(i); // Prefix ++  Righ
prints 0, since = operator Unary -- + t to
· Always keep in mind has the lowest operators - ~ ! Left
that operands are precedence.
Object new Righ
evaluated from left to creation (typ t to
right, and the operations int array[] = new int[5];
and cast e) Left
are executed in the order
of precedence and int index = 0; Multiplicat * / Left
associativity. ion/Divisio % to
array[index] = index = n/Modulus Righ
· Unary Postfix operators 3; // 1st element gets t
and all binary operators assigned to 3, not the 4th
Addition/S +- Left
(except assignment element
ubtraction to
operators) have left to
Righ
right assoiciativity. for (int c = 0; c <
array.length; c++) t

· All unary operators Shift >> Left


(except postfix operators), System.out.println(array[ >>> to
assignment operators, c]); << Righ
ternary operator, object t
creation and cast System.out.println("index
is " + index); // prints 3 Relational < <= Left
operators have right to
> >= to
left assoiciativity.
} inst Righ
anc t
· Inspect the following
} eof
code.
  Equality == ! Left
public class Precedence { = to
Righ
t &= class is not accessible, the
^= | members are not
Bit- & Left
= accessible, even though
wise/Boole to
they are declared public.
an AND Righ
t ·         If no access
modifier is specified, then
Bit- ^ Left
Chapter 3 -  Modifiers the accessibility is default
wise/Boole to
package visibility. All
an XOR Righ 1.        Modifiers are Java classes in the same
t keywords that provide package can access the
Bit- | Left information to compiler feature. It's called as
wise/Boole to about the nature of the friendly access. But
an OR Righ code, data and classes. friendly is not a Java
t keyword. Same directory
2.        Access modifiers -
is same package in Java's
Logical && Left public, protected, private
consideration.
AND to
·         Only applied to
(Short- Righ ·         'private' means
class level variables.
circuit or t only the class can access
Method variables are
Conditiona it, not even sub-classes. 
visible only inside the
l) So, it'll cause access
method.
denial to a sub-class's
Logical OR || Left
·         Can be applied to own variable/method.
(Short- to
circuit or Righ class itself (only to inner
·         These modifiers
Conditiona t classes declared at class
dictate, which classes can
l) level, no such thing as
access the features. An
protected or private top
Ternary ?: Righ instance of a class can
level class)
t to access the private
Left ·         Can be applied to features of another
methods and instance of the same class.
Assignmen = += Righ constructors.
t -= t to 'protected' means all
*= / Left ·         If a class is classes in the same
= accessible, it doesn't package (like default)
%= mean, the members are and sub-classes in any
<<= also accessible. Members' package can access the
>>= accessibility determines features. But a subclass in
>>> what is accessible and another package can
= what is not. But if the access the protected
members in the super- ·         You can declare a initializer or in every
class via only the variable in any scope to constructor. Otherwise
references of subclass or be final. the compiler will
its subclasses. A subclass complain.
·         You may, if
in the same package
necessary, defer ·         A blank final is a
doesn't have this
initialization of a final final variable whose
restriction. This ensures
local variable. Simply declaration lacks an
that classes from other
declare the local variable initializer.
packages are accessing
and initialize it later (for
only the members that ·         Final variables
final instance variables.
are part of their that are not assigned a
You must initialize them
inheritance hierarchy. value at the declaration
at the time of declaration
and method arguments
·         Methods cannot be or in constructor).
that are marked final are
overridden to be more
·         final variables called blank final
private. Only the direction
cannot be changed (result variables. They can be
shown in following figure
in a compile-time error if  assigned a value at most
is permitted from parent
you do so ) once.
classes to sub-classes.
·         final methods ·         Local variables
private à friendly
cannot be overridden. can be declared final as
(default) à protected à
well.
public ·         Method arguments
marked final are read- ·         If a final variable
                Parent
only. Compiler error, if holds a reference to an
classes                          
trying to assign values to object, then the state of
                                   
final arguments inside the the object may be
      Sub-classes
method. changed by operations on
3.        final the object, but the
·         Member variables
variable will always refer
·         final features marked final are not
to the same object.
cannot be changed. initialized by default.
They have to be explicitly ·         This applies also to
·         The final modifier
assigned a value at arrays, because arrays
applies to classes,
declaration or in an are objects; if a final
methods, and variables.
initializer block. Static variable holds a reference
·         final classes finals must be assigned to to an array, then the
cannot be sub-classed. a value in a static components of the array
initializer block, instance may be changed by
finals must be assigned a operations on the array,
value in an instance but the variable will
always refer to the same ·         Can be applied to variables, free floating
array classes and methods. code-block (static
initializer)
·          A blank final ·         For deferring
instance variable must be implementation to sub- ·         Static variables
definitely assigned  at the classes. are initialized at class
end of every constructor load time. A class has only
·         Opposite of final,
of the class in which it is one copy of these
final can't be sub-classed,
declared; otherwise a variables.
abstract must be sub-
compile-time error
classed. ·         Static methods can
occurs.
access only static
·         A class should be
·         A class can be variables. (They have no
declared abstract,
declared final if its this)
definition is complete and 1.        if it has any
·         Access by class
no subclasses are desired abstract methods.
name is a recommended
or required.
2.        if it doesn't way to access static
·         A compile-time provide implementation methods/variables.
error occurs if the name to any of the abstract
·         Static initializer
of a final class appears in methods it inherited
code is run at class load
the extends clause of
3.        if it doesn't time.
another class declaration;
this implies that a final provide implementation
·         Static methods
class cannot have any to any of the methods in
may not be overridden to
subclasses. an interface that it says
be non-static.
implementing.
·         A compile-time ·         Non-static
error occurs if a class is ·         Just terminate the
methods may not be
declared both final and abstract method
overridden to be static.
abstract, because the signature with a ';', curly
implementation of such a braces will give a ·         Abstract methods
class could never be compiler error. may not be static.
completed.
·         A class can be ·         Local variables
·         Because a final abstract even if it doesn't cannot be declared as
class never has any have any abstract static.
subclasses, the methods of methods.
·         Actually, static
a final class are never
5.        static methods are not
overridden   
participating in the usual
·         Can be applied to
4.        abstract overriding mechanism of
nested classes, methods,
invoking the methods                 Parent p =                
based on the class of the new Parent(); System.out.println("In
object at runtime. Static Child..doStuff");
                p.doStuff(); //
method binding is done at
This will invoke                
compile time, so the
Parent.doStuff() System.out.println(x);
method to be invoked is
determined by the type of                 p = c;  }
reference variable rather
than the actual type of                 p.doStuff(); //  }
the object it holds at This will invoke
6.        native
runtime. Parent.doStuff(), rather
than ·         Can be applied to
Let's say a sub-class has a Child.doStuff()                methods only. (static
static method which
methods also)
'overrides' a static  }
method in a parent class.  ·         Written in a non-
}
If you have a reference Java language, compiled
variable of parent class class Parent { for a single machine
type and you assign a target type.
child class object to that   static int x = 100;
variable and invoke the ·         Java classes use lot
  public static void
static method, the method of native methods for
doStuff() {
invoked will be the parent performance and for
class method, not the                 accessing hardware Java
child class method.  The System.out.println("In is not aware of.
following code explains Parent..doStuff");
·         Native method
this. signature should be
               
public class System.out.println(x); terminated by a ';', curly
StaticOverridingTest { braces will provide a
 } compiler error.
  public static void
} ·         native doesn't
main(String s[]) {
affect access qualifiers.
class Child extends Parent
                Child c = new Native methods can be
{
Child(); private.
  static int x = 200;
                c.doStuff(); // ·         Can pass/return
This will invoke   public static void Java objects from native
Child.doStuff() doStuff() { methods.

 
·         ·         Used to control e l
System.loadLibrary is access to critical code in p o
used in static initializer multi-threaded programs. t c
code to load native l k
9.        volatile
libraries. If the library is o
not loaded when the ·         Can be applied to c
static method is called, an variables only. a
UnsatisfiedLinkError is l
thrown. ·         Can be applied to a
static variables. n
7.        transient
d
·         Cannot be applied
·         Can be applied to a
to final variables.
class level variables only. n
(Local variables cannot ·         Declaring a o
be declared transient) variable volatile indicates n
that it might be modified y
·         Transient asynchronously, so that m
variables may not be final all threads will get the o
or static.(But compiler correct value of the u
allows the declaration, variable. s
since it doesn't do any c
harm. Variables marked ·         Used in multi- l
transient are never processor environments. a
serialized. Static variables s
M C I V M C F
are not serialized s
o l n a et o r
anyway.) e
d a n r ho n e
if s e i d s e s
·         Not stored as part
i s r a t fl )
of object's persistent
state, i.e. not written out e c b r o p Y Y Y Y Y N
during serialization. r l l u a u
a e c t bl
·         Can be used for s t i ic
security. s o n
e r g p N Y Y Y Y N
8.        synchronized r
s C
·         Can be applied to ( o o
methods or parts of E d t
methods only. x e e
c b ct
e
d n ti s
y c t
(f Y Y Y Y Y N
m a
ri (
o ti
e O
u c
n K
s i
d f
cl n
ly o
a it
) r
s i
a
N s a
ll
o e li
)
a s z
c ) e
c r
a Y Y N Y N N
e )
b (
ss
st E n N N N Y N N
m
r x a
o
a c ti
d
ct e v
if
p e
ie
t
r tr N N Y N N N
a
a
p N Y Y Y Y N n
n
ri o
si
v n
e
a y
n
t m
t
e o
u s N N N Y N Y
fi Y Y Y Y N N s y (
n ( cl n p
a E a c a
l x s h r
c s r t
e e o o
p s n f
t ) iz m
a
e e
n st N Y Y Y N Y
d t
o a (
h s ·         During array
o h creation, for example new
d o int[x], where the
, u dimension expression x
a l must evaluate to an int
l d value.
s b
·         Indexing array
o e
elements, for example
n o
table['a'], where the index
e b
expression must evaluate
e t
to an int value.
d a
t i ·         Individual
o n operands of the shift
s e operators.
p d
e ) Binary numeric
c promotion
v N N Y N N N
if
ol Contexts:
y
a
a ·         Operands of
ti
n arithmetic operators *, / ,
le
o %, + and -
b
j ·         Operands of
e Chapter 4 Converting relational operators <,
c and Casting <= , > and >=
t Unary Numeric ·         Numeric Operands
o Promotion of equality operators ==
n and !=
w Contexts:
h ·         Integer Operands
·         Operand of the
i of bit-wise operators &, ^
unary arithmetic
c and |
operators + and -
h
Conversion of Primitives
a ·         Operand of the
l unary integer bit-wise 1.        3 types of
o complement operator ~ conversion - assignment
c conversion, method call
k
conversion and arithmetic                else if one char e = -1; // this also
promotion operand is float { won't compile, since the
value is not in the range
2.        boolean may not all float; convert the other
of char
be converted to/from any operand to float;
non-boolean type. float f = 1.3; // this won't
}
compile, even though the
3.        Widening
else if one operand is long value is within float
conversions accepted.
{ range. Here range is not 
Narrowing conversions
important, but precision
rejected. all long; convert the other is. 1.3 is by default a
operand to long; double, so a specific cast
4.        byte, short can't
be converted to char and or f = 1.3f will work.
}
vice versa.  ( but can be
float f = 1/3; // this will
cast ) else {
compile, since RHS
5.        Arithmetic all int; convert all to int; evaluates to an int.
promotion
} Float f = 1.0 / 3.0; // this
5.1     Unary operators won't compile, since RHS
6.        When assigning a evaluates to a double.
·         if the operand is literal value to a variable,
byte, short or char  { the range of the variable's 7.        Also when
data type is checked assigning a final variable
convert it to int; against the value of the to a variable, even if the
literal and assignment is final variable's data type
                       }
allowed or compiler will is wider than the variable,
                else { produce an error. if the value is within the
range of the variable an
do nothing; no conversion char c = 3; // this will implicit conversion is
needed; compile, even though a done.
numeric literal is by
} byte b;
default an int since the
5.2     Binary operators range of char will accept
final int a = 10;
the value
·         if one operand is b = a; // Legal, since value
double { int a = 3;
of 'a' is determinable and
all double; convert the char d = a; // this won't within range of b
other operand to double; compile, since we're
final int x = a;
assigning an int to char 
                       }
b = x; // Legal, since value 10.     Can cast any non- instantiate an interface,
of 'x' is determinable and boolean type to another since it is abstract and
within range of b non-boolean type. doesn't provide any
implementation. These
int y; 11.     Cannot cast a
variables can be used to
boolean or to a boolean
final int z = y; hold objects of classes
type.
that implement the
b = z; // Illegal, since interface. The reason for
Conversion of Object
value of 'z' is not having interfaces as types
references
determinable may be, I think, several
12.     Three types of unrelated classes may
 
reference variables to implement the same
8.        Method call denote objects - class, interface and if there's a
conversions always look interface or array type. need to deal with them
for the exact data type or collectively one way of
13.     Two kinds of
a wider one in the method treating them may be an
objects can be created -
signatures. They will not array of the interface type
class or array.
do narrowing conversions that they implement.
to resolve methods, 14.     Two types of
17.     Primitive arrays
instead we will get a conversion - assignment
can be converted to only
compile error. and method call.
the arrays of the same
Here is the figure of 15.     Permitted if the primitive type. They
allowable primitive direction of the cannot be converted to
conversion. conversion is 'up' the another type of primitive
inheritance hierarchy. array. Only object
byte à short à int à long à reference arrays can be
Means that types can be
float à double converted / cast.
assigned/substituted to
                            only super-types - super-
18.     Primitive arrays
classes or interfaces. Not
           char can be converted to an
the other way around,
Object reference, but not
explicit casting is needed
Casting of Primitives to an Object[] reference.
for that.
This is because all arrays
9.        Needed with
16.     Interfaces can be (primitive arrays and
narrowing conversions.
used as types when Object[]) are extended
Use with care - radical
declaring variables, so from Object.
information loss. Also can
they participate in the
be used with widening Casting of Object
object reference
conversions, to improve references
conversion. But we cannot
the clarity of the code.
19.     Allows super-types ·         We can always ·         any super-class
to be assigned to cast between an interface type reference, (including
subtypes. Extensive and a non-final object. Object)
checks done both at
Run-time rules ·         any sub-class type
compile and runtime. At
reference, with casting,
compile time, class of the ·         If new type is a
with runtime check
object may not be known, class, the class of the
so at runtime if checks expression being ·         an interface
fail, a ClassCastException converted must be new reference, if the class
is thrown. type or extend new type. implements that interface
20.     Cast operator, ·         If new type is an ·         any interface
instanceof operator and interface, the class of the reference, with casting,
the == operator behave expression being with runtime check
the same way in allowing converted must (except if the class is final
references to be the implement the interface. and doesn't implement
operands of them. You the interface)
cannot cast or apply An Object reference can
instanceof or compare be converted to: An Interface reference
unrelated references, (java.lang.Object) can be converted to:
sibling references or any
·         an Object ·         an Object
incompatible references.
reference reference
Compile-time Rules
·         a Cloneable ·         a super-interface
·         When old and new interface reference, with reference
types are classes, one casting, with runtime
·         any
class must be the sub- check
interface/class reference
class of the other.
·         any class with casting, with
·         When old and new reference, with casting, runtime check (except if
types are arrays, both with runtime check the class is final and
must contain reference doesn't implement the
·         any array
types and it must be legal interface)
referenece, with casting,
to cast between those
with runtime check A Primitive Array
types (primitive arrays
reference can be
cannot be cast, conversion ·         any interface
converted to:
possible only between reference, with casting,
same type of primitive with runtime check ·         an Object
arrays). reference
A Class type reference can
be converted to:
·         a Cloneable enclosing block, therefore ·         In the first section
interface reference visible in a nested block of for statement, we can
cannot be re-declared have a list of declaration
·         a primitive array
inside the nested block. statements or a list of
reference of the same type
expression statements,
·         A local variable in
An Object Array reference but not both. We cannot
a block may be re-
can be converted to: mix them.
declared in another local
·         an Object block, if the blocks are ·         All expressions in
reference disjoint. the third section of for
statement will always
·         a  Cloneable ·         Method
execute, even if the first
interface reference parameters cannot be re-
expression makes the loop
declared.
condition false. There is
·         a super-class
1.        Loop constructs no short -circuit here.
Array reference, including
an Object Array reference 2.        Selection
·         3 constructs - for,
while, do Statements
·         any sub-class
Array reference with ·         if takes a boolean
·         All loops are
casting, with runtime arguments. Parenthesis
controlled by a boolean
check required. else part is
expression.
optional. else if structure
Chapter 5 Flow Control
·         In while and for, provides multiple
and Exceptions
the test occurs at the top, selective branching.
   Unreachable so if the test fails at the
first time, body of the loop ·         switch takes an
statements produce a
might not be executed at argument of byte, short,
compile-time error.
all. char or int.(assignment
while (false) { x = 3; } // compatible to int)
won't compile ·         In do, test occurs
at the bottom, so the body ·         case value should
for (;false;) { x =3; } // is executed at least once. be a constant expression
won't compile that can be evaluated at
·         In for, we can compile time.
if (false) {x = 3; } // will declare multiple variables
compile, to provide the in the first part of the loop ·         Compiler checks
ability to conditionally separated by commas, each case value against
compile the code. also we can have multiple the range of the switch
statements in the third expression's data type. 
·         Local variables The following code won't
part separated by
already declared in an compile.
commas.
byte b; 3.        Branching ·         An exception is an
statements event that occurs during
switch (b) {
the execution of a
·         break statement
   case 200: // 200 not in program that disrupts the
can be used with any kind
range of byte normal flow of
of loop or a switch
instructions.
   default: statement or just a
labeled block. ·         There are 3 main
} advantages for
·         continue
exceptions:
·         We need to place a statement can be used
break statement in each with only a loop (any kind 1.        Separates error
case block to prevent the of loop). handling code from
execution to fall through "regular" code
other case blocks. But this ·         Loops can have
is not a part of switch labels. We can use break 2.        Propagating
statement and not and continue statements errors up the call stack
enforced by the compiler. to branch out of multiple (without tedious
levels of nested loops programming)
·         We can have using labels.
multiple case statements 3.        Grouping error
execute the same code. ·         Names of the types and error
Just list them one by one. labels follow the same differentiation
rules as the name of the
·         default case can be ·         An exception
variables.(Identifiers)
placed anywhere. It'll be causes a jump to the end
executed only if none of ·         Labels can have of try block. If the
the case values match. the same name, as long as exception occurred in a
they don't enclose one method called from a try
·         switch can be another. block, the called method
nested. Nested case labels is abandoned.
are independent, don't ·         There is no
clash with outer case restriction against using ·         If there's a catch
labels. the same identifier as a block for the occurred
label and as the name of a exception or a parent
·         Empty switch package, class, interface, class of the exception, the
construct is a valid method, field, parameter, exception is now
construct. But any or local variable. considered handled.
statement within the
switch block should come 4.        Exception ·         At least one 'catch'
under a case label or the Handling block or one 'finally' block
default case label. must accompany a 'try'
statement. If all 3 blocks thread is killed and can be thrown within the
are present, the order is message stack trace is scope of that method.
important. dumped to System.err.
·         All objects of type
(try/catch/finally)
·         Use throw new java.lang.Exception are
·         finally and catch xxxException() to throw checked exceptions.
can come only with try, an exception. If the (Except the classes under
they cannot appear on thrown object is null, a java.lang.RuntimeExcepti
their own. NullPointerException will on) If any method that
be thrown at the handler. contains lines of code that
·         Regardless of
might throw checked
whether or not an ·         If an exception
exceptions, compiler
exception occurred or handler re-throws an
checks whether you've
whether or not it was exception (throw in a
handled the exceptions or
handled, if there is a catch block), same rules
you've declared the
finally block, it'll be apply. Either you need to
methods as throwing the
executed always. (Even if have a try/catch within
exceptions. Hence the
there is a return the catch or specify the
name checked exceptions.
statement in try block). entire method as
throwing the exception ·         If there's no code
·         System.exit() and
that's being re-thrown in in try block that may
error conditions are the
the catch block. Catch throw exceptions
only exceptions where
blocks at the same level specified in the catch
finally block is not
will not handle the blocks, compiler will
executed.
exceptions thrown in a produce an error. (This is
·         If there was no catch block - it needs its not the case for super-
exception or the exception own handlers. class Exception)
was handled, execution
·         The method ·        
continues at the
fillInStackTrace() in Java.lang.RuntimeExcep
statement after the
Throwable class throws a tion and java.lang.Error
try/catch/finally blocks.
Throwable object. It will need not be handled or
·         If the exception is be useful when re- declared.
not handled, the process throwing an exception or
·         An overriding
repeats looking for next error.
method may not throw a
enclosing try block up the
·         The Java language checked exception unless
call hierarchy. If this
requires that methods the overridden method
search reaches the top
either catch or specify all also throws that
level of the hierarchy (the
checked exceptions that exception or a super-class
point at which the thread
of that exception. In other
was created), then the
words, an overriding  |        Error IndexOutOfBoundsExcepti
method may not throw on--
 |
checked exceptions that >ArrayIndexOutOfBounds
are not thrown by the  | Exception,
overridden method. If we StringIndexOutOfBounds
allow the overriding Exception-- Exception
methods in sub-classes to >ClassNotFoundException
, IOException--
throw more general
ClassNotSupportedExcept >EOFException,
exceptions than the
ion, FileNotFoundException,
overridden method in the
IllegalAccessException, InterruptedIOException,
parent class, then the
InstantiationException, UTFDataFormatExceptio
compiler has no way of
IterruptedException, n,
checking the exceptions
NoSuchMethodException, MalformedURLException,
the sub-class might
RuntimeException, ProtocolException,
throw. (If we declared a
AWTException, SockException,
parent class variable and
IOException UnknownHostException,
at runtime it refers to
UnknownServiceExceptio
sub-class object) This
RuntimeException-- n.
violates the concept of
>EmptyStackException,
checked exceptions and Chapter 6 - Objects and
NoSuchElementException,
the sub-classes would be Classes  (Part 1)
ArithmeticException,
able to by-pass the
ArrayStoreException,
enforced checks done by Implementing OO
ClassCastException,
the compiler for checked relationships
IllegalArgumentExceptio
exceptions. This should
n, ·         "is a" relationship
not be allowed.
IllegalMonitorStateExcep is implemented by
Here is the exception tion, inheritance (extends
hierarchy. keyword)
IndexOutOfBoundsExcepti
Object on, ·         "has a"
NegativeArraySizeExcepti relationship is
   | on, NullPointerException, implemented by providing
SecurityException. the class with member
   |
variables.
IllegalArgumentExceptio
Throwable  
n-- Overloading and
 |            |        
>IllegalThreadStateExcep Overriding
 |            |  tion,
·         Overloading is an
NumberFormatException
 |            | example of polymorphism.
(operational / methods. other overridden
parametric) by method by
Excep Overriding
provid super.met
·         Overriding is an tion methods
ing hodName(
example of runtime list may not
appro ), this can
polymorphism (inclusive) may throw
priate be used
vary more
·         A method can have argu only to
freely. checked
the same name as ment access the
exceptions
another method in the list. immediate
than the
same class, provided it super-
overridden
forms either a valid class's
methods.
overload or override method.
Just Related super.super
  the directly to won't
name sub- work. Also,
Overl Overridin
is classing. a class
oadin g
reuse Overrides outside the
g
d. the parent inheritance
Signat Signature Metho class hierarchy
ure has to be ds are method. can't use
has to the same. indep Resolved at this
be (including enden run-time technique.
differe the return t based on
Metho static
nt. type) metho type of the
ds can methods
Just a ds. object.
be don't
differe Resolv
static participate
nce in ed at
or in
return compi
non- overriding,
type is le-
static. since they
not time
Since are
enoug based
the resolved at
h. on
metho compile
metho
Access Overriding ds are time based
d
ibility methods indep on the type
signat
may cannot be enden of
ure.
vary more t, it reference
freely. private Can Overriding doesn' variable. A
than the call method t static
overridden each can call matte method in
r. But a sub- signatures reference variable type.
if two class can't are Only methods are
metho use 'super' different, it resolved at run-time.
ds (for the would have
public class Shadow {
have same formed a
the reason valid   public static void
same that it overload) main(String s[]) {
signat can't use
There' Each                 S1 s1 = new
ure, 'this' for)
s no parent S1();
declar
  limit class
ing
on method                 S2 s2 = new
one as Remembe numb may be S2();
static r that a er of overridden
and static               
overlo at most
anoth method System.out.println(s1.s); /
aded once in any
er as can't be / prints S1
metho sub-class.
non- overridde ds a (That is,                
static n to be class you cannot System.out.println(s1.getS
does non-static can have two ()); // prints S1
not and a non- have. identical
provid static                 
methods in
e a method System.out.println(s2.s); /
the same
valid can't be / prints S2
class)
overlo overridde
ad. n to be ·         Variables can also                
It's a static. In be overridden, it's known System.out.println(s2.getS
compi other as shadowing or hiding. ()); // prints S2
le words, a But, member variable
                 s1 = s2;
time static references are resolved at
error. method compile-time. So at the                 
and a non- runtime, if the class of the System.out.println(s1.s)
static object referred by a ; // prints S1, not S2 -
method parent class reference
variable, is in fact a sub-                                    
cannot
class having a shadowing                        // since
have the
member variable, only the variable is resolved at
same name
parent class variable is compile time
and
signature accessed, since it's
(if already resolved at
compile time based on the
                 class and if we call the   public static void
System.out.println(s1.g method from sub-class main(String s[]) {
etS()); // prints S2 - reference variable, the
                S2 s2 = new
method will return only
                                    S2();
the super-class member
                                 
variable value. For                 s2.display(); 
// since method is
explanation, see the // Produces an output -
resolved at run
following points. S1, S2
time               
·         Also, methods                 S1 s1 = new
 }
access variables only in S1();
} context of the class of the
object they belong to. If a                
  sub-class method calls System.out.println(s1.getS
explicitly a super class ()); // prints S1
class S1 {
method, the super class
               
  public String s = "S1"; method always will
System.out.println(s2.getS
access the super-class
  ()); // prints S1 - since
variable. Super class
super-class method
  public String getS() { methods will not access
the shadowing variables                      // always
                return s; declared in subclasses accesses super-class
because they don't know variable
 }
about them. (When an
object is created,  }
}
instances of all its super- }
 class S2 extends S1{ classes are also created.)
But the method accessed class S1 {
  public String s = "S2";
will be again subject to
  String s = "S1";
  dynamic lookup. It is
always decided at   public String getS() {
  public String getS() { runtime which
implementation is called.                 return s;
                return s;
(Only static methods are
 }
 } resolved at compile-time)
  void display() {
}                                 
public class Shadow2 {                
In the above code, if we
System.out.println(s);
didn't have the overriding   String s = "main";
getS() method in the sub-  }
} ·         JVM knows about object, not the type of
the variable's real type at reference variable. So it is
class S2 extends S1{
any time since when it not at all possible to
  String s = "S2"; allocates memory for an access a method in a
object, it also marks the super-super-class from
  void display() { type with it. Objects a subclass.
always know 'who they
                 public class ShadowTest
are'. This is the basis of
super.display();   // {
instanceof operator.
Prints S1
                public static
·         Sub-classes can
                void main(String s[]){
use super keyword to
System.out.println(s); //
access the shadowed                                
prints S2
variables in super-classes. new STChild().demo();
 } This technique allows for
accessing only the                 }
} immediate super-class.
}
·         With OO super.super is not valid.
languages, the class of the But casting the 'this' class STGrandParent {
object may not be known reference to classes up
above the hierarchy will                 double wealth
at compile-time (by virtue
do the trick. By this way, = 50000.00;
of inheritance). JVM from
the start is designed to variables in super-                 public double
support OO. So, the JVM classes above any level getWealth() {
insures that the method can be accessed from a
sub-class, since                                
called will be from the
variables are resolved System.out.println("Gran
real class of the object
at compile time, when dParent-" + wealth);
(not with the variable
type declared). This is we cast the 'this'
                               
accomplished by virtual reference to a super-
return wealth;
method invocation (late super-class, the
binding). Compiler will compiler binds the                 }
form the argument list super-super-class
variable. But this }
and produce one method
invocation instruction - technique is not possible
class STParent extends
its job is over. The job of with methods since
STGrandParent {
identifying and calling the methods are resolved
proper target code is always at runtime, and                 double wealth
performed by JVM. the method gets called = 100000.00;
depends on the type of
                public double // Compiler error, andParent)
getWealth() { GrandParent method (this)).wealth);               
cannot be accessed
                                }
System.out.println("Paren                                 /
}
t-" + wealth); /super.super.getWealth();
 
                                                                /
return wealth; / Calls Child method, due ·         An inherited
to dynamic method method, which was not
                }
lookup abstract on the super-
} class, can be declared
((STParent)this).getWeal
abstract in a sub-class
class STChild extends th();
(thereby making the
STParent {
// Calls Child method, due sub-class abstract).
                double wealth to dynamic method There is no restriction.
= 200000.00; lookup
·         In the same
                  token, a subclass can be
((STGrandParent)this).ge declared abstract
                public double tWealth();     regardless of whether
getWealth() { the super-class was
                                
abstract or not.
                                System.out.println(wealth
System.out.println("Child- ); // Prints Child wealth ·         Private members
" + wealth); are not inherited, but they
                               
do exist in the sub-classes.
                                System.out.println(super.
Since the private
return wealth; wealth); // Prints Parent
methods are not
wealth
                } inherited, they cannot
                // Prints be overridden. A method
                 public void in a subclass with the
Parent wealth
demo() { same signature as a
System.out.println(((STPa private method in the
                               
rent)(this)).wealth); super-class is essentially a
getWealth(); // Calls
Child method new method, independent
// Prints GrandParent
from super-class, since the
wealth
                                private method in the
super.getWealth(); //                                 super-class is not visible
Calls Parent method System.out.println(((STGr in the sub-class.
 public class PrivateTest { implementation always overrides super-class hi,
calls superclass hello calls subclass hello
                public static
void main(String s[]){                                                                
hello(); try {
                               
new PTSuper().hi(); //                 }                                    
Prints always Super              hello();
                private void
                                hello() { // This method is                                 }
new PTSub().hi(); // not inherited by
                               
Prints Super when subclasses, but exists in
catch(Exception e) {}
subclass doesn't have hi them.
method                  }
                                   
                                                 // Commenting                  void hello()
                              // out both the methods in throws Exception { //
Prints Sub when subclass the subclass show this. This method is
has hi method independent from super-
                                   
class hello
                                             // The test will
PTSuper sup; then print "hello-Super"                                    
for all three calls                              //
                               
Evident from, it's allowed
sup = new PTSub();                                    
to throw Exception
             // i.e. Always
                               
the super-class                                
sup.hi(); // Prints Super
implementations are System.out.println("hello-
when subclass doesn't
called Sub");
have hi method
                                                }
                                   
System.out.println("hello-
             // Prints Sub }
Super");
when subclass has hi
method                 }  

                } }  ·         Private methods


are not overridden, so
} class PTSub extends calls to private methods
PTSuper { are resolved at compile
 class PTSuper {
time and not subject to
                public void
                public void dynamic method lookup.
hi() { // This method
hi() { // Super-class
See the following                 public int g() (arguments)'. If you use
example. { return f(); } this, it must be the first
statement in the
              public class }
constructor. This
Poly {
 class PolyC extends PolyB construct can be used
                public static { only from within a
void main(String args[]) { constructor.
                public int f() {
                                return 2; } ·         A constructor
PolyA ref1 = new PolyC(); can't call the same
} constructor from within.
                                Compiler will say '
Part2
PolyB ref2 = (PolyB)ref1; recursive constructor
       Constructors are not invocation'
                                
inherited as normal
System.out.println(ref2.g( ·         A constructor can
methods, they have to be
)); // This prints 1 call the parent class
defined in the class itself.
constructor explicitly by
                                   
·         If you define no using 'super
                                   
constructors at all, then (arguments)'. If you do
          // If f() is not
the compiler provides a this, it must be first the
private in PolyB, then
default constructor with statement in the
prints 2
no arguments. Even if, constructor. This
                } you define one construct can be used
constructor, this default is only from within a
} constructor.
not provided.
 class PolyA { ·         Obviously, we
·         We can't compile a
                private int f() sub-class if the immediate can't use both this and
{ return 0; } super-class doesn't have a super in the same
no argument default constructor. If compiler
                public int g() constructor, and sub-class sees a this or super, it
{ return 3; } constructors are not won't insert a default
calling super or this call to super().
}
explicitly (and expect the
·         Constructors can't
 class PolyB extends PolyA compiler to insert an
have a return type. A
{ implicit super() call )
method with a class
                private int f() ·         A constructor can name, but with a return
{ return 1; } call other overloaded type is not considered a
constructors by 'this constructor, but just a
method by compiler. §         Cannot pass on referencing of methods is
Expect trick questions the checked exceptions. allowed.
using this. Must catch and handle
·         Order of code
them.
·         Constructor body execution (when creating
can have an empty 2.       Static initializer an object) is a bit tricky.
return statement. blocks.
1.        static variables
Though void cannot be
§         Used to initialize initialization.
specified with the
static variables and load
constructor signature, 2.        static initializer
native libraries.
empty return statement is block execution. (in the
acceptable. §         Cannot pass on order of declaration, if
the checked exceptions. multiple blocks found)
·         Only modifiers
Must catch and handle
that a constructor can 3.        constructor
them.
have are the accessibility header ( super or this -
modifiers. 3.       Instance initializer implicit or explicit )
blocks.
·         Constructors 4.        instance variables
cannot be overridden, §         Used to factor out initialization / instance
since they are not code that is common to initializer block(s)
inherited. all the constructors. execution
·         Initializers are §         Also useful with 5.        rest of the code in
used in initialization of anonymous classes since the constructor
objects and classes and to they cannot have
define constants in Interfaces
constructors.
interfaces. These
initializers are : §         All constructors
must declare the Part 3
1.       Static and Instance uncaught checked
variable initializer exceptions, if any. Interfaces:
expressions.
§         Instance ·         All methods in an
§         Literals and Initializers in anonymous interface are implicitly
method calls to initialize classes can throw any public, abstract, and
variables. exception. never static.

§         Static variables ·         In all the ·         All variables in an


can be initialized only by initializers, forward interface are implicitly
static method calls. referencing of variables is static, public, final. They
not allowed. Forward cannot be transient or
volatile. A class can methods can specify sub- ·         Declared as a class
shadow the variables it set of overridden member with static
inherits from an interface, method's exceptions, here modifier.
with its own variables. none is a sub-set). But if
·         Just like other
the interface didn't
·         A top-level static features of a class.
specify any exception list
interface itself cannot be Can be accessed /
for a method, then the
declared as static or final instantiated without an
class cannot throw any
since it doesn't make instance of the outer
exceptions.
sense. class. Can access only
·         All interface static members of outer
·         Declaring
methods should have class. Can't access
parameters to be final
public accessibility when instance variables or
is at method's
implemented in class. methods.
discretion, this is not
part of method ·         Interfaces cannot ·         Very much like
signature. be declared final, since any-other package level
they are implicitly class / interface. Provide
·         Same case with
abstract. an extension to packaging
final, synchronized,
by the modified naming
native. Classes can ·         A class can
scheme at the top level.
declare the methods to be implement two interfaces
final, synchronized or that have a method with ·         Classes can
native whereas in an the same signature or declare both static and
interface they cannot be variables with the same non-static members.
specified like that. (These name.
·         Any accessibility
are implementation
Inner Classes modifier can be specified.
details, interface need not
worry about this) ·         A class can be ·         Interfaces are
declared in any scope. implicitly static (static
·         But classes cannot
Classes defined inside of modifier also can be
implement an interface
other classes are known specified). They can have
method with a static
as nested classes. There any accessibility modifier.
method.
are four categories of There are no non-static
·         If an interface nested classes. inner, local or anonymous
specifies an exception list interfaces.
1.        Top-level nested
for a method, then the
classes / interfaces 2.        Non-static inner
class implementing the
classes
interface need not declare
the method with the
exception list. (Overriding
·         Declared as a class ·         Cannot declare final variables within the
member without static. any static members.(Even local block. That way, the
declared in a static value of the variable can
·         An instance of a
context) be always made available
non-static inner class can
to the objects returned
exist only with an ·         Can access all the
from the local context to
instance of its enclosing features of the enclosing
outside world.
class. So it always has to class (because they are
be created within a defined inside the method ·         Cannot be
context of an outer of the class) but can specified with static
instance. access only final variables modifier. But if they are
defined inside the method declared inside a static
·         Just like other non-
(including method context such as a static
static features of a class.
arguments). This is method or a static
Can access all the features
because the class can initializer, they become
(even private) of the
outlive the method, but static classes. They can
enclosing outer class.
the method local only access static
Have an implicit
variables will go out of members of the enclosing
reference to the enclosing
scope - in case of final class and local final
instance.
variables, compiler makes variables. But this doesn't
·         Cannot have any a copy of those variables mean they cannot access
static members. to be used by the class. any non-static features
(New meaning for final) inherited from super
·         Can have any classes. These features are
access modifier. ·         Since the names of
their own, obtained via
local classes are not
the inheritance hierarchy.
3.        Local classes visible outside the local
They can be accessed
context, references of
·         Defined inside a normally with 'this' or
these classes cannot be
block (could be a method, 'super'.
declared outside. So their
a constructor, a local
functionality could be 4.        Anonymous
block, a static initializer
accessed only via super- classes
or an instance initializer).
class references (either
Cannot be specified with ·         Anonymous classes
interfaces or classes).
static modifier. are defined where they
Objects of those class
are constructed. They can
·         Cannot have any types are created inside
be created wherever a
access modifier (since methods and returned as
reference expression can
they are effectively local super-class type
be used.
to the block) references to the outside
world. This is the reason
that they can only access
·         Anonymous classes anonymous classes classes) can be abstract
cannot have explicit cannot be specified with or final.
constructors. Instance static, but based on the
·         Classes can be
initializers can be used to context, they could
nested to any depth. Top-
achieve the functionality become static classes. In
level static classes can be
of a constructor. any case, anonymous
nested only within other
classes are not allowed to
·         Typically used for static top-level classes or
declare static members.
creating objects on the fly. interfaces. Deeply nested
Based on the context,
classes also have access to
·         Anonymous classes non-static/static features
all variables of the outer-
can implement an of outer classes are
most enclosing class (as
interface (implicit available to anonymous
well the immediate
extension of Object) or classes. Local final
enclosing class's)
explicitly extend a class. variables are always
Cannot do both. available to them. ·         Member inner
classes can be forward
Syntax: new interface ·         One enclosing
referenced. Local inner
name() { } or new class class can have multiple
classes cannot be.
name() { } instances of inner classes.
·         An inner class
·         Keywords ·         Inner classes can
variable can shadow an
implements and extends have synchronous
outer class variable. In
are not used in methods. But calling
this case, an outer class
anonymous classes. those methods obtains the
variable can be referred
lock for inner object only
·         Abstract classes as
not the outer object.  If
can be specified in the (outerclassname.this.vari
you need to synchronize
creation of an anonymous ablename).
an inner class method
class. The new class is a based on outer object, ·         Outer class
concrete class, which outer object lock must be variables are accessible
automatically extends the obtained explicitly. Locks within the inner class, but
abstract class. on inner object and outer they are not inherited.
object are independent. They don't become
·         Discussion for
local classes on members of the inner
·         Nested classes can
static/non-static context, class. This is different
extend any class or can
accessing enclosing from inheritance. (Outer
implement any interface.
variables, and declaring class cannot be referred
No restrictions.
static variables also holds using 'super', and outer
good for anonymous ·         All nested classes class variables cannot be
classes. In other words, (except anonymous accessed using 'this')
·         An inner class // Example 1                 public void
variable can shadow an doSomething() {
public class
outer class variable. If the
InnerInnerTest {                   // No
inner class is sub-classed
problem in accessing
within the same outer   public static void
without full qualification,
class, the variable has to main(String s[]) {
be qualified explicitly in                   // inner-
the sub-class. To fully         new Outer().new
most class variable
qualify the variable, use Inner().new
shadows the outer-most
classname.this.variablena InnerInner().new
class variable
me. If we don't correctly InnerInnerInner().doSom
qualify the variable, a ething();                  
compiler error will occur. System.out.println(name)
        new Outer().new
(Note that this does not ; // Prints "Sharmi"
InnerChild().doSomething
happen in multiple levels
();                  
of inheritance where an
System.out.println(Outer.t
upper-most super-class's         new Outer2().new
his.name); // Prints "Vel",
variable is silently Inner2().new
explicit reference to Outer
shadowed by the most InnerInner2().doSomethi
recent super-class ng(); // error, variable is not
variable or in multiple inherited from the outer
levels of nested inner         new
class, it can be just
classes where an inner- InnerChild2().doSomethin
accessible
most class's variable g();
silently shadows an outer- //              
 }
most class's variable. System.out.println(this.na
Problem comes only when } me);
these two hierarchy //              
class Outer {
chains (inheritance and System.out.println(InnerI
containment) clash.)   String name = "Vel"; nner.this.name);
·         If the inner class is   class Inner { //              
sub-classed outside of the System.out.println(InnerI
outer class (only possible         String name =
nnerInner.this.name);
with top-level nested "Sharmi";
classes) explicit // error, super cannot be
        class InnerInner {
qualification is not used to access outer class.
needed (it becomes           class
// super will always refer
regular class inheritance) InnerInnerInner {
the parent, in this case
Part4 Object
//                         //        
System.out.println(super. System.out.println(super. System.out.println(this.na
name);  name); // prints me); // error, 'name' is
"Sharmi", Inner has not inherited
                 
declared 'name'
System.out.println(Inner.t //        
his.name); // Prints           System.out.println(super.
"Sharmi", Inner has System.out.println(this.na name); // error, super
declared 'name' me); // prints "Sharmi", refers to Object
name is inherited by
                }           }
InnerChild
          }         }
        }
        }  }
 }
 } }
}
  /* This is an inner class /* This is a stand-alone
class Outer2 {
extending an inner class class extending an inner
in the same scope */   static String name = class */
"Vel";
  class InnerChild extends class InnerChild2 extends
Inner {   static class Inner2 { Outer2.Inner2 {

        public void         static String name =         public void
doSomething() { "Sharmi"; doSomething() {

// compiler error, explicit         class InnerInner2 {          


qualifier needed System.out.println(name)
          public void
; // prints "Sharmi",
// 'name' is inherited doSomething() {
Inner2's name is inherited
from Inner, Outer's 'name'
           
is also in scope          
System.out.println(name)
System.out.println(Outer2
//       ; // prints "Sharmi",
.name); // prints "Vel",
System.out.println(name) inner-most hides outer-
explicit reference to
; most
Outer2's static variable
                     
         
System.out.println(Outer.t System.out.println(Outer2
System.out.println(super.
his.name); // prints "Vel", .name); // prints "Vel",
name); // prints
explicit reference to Outer explicit reference to
"Sharmi", Inner2 has
Outer2's static variable
declared 'name'
                                              //                new
System.out.println(this.na   LocalInnerClass().doSome
me); // prints "Sharmi", thing();
                new
name is inherited by
OuterClass().doAnonymou                 abstract class
InnerChild2
s(); AncestorLocalInnerClass {
        } } // inner class can be
 }
abstract
}
}
                final class
// Example 2
class OuterClass { LocalInnerClass extends
public class InnerTest2 { AncestorLocalInnerClass {
  final int a = 100; // can be final
  public static void
  private String secret =                   public void
main(String s[]) {
"Nothing serious"; doSomething() {
                new
  public void                    
OuterClass().doSomething
doSomething(int arg, System.out.println(this.ge
(10, 20);
final int fa) { tClass() + " - in
// This is legal doSomething"); 
                final int x =
//                100;                    
OuterClass.InnerClass ic = System.out.print("a = " +
                int y = 200;
new OuterClass().new a );
InnerClass();                
                   
System.out.println(this.ge
//                System.out.print(" secret
tClass() + " - in
ic.doSomething(); = " + secret);
doSomething");
// Compiler error, local //                   
               
inner classes cannot be System.out.print(" arg = "
System.out.print("a = " +
accessed from outside + arg);  // Compiler error,
a + " secret = " + secret + "
accessing non-final
//                arg = " + arg + " fa = " +
argument
OuterClass.LocalInnerClas fa);
s lic = new                    
               
OuterClass().new System.out.print(" fa = " +
System.out.println(" x = "
LocalInnerClass(); fa);
+ x + " y = " + y);
//                                   
// Compiler error,
lic.doSomething();            System.out.println(" x = "
forward reference of local
+ x);
inner class
//                    secret + " someConstant = y ra ssi te ct in
System.out.println(" y = " " + someConstant); tio bil r A es
+ y); // Compiler error, n ity in cc st
    }
accessing non-final Co Mo st es at
variable  } nt dif a s ic
ex ier n to or
                  }   public void t s c e n
doAnonymous() { e nc o
                }
lo n-
                //
                new si st
Anonymous class
InnerClass().doSomething n at
implementing the inner
(); // forward reference g ic
interface
fine for member inner co m
class                 nt e
System.out.println((new ex m
                new
InnerInterface() t be
LocalInnerClass().doSome
{ }).someConstant); rs
thing();
                // Pa As Pu N N Bo
 }
Anonymous class ck pa bli o / th
  abstract class extending the inner class ag ck c A st
AncestorInnerClass { } e ag or at
                ( new lev e def ic
  interface InnerInterface InnerClass() { el me aul an
{ final int someConstant = cl mb t d
public void
999;} // inner interface as er no
doSomething() {
s n-
  class InnerClass extends
  secret = "secret is st
AncestorInnerClass
changed"; at
implements
ic
InnerInterface {   super.doSomething();
To As All N St Bo
    public void } p sta o at th
doSomething() {
} ).doSomething(); lev tic ic st
      el cla m at
System.out.println(this.ge  } ne ss e ic
tClass() + " - in ste me m an
}
doSomething");  d mb be d
En De Ac O Di D cl er rs no
      System.out.println("a as in n-
tit cla ce u re ef
= " + a + " secret = " + s en st
(st cl at nt al
ati os ic ex va
c) in t ri
g + a
co lo bl
nt ca es
ex l
An In No Y Al O
t fi
on blo ne es l nl
n
No As All Y Al O y ck m y
al
n no es l nl m wi e no
va
st n- m y ou th m n-
ri
ati sta e no s no be st
a
c tic m n- cl n- rs at
bl
in cla be st as sta in ic
es
ne ss rs at s tic en
r me in ic Lo In No N St O (n co cl
cl mb en ca blo ne o at nl on nt os
as er cl l ck ic y - ext in
s os cl wi m no st g
in as th e n- ati co
g s sta m st c) nt
co (st tic be at ex
nt ati co rs ic t
ex c) nt in +
t ext en lo
cl ca
Lo In No Y Al O
os l
ca blo ne es l nl
in fi
l ck m y
g n
cl wi e no
co al
as th m n-
nt va
s no be st
ex ri
(n n- rs at
t a
on sta in ic
+ bl
- tic en
lo es
st co cl
ca
ati nt os An In No N St O
l
c) ext in on blo ne o at nl
fi
g y ck ic y
n
co m wi m no
ou th e n- at ·         Java is
s sta m st ic fundamentally multi-
cl tic be at m threaded.
as co rs ic et
·         Every thread
s nt in ho
corresponds to an
(st ext en d
instance of
ati cl pr
java.lang.Thread class or
c) os ot
a sub-class.
in ot
g yp ·         A thread becomes
co es eligible to run, when its
nt start() method is called.
To As All N St St
ex Thread scheduler co-
p sta o at at
t ordinates between the
lev tic ic ic
+ threads and allows them
el cla m va
lo to run.
ne ss e ri
ca
ste me m ab ·         When a thread
l
d mb be le begins execution, the
fi
int er rs s scheduler calls its run
n
erf in an method.
al
ac en d
va
e cl no Signature of run method -
ri
(st os n- public void run ()
a
ati in st
bl ·         When a thread
c) g at
es returns from its run
co ic
method (or stop method is
Pa As Pu N N St nt m
called - deprecated in
ck pa bli o / at ex et
1.2), its dead. It cannot be
ag ck c A ic t ho
restarted, but its methods
e ag or va d
can be called. (it's just an
lev e def ri pr
object no more in a
el me aul ab ot
running state)
int mb t le ot
erf er s yp ·         If start is called
ac an es again on a dead thread,
e d IllegalThreadStateExce
Chapter 7 Threads
no ption is thrown.
n-
st
·         When a thread is ·         Create an instance otherwise
in running state, it may of this class. IllegalThreadStateExcepti
move out of that state for on will be thrown.
·         Create a Thread,
various reasons. When it
passing the instance as a ·         A thread spawned
becomes eligible for
target - new by a daemon thread is a
execution again, thread
Thread(object) daemon thread.
scheduler allows it to run.
·         Target should ·         Threads have
·         There are two
implement Runnable, priorities. Thread class
ways to implement
Thread class implements have constants
threads.
it, so it can be a target MAX_PRIORITY (10),
1.        Extend Thread itself. MIN_PRIORITY (1),
class NORM_PRIORITY (5)
·         Call the start
·         Create a new class, method on the Thread. ·         A newly created
extending the Thread thread gets its priority
·         JVM creates one
class. from the creating thread.
user thread for running a
Normally it'll be
·         Provide a public program. This thread is
NORM_PRIORITY.
void run method, called main thread. The
otherwise empty run in main method of the class ·         getPriority and
Thread class will be is called from the main setPriority are the
executed. thread. It dies when the methods to deal with
main method ends. If priority of threads.
·         Create an instance
other user threads have
of the new class. ·         Java leaves the
been spawned from the
implementation of thread
·         Call start method main thread, program
scheduling to JVM
on the instance (don't call keeps running even if
developers. Two types of
run - it will be executed main thread dies.
scheduling can be done.
on the same thread) Basically a program runs
until all the user threads 1.        Pre-emptive
2.        Implement (non-daemon threads) Scheduling.
Runnable interface are dead.
Ways for a thread to leave
·         Create a new class ·         A thread can be running state -
implementing the designated as a daemon
Runnable interface. thread by calling ·         It can cease to be
setDaemon(boolean) ready to execute ( by
·         Provide a public
method. This method calling a blocking i/o
void run method.
should be called before method)
the thread is started,
·         It can get pre- ·         Windows JVM's ·         Two overloaded
empted by a high-priority after Java 1.0.2 versions - one with
thread, which becomes milliseconds, one with
·         Different states of
ready to execute. milliseconds and
a thread:
nanoseconds.
·         It can explicitly
1.        Yielding
call a thread-scheduling ·         Throws an
method such as wait or ·         Yield is a static InterruptedException.
suspend. method. Operates on (must be caught)
current thread.
·         Solaris JVM's are ·         After the time
pre-emptive. ·         Moves the thread expires, the sleeping
from running to ready thread goes to ready
·         Windows JVM's
state. state. It may not execute
were pre-emptive until
immediately after the
Java 1.0.2 ·         If there are no time expires. If there are
threads in ready state, the other threads in ready
2.        Time-sliced or
yielded thread may state, it may have to
Round Robin Scheduling
continue execution, compete with those
·         A thread is only otherwise it may have to threads to run. The
allowed to execute for a compete with the other correct statement is the
certain amount of time. threads to run. sleeping thread would
After that, it has to execute some time after
·         Run the threads
contend for the CPU the specified time period
that are doing time-
(virtual CPU, JVM) time has elapsed.
consuming operations
with other threads.
with a low priority and ·         If interrupt
·         This prevents a call yield periodically method is invoked on a
high-priority thread from those threads to sleeping thread, the
mono-policing the CPU. avoid those threads thread moves to ready
locking up the CPU. state. The next time it
·         The drawback
begins running, it
with this scheduling is - it 2.        Sleeping
executes the
creates a non-
·         Sleep is also a InterruptedException
deterministic system - at
static method. handler.
any point in time, you
cannot tell which thread ·         Sleeps for a 3.        Suspending
is running and how long it certain amount of time.
may continue to run. ·         Suspend and
(passing time without
resume are instance
doing anything and w/o
·         Macintosh JVM's methods and are
using CPU)
deprecated in 1.2
·         A thread that step out of the CPU. All synchronized code, or an
receives a suspend call, Java I/O methods behave IllegalMonitorStateExce
goes to suspended state this way. ption will be thrown. In
and stays there until it other words, only the
·         A thread can also
receives a resume call on threads that obtained the
become blocked, if it
it. object's lock can call these
failed to acquire the lock
methods.
·         A thread can of a monitor.
suspend it itself, or Locks, Monitors and
5.        Waiting
another thread can Synchronization
suspend it. ·         wait, notify and
·         Every object has a
notifyAll methods are not
·         But, a thread can lock (for every
called on Thread, they're
be resumed only by synchronized code block).
called on Object.
another thread. At any moment, this lock
Because the object is the
is controlled by at most
·         Calling resume on one which controls the
one thread.
a thread that is not threads in this case. It
suspended has no effect. asks the threads to wait ·         A thread that
and then notifies when its wants to execute an
·         Compiler won't
state changes. It's called a object's synchronized
warn you if suspend and
monitor. code must acquire the
resume are successive
lock of the object. If it
statements, although the ·         Wait puts an
cannot acquire the lock,
thread may not be able to executing thread into
the thread goes into
be restarted. waiting state.(to the
blocked state and comes
monitor's waiting pool)
4.        Blocking to ready only when the
·         Notify moves one object's lock is available.
·         Methods that are
thread in the monitor's
performing I/O have to ·         When a thread,
waiting pool to ready
wait for some occurrence which owns a lock,
state. We cannot control
in the outside world to finishes executing the
which thread is being
happen before they can synchronized code, it
notified. notifyAll is
proceed. This behavior is gives up the lock.
recommended.
blocking.
·         Monitor (a.k.a
·         NotifyAll moves all
·         If a method needs Semaphore) is an object
threads in the monitor's
to wait an indeterminable that can block and revive
waiting pool to ready.
amount of time until some threads, an object that
I/O takes place, then the ·         These methods can controls client threads.
thread should graciously only be called from Asks the client threads to
wait and notifies them
when the time is right to §         calling thread get a to
continue, based on its gives up the lock lock wait.
state. In strict Java on the (by
§         calling thread
terminology, any object monit mean
goes to monitor's waiting
that has some or. s of
pool
synchronized code is a wait
monitor. (or
§         wait also has a metho
waiti
version with timeout in d)
·         2 ways to ng for
milliseconds. Use this if
synchronize: a
you're not sure when the
blocki
1.        Synchronize the current thread will get
ng i/o
entire method notified, this avoids the
metho
thread being stuck in wait
·         Declare the d)
state forever.
method to be Cause The
synchronized - very ·         notify - points to d by threa
common practice. remember the d
·         Thread should §         one thread gets threa alrea
obtain the object's lock. moved out of monitor's d dy
waiting pool to ready tried acqui
2.        Synchronize part to red
state
of the method execu the
§         notifyAll moves all te lock
·         Have to pass an
the threads to ready state some and
arbitrary object which
synch execu
lock is to be obtained to §         Thread gets to
ronize ted
execute the synchronized execute must re-acquire
d some
code block (part of a the lock of the monitor
code. synch
method). before it can proceed.
(or a ronize
·         We can specify ·         Note the blocki d code
"this" in place object, to differences between ng i/o before
obtain very brief locking - blocked and waiting. metho comin
not very common. d) g
Block Waiti across
·         wait - points to ed ng a wait
remember call.
Threa Threa
§         calling thread d is d has Can Can
gives up CPU waiti been move move
ng to asked to to
ready ready call other synchronous compiler won't catch this.
only only methods on the same At runtime, if the thread
when when object. (this is another doesn't have the lock
the it gets lock) Other threads can't while calling these
lock is notifi do that. They should wait methods, an
availa ed (by to get the lock. IllegalMonitorStateExce
ble. mean ption is thrown.
·         Non-synchronous
( or s of
methods can be called at ·         Deadlocks can
the notify
any time by any thread. occur easily. e.g, Thread A
i/o or
locked Object A and
opera notify ·         Synchronous
waiting to get a lock on
tion is All) methods are re-entrant.
Object B, but Thread B
compl So they can be called
locked Object B and
ete) recursively.
waiting to get a lock on
·         Points for complex ·         Synchronized Object A. They'll be in this
models: methods can be state forever.

1.        Always check overrided to be non-


·         It's the
monitor's state in a while synchronous.
programmer's
loop, rather than in an if Synchronized behavior
responsibility to avoid the
statement. affects only the original
deadlock. Always get the
class.
locks in the same order.
2.        Always call
notifyAll, instead of notify. ·         Locks on
·         While 'suspended',
inner/outer objects are
the thread keeps the locks
·         Class locks independent. Getting a
it obtained - so suspend is
control the static lock on outer object
deprecated in 1.2
methods. doesn't mean getting the
lock on an inner object as ·         Use of stop is also
·         wait and sleep
well, that lock should be deprecated; instead use a
must be enclosed in a
obtained separately. flag in run method.
try/catch for
Compiler won't warn you,
InterruptedException. ·         wait and notify
if you have statements
should be called from
·         A single thread after a call to stop, even
synchronized code. This
can obtain multiple locks though they are not
ensures that while calling
on multiple objects (or on reachable.  
these methods the thread
the same object)
always has the lock on the Here you will find java
·         A thread owning object. If you have Interview Questions for
the lock of an object can wait/notify in non- job Interviews. Before
synchronized code appearing in a job
interview it is very are: in a situation that Some
important to prepare * Public general methods should
well. The easy way to * Protected be implemented and
prepare for a job * Private specialization behavior
interview is to be pre * Defaults should be implemented by
prepared by going child classes. Interfaces
through important job 2. What's the difference are useful in a situation
interview questions. I between an interface that all properties should
created these java and an abstract class? be implemented.
interview faqs database, Also discuss the
by asking many people to similarities. (Very Differences are as
contribute the questions Important) follows:
they faced during job
interviews and found the Abstract class is a class * Interfaces provide a
best way possible to which contain one or form of multiple
present and answer these more abstract methods, inheritance. A class can
questions on this website. which has to be extend only one other
implemented by sub class.
Interview que
classes. Interface is a Java * Interfaces are limited to
1. What is the difference Object containing method public methods and
between private, declaration and doesn't constants with no
protected, and public? contain implementation. implementation. Abstract
The classes which have classes can have a partial
These keywords are for implementing the implementation,
allowing privileges to Interfaces must provide protected parts, static
components such as java the method definition for methods, etc.
methods and variables. all the methods * A Class may implement
Public: accessible to all Abstract class is a Class several interfaces. But in
classes prefix with a abstract case of abstract class, a
Private: accessible only to keyword followed by Class class may extend only one
the class to which they definition. Interface is a abstract class.
belong Interface which starts * Interfaces are slow as it
Protected: accessible to with interface keyword. requires extra indirection
the class to which they Abstract class contains to to find corresponding
belong and any one or more abstract method in in the actual
subclasses. methods. where as class. Abstract classes are
Access specifiers are Interface contains all fast. 
keywords that determines abstract methods and
the type of access to the final declarations Similarities:
member of a class. These Abstract classes are useful
* Neither Abstract classes     public void when it determines no
or Interface can be functionOne(); more references to the
instantiated.     public long object exists. In Java, it is
CONSTANT_ONE = 1000; good idea to explicitly
How to define an } assign null into a variable
Abstract class? when no more in use. I
A class containing 3. Question: How you Java on calling
abstract method is called can force the garbage System.gc() and
Abstract class. An collection? Runtime.gc(), JVM tries to
Abstract class can't be recycle the unused
instantiated. Garbage collection objects, but there is no
Example of Abstract class: automatic process and guarantee when all the
can't be forced. You could objects will garbage
abstract class request it by calling collected.
testAbstractClass {  System.gc(). JVM does not
    protected String guarantee that GC will be 4. What's the difference
myString;  started immediately. between constructors
    public String and normal methods?
getMyString() {  Garbage collection is one
    return myString;  of the most important Constructors must have
}  feature of Java, Garbage the same name as the
public abstract string collection is also called class and can not return a
anyAbstractFunction(); automatic memory value. They are only
} management as JVM called once while regular
automatically removes methods could be called
How to define an the unused many times and it can
Interface? variables/objects (value is return a value or can be
Answer: In Java Interface null) from the memory. void.
defines the methods but User program can't
does not implement them. directly free the object 5. Can you call one
Interface can include from memory, instead it is constructor from
constants. A class that the job of the garbage another if a class has
implements the interfaces collector to automatically multiple constructors
is bound to implement all free the objects that are
the methods defined in no longer referenced by a Yes. Use this() to call a
Interface. program. Every class constructor from an other
Example of Interface: inherits finalize() method constructor.
from java.lang.Object, the
public interface finalize() method is called 6. Explain the usage of
sampleInterface { by garbage collector Java packages.
objects by first casting communications allows
This is a way to organize them as the interface only to send packets of
files when a project type. raw data between
consists of multiple applications. Both the
modules. It also helps 8. What are some client-side and server-side
resolve naming conflicts advantages and have to provide
when different packages disadvantages of Java mechanisms to make the
have classes with the Sockets? data useful in any way.
same names. Packages
access level also allows Some advantages of Java 9. Explain the usage of
you to protect data from Sockets:  the keyword transient?
being used by the non- Sockets are flexible and
authorized classes. sufficient. Efficient socket Transient keyword
based programming can indicates that the value of
7. Explain in your own be easily implemented for this member variable
words the "bottom line" general communications. does not have to be
benefits of the use of an Sockets cause low serialized with the object.
interface. network traffic. Unlike When the class will be de-
HTML forms and CGI serialized, this variable
The interface makes it scripts that generate and will be initialized with a
possible for a method in transfer whole web pages default value of its data
one class to invoke for each new request, Java type (i.e. zero for
methods on objects of applets can send only integers).
other classes, without the necessary updated
requirement to know the information. 10. What's the
true class of those objects, difference between the
provided that those Some disadvantages of methods sleep() and
objects are all Java Sockets: wait()
instantiated from classes Security restrictions are
that implement one or sometimes overbearing The code sleep(1000);
more specified interfaces. because a Java applet puts thread aside for
In other words, objects of running in a Web browser exactly one second. The
classes that implement is only able to establish code wait(1000), causes a
specified interfaces can be connections to the wait of up to one second.
passed into methods of machine where it came A thread could stop
other objects as the from, and to nowhere else waiting earlier if it
generic type Object, and on the network   Despite receives the notify() or
the methods of the other all of the useful and notifyAll() call. The
objects can invoke helpful Java features, method wait() is defined
methods on the incoming Socket based in the class Object and the
method sleep() is defined method access local classes:
in the class Thread. variables of this Primitive Wrapper
method? boolean  -
11. What would you use java.lang.Boolean
to compare two String It's possible if these byte - java.lang.Byte
variables - the operator variables are final. char - java.lang.Character
== or the method double - java.lang.Double
equals()? 15. What can go wrong float - java.lang.Float
if you replace && with & int - java.lang.Integer
I'd use the method in the following code: long - java.lang.Long
equals() to compare the String a=null; if (a!=null short - java.lang.Short
values of the Strings and && a.length()>10) {...} void - java.lang.Void
the == to check if two
variables point at the A single ampersand here 18. How could Java
same instance of a String would lead to a classes direct program
object. NullPointerException. messages to the system
console, but error
12. Why would you use 16. What's the main messages, say to a file?
a synchronized block vs. difference between a
synchronized method? Vector and an The class System has a
ArrayList? variable out that
Synchronized blocks place represents the standard
locks for shorter periods Java Vector class is output, and the variable
than synchronized internally synchronized err that represents the
methods. and ArrayList is not standard error device. By
synchronized. default, they both point at
13. What access level do the system console. This
you need to specify in 17. Describe the how the standard output
the class declaration to wrapper classes in Java. could be re-directed:
ensure that only classes Stream st = new
from the same directory Wrapper class is wrapper Stream(new
can access it? around a primitive data FileOutputStream("outpu
type. An instance of a t.txt")); System.setErr(st);
You do not need to specify wrapper class contains, or System.setOut(st);
any access level, and Java wraps, a primitive value
will use a default package of the corresponding type. 19. How do you know if
access level. an explicit object
Following table lists the casting is needed?
14. Can an inner class primitive types and the
declared inside of a corresponding wrapper If you assign a superclass
object to a variable of a this class contains the
subclass's data type, you method main(), you could 25. You are planning to
need to do explicit test it from a command do an indexed search in
casting. For example: prompt window as a list of objects. Which
Object a; Customer b; b = follows: of the two Java
(Customer) a; c:\>java collections should you
com.xyz.hr.Employee use:
20. When you assign a ArrayList or LinkedList?
subclass to a variable 22. What's the
having a supeclass type, difference between ArrayList
the casting is J2SDK 1.5 and J2SDK
performed 5.0? 26. When should the
automatically. Can you method invokeLater()be
write a Java class that There's no difference, Sun used?
could be used both as Microsystems just re-
an applet as well as an branded this version. This method is used to
application? ensure that Swing
23. Does it matter in components are updated
Yes. Add a main() method what order catch through the event-
to the applet. statements for dispatching thread.
FileNotFoundException
21. If a class is located and IOExceptipon are 27. How can a subclass
in a package, what do written? call a method or a
you need to change in constructor defined in a
the OS environment to Yes, it does. The superclass?
be able to use it? FileNoFoundException is
inherited from the Use the following syntax:
You need to add a IOException. Exception's super.myMethod(); To
directory or a jar file that subclasses have to be call a constructor of the
contains the package caught first. superclass, just write
directories to the super(); in the first line of
CLASSPATH environment 24. Name the containers the subclass's constructor.
variable. Let's say a class which uses Border
Employee belongs to a Layout as their default 28. What do you
package com.xyz.hr; and layout? understand by
is located in the file Synchronization?
c:\dev\com\xyz\hr\Empl Containers which uses
oyee.javIn this case, you'd Border Layout as their Synchronization is a
need to add c:\dev to the default are: window, process of controlling the
variable CLASSPATH. If Frame and Dialog classes. access of shared resources
by the multiple threads in 30. You can create an HashSet, HashMap,
such a manner that only abstract class that ArrayList, LinkedList,
one thread can access one contains only abstract TreeSet and TreeMap.
resource at a time. In non methods. On the other Example of interfaces:
synchronized hand, you can create an Collection, Set, List and
multithreaded interface that declares Map.
application, it is possible the same methods. So
for one thread to modify a can you use abstract 33. How would you
shared object while classes instead of make a copy of an
another thread is in the interfaces? entire Java object with
process of using or its state?
updating the object's Sometimes. But your class
value. Synchronization may be a descendent of Have this class implement
prevents such type of data another class and in this Cloneable interface and
corruption. case the interface is your call its method clone().
E.g. Synchronizing a only option.
function: 34. How can you
public synchronized void 31. If you're overriding minimize the need of
Method1 () { the method equals() of garbage collection and
    // Appropriate an object, which other make the memory use
method-related code.  method you might also more effective?
} consider?
E.g. Synchronizing a block Use object pooling and
of code inside a function: hashCode() weak object references.
public myFunction (){
    synchronized (this) {  32. What is Collection 35. There are two
    // Synchronized code API? classes: A and B. The
here. class B need to inform a
  } The Collection API is a set class A when some
} of classes and interfaces important event has
that support operation on happened. What Java
29. What's the collections of objects. technique would you
difference between a These classes and use to implement it?
queue and a stack? interfaces are more
flexible, more powerful, If these classes are
Stacks works by last-in- and more regular than threads I'd consider
first-out rule (LIFO), the vectors, arrays, and notify() or notifyAll(). For
while queues use the FIFO hashtables if effectively regular classes you can
rule replaces.  use the Observer
Example of classes: interface.
different types of actions. sub-classing it to the
36. Explain the The specific action is Exception class. This
Encapsulation determined by the exact allows custom exceptions
principle. nature of the situation. to be generated (using
The concept of throw) and caught in the
Encapsulation is a process polymorphism can be same way as normal
of binding or wrapping explained as "one exceptions.
the data and the codes interface, multiple Example:
that operates on the data methods". 
into a single entity. This From a practical class myCustomException
keeps the data safe from programming viewpoint, extends Exception {
outside interface and polymorphism exists in      / The class simply has
misuse. One way to think three distinct forms in to exist to be an exception
about encapsulation is as Java: }
a protective wrapper that
prevents code and data * Method overloading
from being arbitrarily * Method overriding 41. What is OOPS?
accessed by other code through inheritance
defined outside the * Method overriding OOP is the common
wrapper.  through the Java abbreviation for Object-
interface Oriented Programming. 
37. Explain the There are three main
Inheritance principle. 39. Is Iterator a Class or principals of oops which
Interface? What is its are called Polymorphism,
Inheritance is the process use? Inheritance and
by which one object Encapsulation. 
acquires the properties of Iterator is an interface
another object.  which is used to step 39.  Read the following
through the elements of a program:
38. Explain the Collection. 
Polymorphism public class test {
principle. 40. Explain the user public static void
defined Exceptions? main(String [] args) {
The meaning of     int x = 3;
Polymorphism is User defined Exceptions     int y = 1;
something like one name are the separate     if (x = y)
many forms. Exception classes defined        
Polymorphism enables by the user for specific System.out.println("Not
one entity to be used as as purposed. An user defined equal");
general category for can created by simply    else
        understand by
System.out.println("Equal Synchronization?
"); Answer: Synchronization
  } is a process of controlling
} the access of shared
resources by the multiple
What is the result? threads in such a manner
The output is “Equal” that only one thread can
B. The output in “Not access one resource at a
Equal” time. In non synchronized
C. An error at " if (x = y)" multithreaded
causes compilation to fall. application, it is possible
D. The program executes for one thread to modify a
but no output is show on shared object while
console. another thread is in the
Answer: C process of using or
Answer: Transient updating the object's
variable can't be serialize. value. Synchronization
For example if a variable prevents such type of data
is declared as transient in corruption.
a Serializable class and E.g. Synchronizing a
the class is written to an function:
ObjectStream, the value of public synchronized void
the variable can't be Method1()
written to the stream
{
instead when the class is
// Appropriate method-
retrieved from the
relatedcode.
ObjectStream the value of
}
the variable becomes null.
E.g. Synchronizing a block
of code inside a function:
# Question: Name the
public myFunction()
containers which uses
Border Layout as their {
default layout? synchronized (this)
Answer: Containers which
uses Border Layout as {
their default are: window, // Synchronized code
Frame and Dialog classes. here.
}
# Question: What do you }

You might also like