Java programming language The Java programming language is a
high-level language that can be characterized by all of the
following buzzwords: Architecture Simple neutral Object Portable
oriented High Distributed performance Robust Multithreaded Dynamic
Secure Portable: Your applications are portable across multiple
platforms. Write your applications once, and you never need to port
themthey will run without modification on multiple operating
systems and hardware architectures. Robust: Your applications are
robust because the Java run-time system manages memory for you.
Because Java has inbuilt garbage collector and type safety checks
in code. The compiler restricts the type compatibility when
converting data from one type o another. High Performance: Your
interactive graphical applications have high performance because
multiple concurrent threads of activity in your application are
supported by the multithreading built into the Java language and
runtime platform. Secure: Your end users can trust that your
applications are secure, even though theyre downloading code from
all over the Internet; the Java run-time system has built-in
protection against viruses and tampering. Each of the preceding
buzzwords is explained in The Java Language Environment , a white
paper written by James Gosling and Henry McGilton. In the Java
programming language, all source code is first written in plain
text files ending with the .java extension. Those source files are
then compiled into .class files by the javac compiler. A .class
file does not contain code that is native to your processor; it
instead contains bytecodes the machine language of the Java Virtual
Machine1 (Java VM). The java launcher tool then runs your
application with an instance of the Java Virtual Machine.
An overview of the software development process. Because the
Java VM is available on many different operating systems, the same
.class files are capable of running on Microsoft Windows, the
Solaris TM Operating System (Solaris OS), Linux, or Mac OS. Some
virtual machines, such as the Java HotSpot virtual machine, perform
additional steps at runtime to give your application a performance
boost. This include various tasks such as finding performance
bottlenecks and recompiling (to native code) frequently used
sections of code.
Through the Java VM, the same application is capable of running
on multiple platforms. The Java Platform A platform is the hardware
or software environment in which a program runs. We've already
mentioned some of the most popular platforms like Microsoft
Windows, Linux, Solaris OS, and Mac OS. Most platforms can be
described as a combination of the operating system and underlying
hardware. The Java platform differs from most other platforms in
that it's a software-only platform that runs on top of other
hardware-based platforms. The Java platform has two components: The
Java Virtual Machine The Java Application Programming Interface
(API)
You've already been introduced to the Java Virtual Machine; it's
the base for the Java platform and is ported onto various
hardware-based platforms. The API is a large collection of
ready-made software components that provide many useful
capabilities. It is grouped into libraries of related classes and
interfaces; these libraries are known as packages. The next
section, What Can Java Technology Do? highlights some of the
functionality provided by the API.
The API and Java Virtual Machine insulate the program from the
underlying hardware. As a platform-independent environment, the
Java platform can be a bit slower than native code. However,
advances in compiler and virtual machine technologies are bringing
performance close to that of native code without threatening
portability.
Why Strings have been made immutable? JVM internally maintains
the "String Pool". To achieve the memory efficiency, JVM will refer
the String object from pool. It will not create the new String
objects. So, whenever you create a new string literal, JVM will
check in the pool whether it already exists or not. If already
present in the pool, just give the reference to the same object or
create the new object in the pool. There will be many references
point to the same String objects, if someone changes the value, it
will affect all the references. So, sun decided to make it
immutable. It checks only for string literals. If you create a
string with new operator it does not check it directly creates new
object. String.intern() method lets you the objects created using
new operator to be placed into string pool.
Primitive Data Types The Java programming language is
statically-typed, which means that all variables must first be
declared before they can be used. This involves stating the
variable's type and name, as you've already seen: int gear = 1;
Doing so tells your program that a field named "gear" exists, holds
numerical data, and has an initial value of "1". A variable's data
type determines the values it may contain, plus the operations that
may be performed on it. In addition to int, the Java programming
language supports seven other primitive data types. A primitive
type is predefined by the language and is named by a reserved
keyword. Primitive values do not share state with other primitive
values. The eight primitive data types supported by the Java
programming language are: byte: The byte data type is an 8-bit
signed two's complement integer. It has a minimum value of -128 and
a maximum value of 127 (inclusive). The byte data type can be
useful for saving memory in large arrays, where the memory savings
actually matters. They can also be used in place of int where their
limits help to clarify your code; the fact that a variable's range
is limited can serve as a form of documentation. short: The short
data type is a 16-bit signed two's complement integer. It has a
minimum value of -32,768 and a maximum value of 32,767 (inclusive).
As with byte, the same guidelines apply: you can use a short to
save memory in large arrays, in situations where the memory savings
actually matters. int: The int data type is a 32-bit signed two's
complement integer. It has a minimum value of -2,147,483,648 and a
maximum value of 2,147,483,647 (inclusive). For integral values,
this data type is generally the default choice unless there is a
reason (like the above) to choose something else. This data type
will most likely be large enough for the numbers your program will
use, but if you need a wider range of values, use long instead.
long: The long data type is a 64-bit signed two's complement
integer. It has a minimum value of -9,223,372,036,854,775,808 and a
maximum value of 9,223,372,036,854,775,807 (inclusive). Use this
data type when you need a range of values wider than those provided
by int. float: The float data type is a single-precision 32-bit
IEEE 754 floating point. Its range of values is beyond the scope of
this discussion, but is specified in section 4.2.3 of the Java
Language Specification. As with the recommendations for byte and
short, use a float (instead of double) if you need to save memory
in large arrays of floating point numbers. This data type
should
never be used for precise values, such as currency. For that,
you will need to use the java.math.BigDecimal class instead.
Numbers and Strings covers BigDecimal and other useful classes
provided by the Java platform. double: The double data type is a
double-precision 64-bit IEEE 754 floating point. Its range of
values is beyond the scope of this discussion, but is specified in
section 4.2.3 of the Java Language Specification. For decimal
values, this data type is generally the default choice. As
mentioned above, this data type should never be used for precise
values, such as currency. boolean: The boolean data type has only
two possible values: true and false. Use this data type for simple
flags that track true/false conditions. This data type represents
one bit of information, but its "size" isn't something that's
precisely defined. char: The char data type is a single 16-bit
Unicode character. It has a minimum value of '\u0000' (or 0) and a
maximum value of '\uffff' (or 65,535 inclusive). In addition to the
eight primitive data types listed above, the Java programming
language also provides special support for character strings via
the java.lang.String class. Enclosing your character string within
double quotes will automatically create a new String object; for
example, String s = "this is a string";. String objects are
immutable, which means that once created, their values cannot be
changed. The String class is not technically a primitive data type,
but considering the special support given to it by the language,
you'll probably tend to think of it as such. You'll learn more
about the String class in Simple Data Objects Default Values It's
not always necessary to assign a value when a field is declared.
Fields that are declared but not initialized will be set to a
reasonable default by the compiler. Generally speaking, this
default will be zero or null, depending on the data type. Relying
on such default values, however, is generally considered bad
programming style. The following chart summarizes the default
values for the above data types. Default Value (for Data Type
fields) byte 0 short 0 int 0 long 0L float 0.0f double 0.0d
char '\u0000' String (or any null object) boolean false Local
variables are slightly different; the compiler never assigns a
default value to an uninitialized local variable. If you cannot
initialize your local variable where it is declared, make sure to
assign it a value before you attempt to use it. Accessing an
uninitialized local variable will result in a compile-time error.
Literals You may have noticed that the new keyword isn't used when
initializing a variable of a primitive type. Primitive types are
special data types built into the language; they are not objects
created from a class. A literal is the source code representation
of a fixed value; literals are represented directly in your code
without requiring computation. As shown below, it's possible to
assign a literal to a variable of a primitive type: boolean result
= true; char capitalC = 'C'; byte b = 100; short s = 10000; int i =
100000; double d = 23.45; float f = 23.45f; * If you assign 23.45
to a literal it takes it as a double value Class and Objects:
Things an object knows about itself are called instance variables.
They represent an objects state (the data), and can have unique
values for each object of that type. Things an object does are
methods. Methods operate on data. A class is not an object but its
used to construct them. A class is a blueprint for an object. It
tells the virtual machine how to make an object of that particular
type. Each object made from that class can have its own values for
the instance variables of that class. 1. Object-oriented
programming lets you extend a program without having to touch
previously tested, working code. 2. All Java code is defined in a
class. 3. A class describes how to make an object of that class
type. A class is like a blueprint.
4. An object can take care of itself; you dont have to know or
care how the object does it. 5. An object knows things and does
things. Things an object knows about itself are called instance
variables. They represent the state of an object. Things an object
does are called methods. They represent the behavior of an object.
6. A class can inherit instance variables and methods from a more
abstract superclass. 7. At runtime, a Java program is nothing more
than objects talking to other objects. 8. There is actually no such
thing as an object variable. Theres only an object reference
variable. 9. An object reference variable holds bits that represent
a way to access an object. It doesnt hold the object itself, but it
holds something like a pointer. Or an address. Except, in Java we
dont really know what is inside a reference variable. We do know
that whatever it is, it represents one and only one object. And the
JVM knows how to use the reference to get to the object. Garbage
collector: Some object-oriented languages require that you keep
track of all the objects you create and that you explicitly destroy
them when they are no longer needed. Managing memory explicitly is
tedious and errorprone. The Java platform allows you to create as
many objects as you want (limited, of course, by what your system
can handle), and you don't have to worry about destroying them. The
Java runtime environment deletes objects when it determines that
they are no longer being used. This process is called garbage
collection. An object is eligible for garbage collection when there
are no more references to that object. References that are held in
a variable are usually dropped when the variable goes out of scope.
Or, you can explicitly drop an object reference by setting the
variable to the special value null. Remember that a program can
have multiple references to the same object; all references to an
object must be dropped before the object is eligible for garbage
collection. The Java runtime environment has a garbage collector
that periodically frees the memory used by objects that are no
longer referenced. The garbage collector does its job automatically
when it determines that the time is right. Java takes out the
Garbage: Each time an object is created in Java, it goes into an
area of memory known as The Heap. All objectsno matter when, where,
or how theyre created live on the heap. But its no t just any old
memory heap; the Java heap is actually called the
Garbage-Collectible Heap. When you create an object, Java
allocates memory space on the heap according to how much that
particular object needs. An object with , say, 15 instance
variables, will probably need more space than an object with only
two instance variables. But what happens when you need to reclaim
that space ? How do you get an object out of the heap when youre
done with it? Java manages that memory for you! When the JV M can
see that an object can never be used again, that object becomes
eligible for garbage collection. And if youre running low on
memory, the Garbage Collector will run, throw out the un reachable
objects, and free up the space, so that the space can be reused.
Reference variables: All references for a given JVM will be the
same size regardless of the objects they reference, but each JVM
might have a different way of representing references, so
references on one JVM may be smaller or larger than references on
another JVM. How big the reference variable is? You dont know.
Unless youre cozy with someone on the JVMs development team, you
dont know how a reference is represented. There are pointers in
there somewhere, but you cant access them. You wont need to. (OK,
if you insist, you might as well just imagine it to be a 64-bit
value.) But when youre talking about memory allocation issues, your
Big Concern should be about how many objects (as opposed to object
references) youre creating, and how big they (the objects) really
are. 1. 2. 3. 4. 5. 6. 7. 8. 9. Unreachable objects are eligible
for garbage collection The final variables are not allowed to be
assigned again. Variables come in two flavors: primitive and
reference. Variables must always be declared with a name and a
type. A primitive variable value is the bits representing the value
(5, a, true, 3.1416, etc.). A reference variable value is the bits
representing a way to get to an object on the heap. A reference
variable is like a remote control. Using the dot operator (.) on a
reference variable is like pressing a button on the remote control
to access a method or instance variable. A reference variable has a
value of null when it is not referencing any object. An array is
always an object, even if the array is declared to hold primitives.
There is no such thing as a primitive array, only an array that
holds primitives.
Difference between instance variables and local variables
Instance variables are declared within the class. Instance
variables always get a default value if you dont explicitly set a
value. Integers ------ 0 Floating points --------- 0.0 Boolean
------ false References--- null Local variables are declared within
the method. They dont get a default value if you dont assign a
value. They must be initialized before they are used. The compiler
complains you if you use the local variables before they are
initialized. Public void change(){ Int x; Int y = x + 4; //error X
= 10; Int z = x + 4;//Okay } Method parameters are virtually the
same as local variablestheyre declared inside the method (well,
technically theyre declared in the argument list of the method
rather than within the body of the method, but theyre still local
variables as opposed to instance variables). But method parameters
will never be uninitialized, so youll never get a compiler error
telling you that a parameter variable might not have been
initialized. Comparison: The == compares between primitive values.
It compares bits within the variables. And if the two reference
variables are refereeing same object on the heap, == returns true.
Foo a = new Foo(); Foo b = new Foo(); Foo c = a; if (a == b) { //
false } if (a == c) { // true } if (b == c) { // false } Pass by
Value: Java is a pass by value that means pass by copy. When the
variables are passed to the methods the bits representing values
are get actually copied and copies will be passed instead of
originals. In the case of primitives the bits are copied and copies
are sent to method and the original values are remains same after
the completion of method execution even though the parameters of
the method have
been changed inside the method. The method cant change the bits
that were in the calling variable. In the case of reference
variables, the copies of reference variables are sent to the
method. And both the original and copy referring to the same object
in the heap, the modification made on the state of objects during
the method execution can be accessed by the original reference
variable too. class PassByCopyTest { static void change(int y){ y =
y + 10; } static void change(A obj){ obj.x = 15; } public static
void main(String[] args) { System.out.println("Pass by copy
example"); int a = 20; System.out.println("Primitive variable after
change: "+a); change(a); System.out.println("Primitive variable
after change: "+a); A obj = new A(); obj.x = 30;
System.out.println("Object state before change : "+obj.x);
change(obj); System.out.println("Object state after change :
"+obj.x); } } class A { int x = 20; } ---------- run ---------Pass
by copy example Primitive variable after change: 20 Primitive
variable after change: 20 Object state before change : 30 Object
state after change : 15
Arrays Arrays are always objects, whether theyre declared to
hold primitives or object references. But you can have an array
object thats declared to hold primitive values. In other words, the
array object can have elements which are primitives, but the array
itself is never a primitive. Regardless of what the array holds,
the array itself is always an object!. Array of references hold
references not objects. Every element in an array is just a
variable. In other words, one of the eight primitive variable types
(think: Large Furry Dog) or a reference variable. Anything you
would put in a variable of that type can be assigned to an array
element of that type. So in an array of type int (int[]), each
element can hold an int. In a Dog array (Dog[]) each element can
hold... a Dog? No, remember that a reference variable just holds a
reference (a remote control), not the object itself. So in a Dog
array, each element can hold a remote control to a Dog.
Encapsulation: Encapsulation is nothing but hiding the details.
Encapsulation puts a force-field around my instance variables, so
nobody can set them to, lets say, something inappropriate. It is
good practice, make the instance variables as private and provide
public setter and getter methods to access them. Inheritance 1. A
subclass extends a superclass. 2. A subclass inherits all public
instance variables and methods of the superclass, but 3. does not
inherit the private instance variables and methods of the
superclass. 4. Inherited methods can be overridden; instance
variables cannot be overridden (although they can be redefined in
the subclass, but thats not the same thing, and theres almost never
a need to do it.) 5. Use the IS-A test to verify that your
inheritance hierarchy is valid. If X extends Y, 6. then X IS-A Y
must make sense. 7. The IS-A relationship works in only one
direction. A Hippo is an Animal, but not all 8. Animals are Hippos.
9. When a method is overridden in a subclass, and that method is
invoked on an instance of 10. the subclass, the overridden version
of the method is called. (The lowest one wins.) 11. If class B
extends A, and C extends B, class B IS-A class A, and class C IS-A
class B, and class C also IS-A class A. What does all this
inheritance buy you:
1. You can get rid of duplicate code by abstracting out the
behavior common to a group of classes, and sticking that code in a
superclass. That way, when you need to modify it, you have only one
place to update, and the change is magically reflected in all the
classes that inherit that behavior. 2. Just deliver the
newly-changed superclass, and all classes that extend it will
utomatically use the new version. Polymorphism With polymorphism,
the reference type can be a superclass of the actual object type.
Using polymorphic arguments, where you can declare the method
parameter as a superclass type, you can pass in any subclass object
at runtime. Polymorphism lets you use a more abstract supertype
(including an interface) reference to refer to one of its subtypes
(including interface implementers).
Aninal getAnimal(){ } Void method(Animal animal){ } //method(new
Tiger());// With polymorphic perspective, we can design
Animal-using programs with Animal arguments (and array
declarations) Overriding rules: 1. Arguments must be the same, and
return types must be compatible. The contract of superclass defines
how other code can use a method. Whatever the superclass takes as
an argument, the subclass overriding the method must use that same
argument and same in the order. And whatever the superclass
declares as a return type, the overriding method must declare
either the same type, or a subclass type. Remember, a subclass
object is guaranteed to be able to do anything its superclass
declares, so its safe to return a subclass where the superclass is
expected. Error case: class A { OverridingTest one(){ return new
OverridingTest();
} } class OverridingTest extends A { A one(){ return new
OverridingTest(); } public static void main(String[] args) {
System.out.println("Hello World!"); } } ---------- compile
---------OverridingTest.java:11: one() in OverridingTest cannot
override one() in A; attempting to use incompatible return type
found : A required: OverridingTest A one(){ ^ 1 error Output
completed (0 sec consumed) Success case: class A { A one(){ return
new OverridingTest(); } } class OverridingTest extends A {
OverridingTest one(){ return new OverridingTest(); } public static
void main(String[] args) { System.out.println("Hello World!"); }
}
2. The method cant be less accessible. The access modifier of
overridden method in subclass cant be less than that of the
overridden method in superclass. Order of access modifiers :
private, default, protected, public Error case class A { public A
one(){ return new OverridingTest(); } } class OverridingTest
extends A { OverridingTest one(){ //OverridingTest.java:11: one()
in OverridingTest cannot override one() //in A; attempting to
assign weaker access privileges; was public return new
OverridingTest(); } public static void main(String[] args) {
System.out.println("Hello World!"); } } Success case: class A { A
one(A a ){ return new OverridingTest(); } A one(OverridingTest a){
return new OverridingTest(); } } //Arguments types are not exactly
same. 3. The throws clause: Every method has RutimeException
(unchecked exception) in its throws clause by default. Sub class
method should not define checked exception in throws clause if the
super class method didnt. Sub class method can throw its sub class
exception not super class exception. 4. The overriding method (sub
class) CAN throw any unchecked (runtime) exception, regardless of
whether the overridden method declares the exception. (More in
Chapter 5.)
5.
The overriding method must NOT throw checked exceptions that are
new or broader than those declared by the overridden method. For
example, a method that declares a FileNotFoundException cannot be
overridden by a method that declares a SQLException, Exception, or
any other non-runtime exception unless it's a subclass of
FileNotFoundException. The overriding method can throw narrower or
fewer exceptions. Just because an overridden method "takes risks"
doesn't mean that the overriding subclass' exception takes the same
risks. Bottom line: an overriding method doesn't have to declare
any exceptions that it will never throw, regardless of what the
overridden method declares.
6.
Overloading: Method overloading is nothing more than having two
methods with the same name but different argument lists. Theres no
polymorphism involved with overloaded methods! Overloading lets you
make multiple versions of a method, with different argument lists
1. The return types can be different. Youre free to change the
return types in overloaded methods, as long as the argument lists
are different. 2. You cant change ONLY the return type. If only the
return type is different, its not a valid overloadthe compiler will
assume youre trying to override the method. And even that wont be
legal unless the return type is a subtype of the return type
declared in the superclass. To overload a method, you MUST change
the argument list, although you can change the return type to
anything. 3. You can vary the access levels in any direction. Youre
free to overload a method with a method thats more restrictive. It
doesnt matter, since the new method isnt obligated to fulfill the
contract of the overloaded method. class A { A one(){ return new
OverridingTest(); } OverridingTest one(){ //OverridingTest.java:7:
one() is already defined in A return new OverridingTest(); } }
Final Final classes and methods provide security. If you need
security of knowing that the methods will always work the way that
you wrote them (because they cant be overridden), a final will help
us. If you want to protect a specific method from being overridden,
mark the method with the final modifier. Mark the whole class as
final if you want to guarantee that none of the methods in that
class will ever be overridden. Abstract class: Consider a scenario
where Animal is the super class for Tiger, Lion and Wolf. We can
create objects for Tiger, Lion and Wolf. We cant create object for
Animal. Because we dont know what color, size and how many of legs
the animal has. ENCAPSULATION (data hiding) The technique of hiding
the internal implementation detail of an object from its external
views. Internal structure remains private and services can be
accessed by other objects only through messages passed via a
clearly defined interface. Encapsulation ensures that the object
providing service can prevent other objects from manipulating its
data or procedures directly, and it enables the object requesting
service to ignore the details of how that service is provided.
Access specifiers: Protected: The sub class can access protected
members of super class only through the inheritance. Once the
subclass-outside-the-package inherits the protected member, that
member (as inherited by the subclass) becomes private to any code
outside the subclass, with the exception of subclasses of the
subclass. The protected members become private to the subclass and
its subclasses. The bottom line: when a
subclass-outside-the-package inherits a protected member, the
member is essentially private inside the subclass, such that only
the subclass and its subclasses can access it through the
inheritance. For years, object-oriented programmers knew that one
of the main OOP features is encapsulation: an ability to hide and
protect object internals. Private and protected properties were
invented to support this. But who are we hiding from? From stupid
developers who will decide to use our smart framework classes.
The Private and Protected section of the classes you design
should contain Abstraction "java abstraction is data hiding
concepts" this is completely incorrect. Encapsulation is used for
data hiding not abstraction. Abstraction is a design concept on
which we only declare functionality doesn't define it because we
don't know about them at design point. For example if you are
designing Server Class you know that there must be start() and
stop() method but you don't know the exact way each server will
start and stop because that will vary from server to server, so in
this case we will declare Server as abstract. In Java abstraction
is implemented using either abstract class or interface. Interface
achieves 100% abstractness. what is abstraction ? something which
is not concrete , something which is incomplete. java has concept
of abstract classes , abstract method but a variable can not be
abstract. an abstract class is something which is incomplete and
you can not create instance of it for using it.if you want to use
it you need to make it complete by extending it. an abstract method
in java doesn't have body , its just a declaration. so when do you
use abstraction ? ( most important in my view ) when I know
something needs to be there but I am not sure how exactly it should
look like. e.g. when I am creating a class called Vehicle, I know
there should be methods like start() and Stop() but don't know
start and stop mechanism of every vehicle since they could have
different start and stop mechanism e..g some can be started by kick
or some can be by pressing buttons .
the same concept apply to interface also , which we will discuss
in some other post. so implementation of those start() and stop()
methods should be left to there concrete implementation e.g.
Scooter , MotorBike , Car etc. In Java Interface is an another way
of providing abstraction, Interfaces are by default abstract and
only contains public static final constant or abstract methods. Its
very common interview question is that where should we use abstract
class and where should we use Java Interfaces in my view this is
important to understand to design better java application, you can
go for java interface if you only know the name of methods your
class should have e.g. for Server it should have start() and stop()
method but we don't know how exactly these start and stop method
will work. if you know some of the behavior while designing class
and that would remain common across all subclasses add that into
abstract class. Interfaces An interface is a contract between a
class and the outside world. When a class implements an interface,
it promises to provide the behavior published by that interface.
Implementing an interface allows a class to become more formal
about the behavior it promises to provide. Interfaces form a
contract between the class and the outside world, and this contract
is enforced at build time by the compiler. If your class claims to
implement an interface, all methods defined by that interface must
appear in its source code before the class will successfully
compile. 1. Interface is 100 % abstract. 2. Interfaces increase the
abstractness by moving one step further when compare to abstract
class and only allows to declare abstract methods and their
implementation. 3. Interfaces are implicitly abstract. 4. Interface
methods are by default public and abstract, they can not be static,
native and strictfp. 5. All the member variables in interface are
constants, public , static and final.
Difference between String, StringBuffer and StringBuilder
Methods in String produce new objects rather than modifying the
same object. So String is immutable(unchanged). String buffer and
String builder is mutable(can be changed). And StringBuffer is
thread safe (synchronized). StringBuilder is not. Nested classes
Nested classes are divided into two categories: static and
non-static. Nested classes that are declared static are simply
called static nested classes. Non-static nested classes are called
inner classes. A nested class is a member of its enclosing class.
Non-static nested classes (inner classes) have access to other
members of the enclosing class, even if they are declared private.
Static nested classes do not have access to other members of the
enclosing class. As a member of the OuterClass, a nested class can
be declared private, public, protected, or package private. (Recall
that outer classes can only be declared public or package private.)
Inner classes: 1. Inner classes cant have main method to run,
because a regular inner class can't have static declarations of any
kind. The only way you can access the inner class is through a live
instance of the outer class! In other words, only at runtime when
there's already an instance of the outer class to tie the inner
class instance to. 2. Since being a member of outer class, Inner
class can access the members of outer class even they are private.
3. Inner class objects always have tied with outer class object. To
create an instance of an inner class, you must have an instance of
the outer class to tie to the inner class. There are no exceptions
to this rule: an inner class instance can never stand alone without
a direct relationship to an instance of the outer class. 4. You
always need to create instance for inner class before you using the
members. Declaring the inner class does not meant that outer class
has a object of inner class. 5. Inner classes are basically
designed to be helper classes for Outer classes. 6. Sample public
class Outer { class Inner{
void display(){ System.out.println("Welcome to Inner classes");
} } void showMsg(){ Inner inner = new Inner(); //Outer.Inner inner1
= this.new Inner(); inner.display(); } public static void
main(String[] args) { Outer.Inner inner = new Outer().new Inner();
inner.display(); } } 7. Member Modifiers Applied to Inner Classes A
regular inner class is a member of the outer class just as instance
variables and methods are, so the following modifiers can be
applied to an inner class: 1. I final 2. I abstract 3. I public 4.
I private 5. I protected 6. I staticbut static turns it into a
static nested class not an inner class 7. I strictfp Method local
Inner Class & Anonymous Inner Class Both the classes cannot
access outside method local variables unless they are final. You
must create an instance of this inner class before you use it.
Static Inner Classes A static nested class is simply a class that's
a static member of the enclosing class: The class itself isn't
really "static"; there's no such thing as a static class. The
static modifier in this case says that the nested class is a static
member of the outer class. That means it can be accessed, as with
other static members, without having an instance of the outer
class. Just as a static method does not have access to the instance
variables and nonstatic methods of the class, a static nested class
does not have access to the instance variables and nonstatic
methods of the
outer class. Look for static nested classes with code that
behaves like a nonstatic (regular inner) class.
Inner Class Can have declaration of any kind static Can be
instantiated from outside of class of outer class Can be created in
a method No
Static Inner Class yes
Method Local Inner Class No
Anonymous Inner class No
Yes
Yes
No
No
No
No
Yes
Yes
Enume You should use enum types any time you need to represent a
fixed set of constants. Java programming language enum types are
much more powerful than their counterparts in other languages. The
enu declaration defines a class m (called an enum type). The enum
class body can include methods and other fields. The compiler
automatically adds some special methods when it creates an enum.
For example, they have a static vau method that l returns an array
containing all of the values of the enum in the order they are
declared. This method is commonly used in combination with the
for-each construct to iterate over the values of an enum type. The
constructor for an enum type must be package-private or private
access. It automatically creates the constants that are defined at
the beginning of the enum body. You cannot invoke an enum
constructor yourself. All enums implicitly extend jvlE Java does
not support multiple inheritance, an enum .aan Since .. ag n cannot
extend anything else. public enum Day {
MONDAY (1), TUESDAY (2), WEDNESDAY (3), THURSDAY (4), FRIDAY
(5), SATURDAY (6), SUNDAY (7); private int day; private Day(int
day){ this.setDay(day); } @Deprecated public void setDay(int day) {
this.day = day; } public int getDay() { return day; } public static
Day getDay(int day){ Day d = null; for(Day d1 : values()){
if(d1.getDay() == day){ d = d1; break; } } return d; } } Shutdown
Hook In many circumstances, you need a chance to do some clean-up
when the user shuts down your application. The problem is, the user
does not always follow the recommended procedure to exit. Java
provides an elegant way for programmers to execute code in the
middle of the shutdown process, thus making sure your clean-up code
is always executed. This article shows how to use a shutdown hook
to guarantee that clean-up code is always run, regardless of how
the user terminates the application. You may have code that must
run just before an application completely exits. For example, if
you are writing a text editor with Swing and your application
creates a temporary edit file when it starts, this temporary file
must be deleted when the user closes your application. If you are
writing a servlet container such as Tomcat or
Jetty, you must call the destroy method of all loaded servlets
before the application shuts down. In many cases, you rely on the
user to close the application as prescribed. For instance, in the
first example, you may provide a JButton that, when clicked, runs
the clean up code before exiting. Alternatively, you may use a
Window listener that listens to the windowClosing event. Tomcat
uses a batch file that can be executed for a proper shutdown.
However, you know that the user is the king; he or she can do
whatever they want with the application. He or she might be nice
enough to follow your instruction, but could just close the console
or log off of the system without first closing your application. In
Java, the virtual machine shuts down itself in response to two
types of events: first, when the application exits normally, by
calling the System.exit method or when the last non-daemon thread
exits. Second, when the user abruptly forces the virtual machine to
terminate; for example, by typing Ctrl+C or logging off from the
system before closing a running Java program. Fortunately, the
virtual machine follows this two-phase sequence when shutting down:
The virtual machine starts all registered shutdown hooks, if any.
Shutdown hooks are threads registered with the Runtime. All
shutdown hooks are run concurrently until they finish. 2. The
virtual machine calls all uninvoked finalizers, if appropriate. In
this article, we are interested in the first phase, because it
allows the programmer to ask the virtual machine to execute some
clean-up code in the program. A shutdown hook is simply an instance
of a subclass of the Thread class. Creating a shutdown hook is
simple: 1. Write a class extending the Thread class. Provide the
implementation of your class' run method. This method is the code
that needs to be run when the application is shut down, either
normally or abruptly. 3. In your application, instantiate your
shutdown hook class. 4. Register the shutdown hook with the current
runtime's addShutdownHook method. As you may have noticed, you
don't start the shutdown hook as you would other threads. The
virtual machine will start and run your shutdown hook when it runs
its shutdown sequence. 1. 2. The code in Listing 1 provides a
simple class called
ShutdownHookDemo and a subclass of Thread named ShutdownHook.
Note that the run method of the ShutdownHook class simply prints
the string "Shutting down" to the console. Of course, you can
insert any code that needs to be run before the shutdown. After
instantiation of the public class, its start method is called. The
start method creates a shutdown hook and registers it with the
current runtime. ShutdownHook shutdownHook = new ShutdownHook();
Runtime.getRuntime().addShutdownHook(shutdownHook); Then, the
program waits for the user to press Enter. System.in.read(); When
the user does press Enter, the program exits. However, the virtual
machine will run the shutdown hook, printing the words "Shutting
down." Listing 1: Using ShutdownHook package test; public class
ShutdownHookDemo { public void start() {
System.out.println("Demo"); ShutdownHook shutdownHook = new
ShutdownHook(); Runtime.getRuntime().addShutdownHook(shutdownHook);
} public static void main(String[] args) { ShutdownHookDemo demo =
new ShutdownHookDemo(); demo.start(); try { System.in.read(); }
catch(Exception e) { } } } class ShutdownHook extends Thread {
public void run() { System.out.println("Shutting down"); } }
As another example, consider a simple Swing application whose
class is called MySwingApp (see Figure 1). This application creates
a temporary file when it is launched. When closed, the temporary
file must be deleted. The code for this class is given in Listing 2
on the following page.
Figure 1: A simple Swing application package test;
import import import import import
java.awt.*; javax.swing.*; java.awt.event.*; java.io.File;
java.io.IOException;
public class MySwingApp extends JFrame { JButton exitButton =
new JButton(); JTextArea jTextArea1 = new JTextArea(); String dir =
System.getProperty("user.dir"); String filename = "temp.txt";
public MySwingApp() { exitButton.setText("Exit");
exitButton.setBounds(new Rectangle(304, 248, 76, 37));
exitButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
exitButton_actionPerformed(e); } });
this.getContentPane().setLayout(null); jTextArea1.setText("Click
the Exit button to quit"); jTextArea1.setBounds(new Rectangle(9, 7,
371, 235)); this.getContentPane().add(exitButton, null);
this.getContentPane().add(jTextArea1, null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setBounds(0,0, 400, 330); this.setVisible(true);
initialize(); } private void initialize() { // create a temp file
File file = new File(dir, filename); try {
System.out.println("Creating temporary file");
file.createNewFile(); } catch (IOException e) {
System.out.println("Failed creating temporary file."); } } private
void shutdown() { // delete the temp file File file = new File(dir,
filename); if (file.exists()) { System.out.println("Deleting
temporary file."); file.delete(); } } void
exitButton_actionPerformed(ActionEvent e) { shutdown();
System.exit(0); } public static void main(String[] args) {
MySwingApp mySwingApp = new MySwingApp(); } } When run, the
application calls its initialize method. The initialize method, in
turn, creates a temporary file called temp.txt in the user's
directory: private void initialize() { // create a temp file File
file = new File(dir, filename); try {
System.out.println("Creating temporary file");
file.createNewFile(); } catch (IOException e) {
System.out.println("Failed creating temporary file."); } } When the
user closes the application, the application must delete the
temporary file. We hope that the user will always click the Exit
button-by doing so, the shutdown method (which deletes the
temporary file) will always be called. However, the temporary file
will not be deleted if the user closes the application, by clicking
the X button of the frame or by some other means. Listing 3 offers
a solution to this. It modifies the code in Listing 2 by providing
a shutdown hook. The shutdown hook class is declared as an inner
class so that it has access to all of the methods of the main
class. In Listing 3, the shutdown hook's run method calls the
shutdown method, guaranteeing that this method will be invoked when
the virtual machine shuts down. Listing 3: Using a shutdown hook in
the Swing application package test; import import import import
import java.awt.*; javax.swing.*; java.awt.event.*; java.io.File;
java.io.IOException;
public class MySwingAppWithShutdownHook extends JFrame { JButton
exitButton = new JButton(); JTextArea jTextArea1 = new JTextArea();
String dir = System.getProperty("user.dir"); String filename =
"temp.txt"; public MySwingAppWithShutdownHook() {
exitButton.setText("Exit"); exitButton.setBounds(new Rectangle(304,
248, 76, 37)); exitButton.addActionListener(new
java.awt.event.ActionListener() { public void
actionPerformed(ActionEvent e) { exitButton_actionPerformed(e);
} }); this.getContentPane().setLayout(null);
jTextArea1.setText("Click the Exit button to quit");
jTextArea1.setBounds(new Rectangle(9, 7, 371, 235));
this.getContentPane().add(exitButton, null);
this.getContentPane().add(jTextArea1, null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setBounds(0,0,
400, 330); this.setVisible(true); initialize(); } private void
initialize() { // add shutdown hook MyShutdownHook shutdownHook =
new MyShutdownHook();
Runtime.getRuntime().addShutdownHook(shutdownHook); // create a
temp file File file = new File(dir, filename); try {
System.out.println("Creating temporary file");
file.createNewFile(); } catch (IOException e) {
System.out.println("Failed creating temporary file."); } } private
void shutdown() { // delete the temp file File file = new File(dir,
filename); if (file.exists()) { System.out.println("Deleting
temporary file."); file.delete(); } } void
exitButton_actionPerformed(ActionEvent e) { shutdown();
System.exit(0); }
public static void main(String[] args) {
MySwingAppWithShutdownHook mySwingApp = new
MySwingAppWithShutdownHook(); } private class MyShutdownHook
extends Thread { public void run() { shutdown(); } } } Pay special
attention to the initialize method in the class shown in Listing 3.
The first thing it does is to create an instance of the inner class
MyShutdownHook, which extends a Thread: // add shutdown hook
MyShutdownHook shutdownHook = new MyShutdownHook(); Once you get an
instance of the MyShutdownHook class, pass it to the
addShutDownHook method of the Runtime, as in the following line:
Runtime.getRuntime().addShutdownHook(shutdownHook); The rest of the
initialize method is similar to the initialize method in the class
given in Listing 2. It creates a temporary file and prints a string
"Creating temporary file": // create a temp file File file = new
File(dir, filename); try { System.out.println("Creating temporary
file"); file.createNewFile(); } catch (IOException e) {
System.out.println("Failed creating temporary file."); } Now, start
the small application given in Listing 3. Check that the temporary
file is always deleted, even if you abruptly shut down the
application. Summary Sometimes we want our application to run some
clean-up code prior to shutting down. However, it is impossible to
rely on the user to always quit properly. The shutdown hook
described in this article offers a solution that guarantees that
the clean-up code is run, regardless of
how the user closes the application. Q: What is OOPS, object and
class. A: OOPS provide the way of modularizing the program by
creating partitioned memory area for both data and operations. OOPS
allows describing the problem in terms of problem rather than in
terms of computer where the solution will run and follows bottom-up
approach in design. Objects are run time entities (physical
entities) represent the real world entities. That has both data and
operations to manipulate data. We can make request to object asking
it to perform its operations by sending messages (making a call to
method of object). Each object occupies its own memory. Thats the
way all object are communicate each other through sending message.
Object is an entity, we can feel and touch. Objects are really
existed in real world. In theory the conceptual concept of problem
is represented as object in problem space. Class is user defined
data type that represents the logical idea of real world entity and
describes the properties and behavior of real world entity. Class
is blue print or plan, we cant feel and touch. Classes are not
existed in real world. Q. What is inheritance? A. Is the process by
which an object can acquires the properties of another object.
Inheritance allows the creation of hierarchical classification.
Which defines an interface is common for a set of related items.
Which provides is-a relationship between classes. For example A
Triangle is a Shape. A class is inherited is called superclass and
a class does inheriting is called subclass. The main goal of
inheritance is to provide code reusability. a) All the messages
send to object of superclass can also send to subclass. b) We can
add additional features to the existing type with out disturbing
it. c) We can change the behavior of new class. This is called
overriding. It means we are using same interface as existing type,
but we are making it something different for new type. Q What is
the difference between an Interface and an Abstract class? : A:An
abstract class provides common interface for all its subclasses.
And this common interface expressed differently in sub classes. An
abstract class is a class that is declared abstractit may or may
not include abstract methods. When an abstract class is subclassed,
the subclass usually provides implementations for all of the
abstract
methods in its parent class. However, if it does not, the
subclass must also be declared abstract. Abstract classes are
similar to interfaces, except that they provide a partial
implementation, leaving it to subclasses to complete the
implementation. An abstract class can have instance methods,
instance variables that implement a default behavior. Abstract
class may also contain abstract methods which has no
implementation. An abstract class may have static fields and static
methods. You can use these static members with a class referencefor
example, AbstractClass.staticMethod()as you would with any other
class. An abstract class can not be instantiated. And may refer the
sub classs objects. Any class with an abstract method is
automatically abstract itself, and must be declared as such. A
class may be declared abstract even if it has no abstract methods.
This prevents it from being instantiated. An abstract class is a
class which may have the usual flavors of class members (private,
protected, etc.), but has some abstract methods which are not
private.
abstract class GraphicObject { int x, y; ... void moveTo(int
newX, int newY) { ... } abstract void draw(); abstract void
resize(); } class Circle extends GraphicObject { void draw() { ...
} void resize() { ... } } class Rectangle extends GraphicObject {
void draw() { ... }
void resize() { ... } } An Interface can only declare constants
and abstract methods which has no implementation. An interface has
all public members and no implementation. Interface may contain
fields those are public, static and final implicitly. An interface
may can extend any number of interfaces. All methods declared in an
interface are implicitly public, so the public modifier can be
omitted. An interface can contain constant declarations in addition
to method declarations. All constant values defined in an interface
are implicitly public, static, and final. Once again, these
modifiers can be omitted. An interface cannot provide any code at
all, much less default code. An abstract class can provide complete
code, default code, and/or just stubs that have to be overridden.
Abstract class provides is-a relationship. Interface provides has-a
or can-do relationship. 1.MyThread is a Thread. 2.MyCode has a
runnable independent capability(Runnable). Interfaces are often
used to describe the minor abilities of a class, not its central
identity, e.g. an Automobile class might implement the Recyclable
interface, which could apply to many otherwise totally unrelated
objects. An abstract class defines the central part identity of its
children. If you defined a Dog abstract class then Damamation
descendants are Dogs(is-a), they are not only dogable. In a Java
context, users should typically implement the Runnable interface
rather than extending Thread, because they're not really interested
in providing some new Thread functionality, they normally just want
some code to have (has-a)the capability of thread(running
independently). They want to create something that can be run in a
thread, not a new kind of thread. When you implement the inteface,
It strictly force you to start from scratch without any default
implementation. You have to obtain your tools from other classes;
nothing comes with the interface other than a few constants. This
gives you freedom to implement a very different internal design.
You must use the abstract class as-is for the code base, with all
its attendant belongings, good or bad. The abstract class author
has imposed structure on you. Depending on the cleverness of the
author of the abstract class, this may be good or bad. If
implementors/subclasses are homogeneous, tend towards an abstract
base class. If they are heterogeneous, use an interface. If
the various objects are all of-a-kind, and share a common state
and behavior, then tend towards a common base class(abstract
class). If all they share is a set of method signatures, then tend
towards an interface. When to choose Choosing interfaces and
abstract classes is not an either/or proposition. If you need to
change your design frequently, make it an interface. However, you
may have abstract classes that provide some default behavior.
Abstract classes are excellent candidates inside of application
frameworks. Abstract classes let you define some behaviors; they
force your subclasses to provide others. For example, if you have
an application framework, an abstract class may provide default
services such as event and message handling. Those services allow
your application to plug in to your application framework.
Q. Difference between Overloading and overriding A. Using the
same name for operations on different types is called overloading.
Method overloading allows several methods to share the same name
but with a different set of parameters (does not depend on return
type). Each overloaded method performs a similar task. Overloaded
methods are normally used to perform similar operations that
involve different programming logic on different data types.
Overloading occurs within a class. Another common use of
overloading is when defining constructors: public Time( ) //default
constructor public Time( int hr, int min, int sec ) //general
constructor public Time( Time time ) //copy constructor Overriding
is similar to overloading, with the exception that it occurs
between classes and each method has the same signature. An instance
method in a subclass with the same signature (name, plus the number
and the type of its parameters) and return type as an instance
method in the superclass overrides the superclass's method.A
subclass can override a superclass method by redefining that
method. When the method is mentioned by name in the subclass, then
the subclass version is automatically used. Overloading deals with
multiple methods in the same class with the same name but different
signatures. Overriding deals with two
methods, one in a parent class and one in a child class that
have the same signature. Overloading lets you define a similar
operation in different ways for different data. Overriding lets you
define a similar operation in different ways for different object
types. Instance method cannot override the static methods and
vice-versa. While overriding be care of weaker privileges (The
method must have higher access specifier than that of in super
class). Q What is the purpose of garbage collection in Java, and
when is it : used? A:The purpose of garbage collection is to
identify and discard objects that are no longer needed by a program
so that their resources can be reclaimed and reused. A Java object
is subject to garbage collection when it becomes unreachable to the
program in which it is used. In java memory deallocation is done
automatically. When object has no reference is exists then it is
treated to be no longer needed. Then the garbage collector reclaims
the memory occupied by that object. The finalize () method on
object is called just prior to object is going to be garbage
collected. Which is usually cleans up or releases the resources
used by that object. We can do garbage collection manually by a
call System.gc(); Example: class NoOfObjects { String nameOfObject;
static int count=0; NoOfObjects(String name) { nameOfObject=name;
System.out.println("object "+nameOfObject+" is created"); count++;
} /*finalize method is called just before object is going to be
garbage collected.*/ public void finalize() { count--;
System.out.println(nameOfObject+" is garbage collected"); } public
static void main(String[] args) { NoOfObjects a=new
NoOfObjects("a");
NoOfObjects b=new NoOfObjects("b"); new NoOfObjects("c");
System.out.println("no of objects "+NoOfObjects.count); b=null;
System.gc(); System.out.println("no of objects
"+NoOfObjects.count); } } Initializing the base class
are
are
In super class, when we dont have any constructors or we have
implemented default constructor and parameterized constructors,
there is no need to call super class constructor from base class
constructor. If we have parameterized constructor and not having
any implemented default constructor then we have to call super
classs constructor from base class constructor. Why because the
default is lost when we have implemented any constructor.
Initializing and loading of child class Class (.class file) is
loaded at the point of used first. This is usually when the object
of that is class is constructed, but loading also occurs when a
static field or static method is accessed. When a class file is
going to be loaded it checks extends keyword, if there is super
class then first super class is loaded then the child class. If the
base class again has another base class, that second class would
then be loaded, and so on. Class A { } Class B extends A { } Class
C extends B { } Class Demo { //C.staticMethod(); or new C(); ----}
A is first loaded, then B, finally C. 1. All the static variables
and static block are loaded in textual order (the order that you
write down in class definition). And statics also initialized only
once. 2. After all the initialization variables and initialization
block are loaded in textual order (the order that you write down in
class definition). And these are initialized as many as times as no
of objects are created.
3. Finally constructor is executed. For example Class A { }
Clsss B extends A {} Class Demo { Public static void main(String
a[]) { B ob1 =new B(); B ob2=new B(); } } //end Demo Execution flow
B ob1=new B(); 1. Static variables and static block of class A in
textual order. These are executed only once. 2. Static variables
and static block of class B in textual order. These are executed
only once. 3. Instance variables and initialization block of class
A in textual order and finally constructor. 4. Instance variables
and initialization block of class B in textual order and finally
constructor. B ob2=new B() 5. Instance variables and initialization
block of class A in textual order and finally constructor. 6.
Instance variables and initialization block of class B in textual
order and finally constructor. What is final? Final means it is
constant. A field is both static and final is single storage field
that cannot be changed. Final classes can not be inherited. We can
change the fields in final class objects as well as final objects
(it means fields in final class are not final). All the methods in
final class are implicitly final. Final primitives are can not be
changed. Final referenced variables are can not point to another
objects. But the objects are modifiable. This is also for arrays.
Those array contents can be modified. Finals that are declared as
final but not given an initialization values are called blank
finals. Blank finals must be initialized in constructor. Final
arguments cannot be changed (primitives cannot be changed,
references can not point to other objects) within the method. But
we can read them. Final methods are not overridden. We can prevent
the change of code. All the private methods in a class are
implicitly final. final class B {
final int b; int c; B() { b=c; } void change(int i) { //b=i;
final variable b can not be changed } int a=40; } class A //extends
B --A final class canot be inherited { A () { } A (B b,final int
c,final B d) { b=new B();//ok //d=new B();//cant change //c=20;
cannot change } final private void bb() { } int y; } Public class
FinalDemo { final int x=30; final A ob=new A(); final int arr[]=new
int[9]; void fun1() { ob.y=20; arr[6]=90; //x=80; primitive finals
can not be changed //ob=new A();
//arr=new int[90]; int z; z=20; System.out.println(z); final A
a; //System.out.println(a); //a.y=0; we cannot use local variable
before //assinging it even it is non-final B oa=new B(); oa.a=70;
//we can change final class objects System.out.println("ok"); } /**
* @param args */ public static void main(String[] args) { FinalDemo
i=new FinalDemo(); i.fun1(); i.ob.y=80; //x=90; // TODO
Auto-generated method stub } } Q. What is singleton java class? A
java class allows to create only one object for it is called
singleton java class. Creation: class SingleTon { private static
SingleTon obj=null; private SingleTon() { } static SingleTon
getObj() { obj=new SingleTon(); return obj; } public clone()
{ throw new CloneNotSupportedException(); } }
Q Describe synchronization in respect to multithreading. :
A:With respect to multithreading, synchronization is the capability
to control the access of multiple threads to shared resources.
Without synchronization, it is possible for one thread to modify a
shared variable while another thread is in the process of using or
updating same shared variable. This usually leads to significant
errors. Synchronization allows one thread can use the resource at a
time. In java every object has its own monitor implicitly so that
it is entered automatically when a thread uses a objects
synchronized method, no other threads can invoke any synchronized
method on same object. Q Explain different way of using thread? :
A:The thread could be implemented by using Runnable interface or by
inheriting from the Thread class. The former is more advantageous,
because when you are going for multiple inheritance., the only
interface can help. Q: What are pass by reference and passby value?
A: Pass By Reference means the passing the address itself rather
than passing the value. Passby Value means passing a copy of the
value to be passed. Q: What is HashMap and Map? A: Map is Interface
and Hashmap is class that implements that. Maps store a key / value
pairs. Keys are unique. Some Maps allows null key and null value
others can not. HashMap uses hashing when storing the elements.
When we are using HashMap, specify the object as key and value that
linked to that object key. The key is then hashed. The resulting
hashcode is used as the index at which the value is stored in map.
These hashcodes are used to look up the values. HashMap allows
nulls as both keys and values. Hashing is used to get fast lookup.
Q: Difference between HashMap and HashTable?
A: Hashtable is synchronized whereas HashMap not. The HashMap
class is roughly equivalent to HashTable, except that it is
unsynchronized and permits nulls. (HashMap allows null values as
key and value whereas Hashtable doesnt allow). HashMap does not
guarantee that the order of the map will remain constant over time.
In addition to methods defined by Map interface a Hastable adds
some of legacy methods for better performance. Q: Difference
between ArrayList and LinkedList? If you need to support random
access (getting elements from anywhere), without inserting or
removing elements at/from any place other than the end, then
ArrayList offers the optimal collection. Randomly accessing
elements in ArrayList is a constant time operation. It takes same
time regardless where from you accessing element. In LinkedList it
is expensive. Both are not synchronized. Both allow null values.
If, however, you need to frequently add and remove elements from
the middle of the list and only access the list elements
sequentially then LinkedList offers the better implementation. In
addition, LinkedList adds several methods for working with the
elements at the ends of the list (only the new methods are shown in
the following diagram):
By using these new methods, you can easily treat the LinkedList
as a stack, queue, or other end-oriented data structure. Basics The
underlaying data structure for the ArrayList is the array, and for
the LinkedList the linked list. This means for the ArrayList; fast
random access but slow insert/remove except adding elements at the
end because the array index gets you right to that element. But
then adding and deleting at the start and middle of the arraylist
would be slow, because all the later elements have to copied
forward or backward. (Using System.arrayCopy()). when run an
"add(Object o)" command a new array will be created
with n+1 dimension. All "older" elements will be copied to first
n elements and last n+1 one will filled with the value which you
provide with add() method. To avoid that internal re-copying of
arrays you should use ensureCapacity(int requestCapacity) method it
will create an array only once. For example if you need to add new
element to the end of an ArrayList you have to look at the size of
the collection and then add that new element at n+1 place. In
LinkedList you do it directly by addLast(E e) method. And for the
LinkedList; slow random access but fast insert/remove anywhere.
LinkedList is made up of a chain of nodes. Each node stores an
element and the pointer to the next node. A singly linked list only
has pointers to next. A doubly linked list has a pointer to the
next and the previous element. This makes walking the list backward
easier. Linked lists are fast for inserts and deletes anywhere in
the list, since all you do is update a few next and previous
pointers of a node. Q Difference between Vector and ArrayList? :
The Vector is a historical collection which is replaced by
ArrayList. The documentation for ArrayList states "This class
roughly equivalent to Vector, except that it unsynchronized."
is is
An ArrayList could be a good choice if you need very flexible
Array type of collection with limited functionality. Vectors are a
lot slower, performance wise, than ArrayLists. So, use Arraylists
unless you need synchronised lists. Vector is historical class and
was retrofitted to satisfy the List interface, but still retain the
"old" methods (like getElementAt()). Vector is synchronized whereas
ArrayList is not. Vector has many legacy methods that shows high
performance and those are not part of collections. public
synchronized void removeElementAt(int); protected void
removeRange(int,int); public synchronized java.lang.Object
firstElement(); public synchronized java.lang.Object lastElement();
public java.util.Enumeration elements(); public synchronized
java.util.List subList(int,int); we can use Collections wrapper to
get synchronization list List myList=new ArrayList(); myList =
Collections.synchronizedList(myList)
Q. Difference between Iterator and ListLterator? A.ListIterator
are obtainable only from collections that implements List
interface. Iterator provides only forward access whereas List
iterator can move in both directions. List iterator has higher
performance. Iterator supports only removal of its content.
ListIterator can also add and modify the elements to its content.
ListIterator can produce the previous and next indexes respect to
the current position. Q: Difference between Swing and Awt? A: AWT
are heavy-weight components. Swings are light-weight components.
Hence swing works faster than AWT. Q: What is the difference
between a constructor and a method? A: A constructor is a member
function of a class that is used to create objects of that class.
It has the same name as the class itself, has no return type, and
is invoked using the new operator. A method is an ordinary member
function of a class. It has its own name, a return type (which may
be void), and is invoked using the dot operator.
Q: State the significance of public, private, protected, default
modifiers both singly and in combination and state the effect of
package relationships on declared items qualified by these
modifiers. A: public : Public class is visible in other packages,
field is visible everywhere (class must be public too) private:
Private variables or methods may be used only by an instance of the
same class that declares the variable or method, A private feature
may only be accessed by the class that owns the feature. protected
: Is available to all classes in the same package and also
available to all subclasses of the class that owns the protected
feature. This access is provided even to subclasses that reside in
a different package from the class that owns the protected feature.
default:What you get by default i.e., without any access modifier
(public or private or protected).It means that it is visible to all
within a particular package. Q What is static in java? :
A:Static block is executed when a class is loaded into memory.
Static means one per class, not one for each object no matter how
many instance of a class might exist. This means that you can use
them without creating an instance of a class. Static methods and
variables can be used in non-static methods, reverse is not
possible. Static methods can be overridden. you can't override a
static method with a non-static method. In other words, you can't
change a static method into an instance method in a subclass. Q
What is final? : A:A final class can't be extended ie., final class
may not be subclassed. A final method can't be overridden when its
class is inherited. You can't change value of a final variable (is
a constant). Q What if the main method is declared as private? :
A:The program compiles properly but at runtime it will give "Main
method not public." message. [ Recei ved from Sandes h Sadhal e] Q:
What if the static modifier is removed from the signature of the
main method? A: Program compiles. But at runtime throws an error
"NoSuchMethodError". [ Receive d from Sandesh Sadhale] Q What if I
write static public void instead of public static void? : A:Program
compiles and runs properly. [ Received from Sandesh Sadhale] Q What
if I do not provide the String array as the argument to the :
method? A:Program compiles but throws a runtime error
"NoSuchMethodError". [ Received from Sandesh Sadhale] Q What is the
first argument of the String array in main method? : A:The String
array is empty. It does not have any element. This is
unlike C/C++ where the first element by default is the program
name. [ Received from Sandesh Sadhale] Q If I do not provide any
arguments on the command line, then the : String array of Main
method will be empty or null? A:It is empty. But not null. [
Received from Sandesh Sadhale] Q How can one prove that the array
is not null but empty using one line : of code? A:Print
args.length. It will print 0. That means it is empty. But if it
would have been null then it would have thrown a
NullPointerException on attempting to print args.length. [ Received
from Sandesh Sadhale] Q What environment variables do I need to set
on my machine in order : to be able to run Java programs?
A:CLASSPATH and PATH are the two variables. [ Receiv ed from
Sandesh Sadhale] Q Can an application have multiple classes having
main method? : A:Yes it is possible. While starting the application
we mention the class name to be run. The JVM will look for the Main
method only in the class whose name you have mentioned. Hence there
is not conflict amongst the multiple classes having main method. [
Receiv ed from Sandesh Sadhale] Q Can I have multiple main methods
in the same class? : A:No the program fails to compile. The
compiler says that the main method is already defined in the class.
[ Receiv ed from Sandesh Sadhale] Q Do I need to import java.lang
package any time? Why ? : A:No. It is by default loaded internally
by the JVM. [ Receiv ed from Sandesh Sadhale]
Q Can I import same package/class twice? Will the JVM load the :
package twice at runtime? A:One can import the same package or same
class multiple times. Neither compiler nor JVM complains about it.
And the JVM will internally load the class only once no matter how
many times you import the same class. Q: A: What are Checked and
UnChecked Exception? A checked exception is some subclass of
Exception (or Exception itself), excluding class RuntimeException
and its subclasses. Making an exception checked forces client
programmers to deal with the possibility that the exception will be
thrown. eg, IOException thrown by java.io.FileInputStream's read()
method Unchecked exceptions are RuntimeException and any of its
subclasses. Class Error and its subclasses also are unchecked. With
an unchecked exception, however, the compiler doesn't force client
programmers either to catch the exception or declare it in a throws
clause. In fact, client programmers may not even know that the
exception could be thrown. eg, StringIndexOutOfBoundsException
thrown by String's charAt() method Checked exceptions must be
caught at compile time. Runtime exceptions do not need to be.
Errors often cannot be. What are different types of inner classes?
Nested top-level classes, Member classes, Local classes, Anonymous
classes Nested top-level classes- If you declare a class within a
class and specify the static modifier, the compiler treats the
class just like any other top-level class. Any class outside the
declaring class accesses the nested class with the declaring class
name acting similarly to a package. eg, outer.inner. Top-level
inner classes implicitly have access only to static variables.There
can also be inner interfaces. All of these are of the nested
top-level variety. Member classes - Member inner classes are just
like other member methods and member variables and access to the
member class is restricted, just like methods and variables. This
means a public member class acts similarly to a nested top-level
class. The primary difference between member classes and nested
top-level classes is that member classes have access to the
specific instance of the enclosing class.
Q: A:
Local classes - Local classes are like local variables, specific
to a block of code. Their visibility is only within the block of
their declaration. In order for the class to be useful beyond the
declaration block, it would need to implement a more publicly
available interface. Because local classes are not members, the
modifiers public, protected, private, and static are not usable.
Anonymous classes - Anonymous inner classes extend local inner
classes one level further. As anonymous classes have no name, you
cannot provide a constructor. Q: Are the imports checked for
validity at compile time? e.g. will the code containing an import
such as java.lang.ABCD compile? A: Yes the imports are checked for
the semantic validity at compile time. The code containing above
line of import will not compile. It will throw an error saying,can
not resolve symbol symbol : class ABCD location: package io import
java.io.ABCD; [ Receive d from Sandesh Sadhale] Q: Does importing a
package imports the subpackages as well? e.g. Does importing
com.MyTest.* also import com.MyTest.UnitTests.*? A: No you will
have to import the subpackages explicitly. Importing com.MyTest.*
will import classes in the package MyTest only. It will not import
any class in any of it's subpackage. [ Receive d from Sandesh
Sadhale] Q: What is the difference between declaring a variable and
defining a variable? A: In declaration we just mention the type of
the variable and it's name. We do not initialize it. But defining
means declaration + initialization. e.g String s; is just a
declaration while String s = new String ("abcd"); Or String s =
"abcd"; are both definitions. [ Receive d from Sandesh Sadhale] Q:
What is the default value of an object reference declared as an
instance variable? A: null unless we define it explicitly. [
Receive
d from Sandesh Sadhale] Q: Can a top level class be private or
protected? A: No. A top level class can not be private or
protected. It can have either "public" or no modifier. If it does
not have a modifier it is supposed to have a default access.If a
top level class is declared as private the compiler will complain
that the "modifier private is not allowed here". This means that a
top level class can not be private. Same is the case with
protected. [ Receive d from Sandesh Sadhale] Q: What type of
parameter passing does Java support? A: In Java the arguments are
always passed by value . [ Update from Eki and Jyothish Venu] Q:
Primitive data types are passed by reference or pass by value? A:
Primitive data types are passed by value. [ Received from Sandesh
Sadhale] Q: Objects are passed by value or by reference? A: Java
only supports pass by value. With objects, the object reference
itself is passed by value and so both the original reference and
parameter copy both refer to the same object. [ Update from Eki and
Jyothish Venu] Q: What is serialization? A: Serialization is a
mechanism by which you can save the state of an object by
converting it to a byte stream. [ Received from Sandesh Sadhale] Q:
How do I serialize an object to a file? A: The class whose
instances are to be serialized should implement an interface
Serializable. Then you pass the instance to the
ObjectOutputStream which is connected to a fileoutputstream.
This will save the object to a file. [ Received from Sandesh
Sadhale] Q: Which methods of Serializable interface should I
implement? A: The serializable interface is an empty interface, it
does not contain any methods. So we do not implement any methods. [
Received from Sandesh Sadhale] Q:How can I customize the
seralization process? i.e. how can one have a control over the
serialization process? A: Yes it is possible to have control over
serialization process. The class should implement Externalizable
interface. This interface contains two methods namely readExternal
and writeExternal. You should implement these methods and write the
logic for customizing the serialization process. [ Received from
Sandesh Sadhale] Q:What is the common usage of serialization? A:
Whenever an object is to be sent over the network, objects need to
be serialized. Moreover if the state of an object is to be saved,
objects need to be serilazed. [ Received from Sandesh Sadhale]
Q:What is Externalizable interface? A: Externalizable is an
interface which contains two methods readExternal and
writeExternal. These methods give you a control over the
serialization mechanism. Thus if your class implements this
interface, you can customize the serialization process by
implementing these methods. [ Received from Sandesh Sadhale] Q:When
you serialize an object, what happens to the object references
included in the object? A: The serialization mechanism generates an
object graph for serialization. Thus it determines whether the
included object references are serializable or not. This is a
recursive process. Thus when an object is serialized, all the
included objects are also serialized alongwith the original obect.
[ Received from
Sandesh Sadhale] Q:What one should take care of while
serializing the object? A: One should make sure that all the
included objects are also serializable. If any of the objects is
not serializable then it throws a NotSerializableException. [
Received from Sandesh Sadhale] Q:What happens to the static fields
of a class during serialization? A: There are three exceptions in
which serialization doesnot necessarily read and write to the
stream. These are 1. Serialization ignores static fields, because
they are not part of ay particular state state. 2. Base class
fields are only hendled if the base class itself is serializable.
3. Transient fields. [ Received from Sandesh Sadhale Modified after
P.John David comments.] Q:Does Java provide any construct to find
out the size of an object? A: No there is not sizeof operator in
Java. So there is not direct way to determine the size of an object
directly in Java. [ Received from Sandesh Sadhale] Q:Give a
simplest way to find out the time a method takes for execution
without using any profiling tool? A: Read the system time just
before the method is invoked and immediately after method returns.
Take the time difference, which will give you the time taken by a
method for execution. To put it in code... long start =
System.currentTimeMillis (); method (); long end =
System.currentTimeMillis (); System.out.println ("Time taken for
execution is " + (end - start)); Remember that if the time taken
for execution is too small, it might show that it is taking zero
milliseconds for execution. Try it on a method which is big enough,
in the sense the one which is doing considerable amout of
processing. [ Received from Sandesh Sadhale] Q:What are wrapper
classes? A: Java provides specialized classes corresponding to each
of the primitive data types. These are called wrapper classes. They
are e.g. Integer, Character, Double etc.
[ Received from Sandesh Sadhale] Q:Why do we need wrapper
classes? A: It is sometimes easier to deal with primitives as
objects. Moreover most of the collection classes store objects and
not primitive data types. And also the wrapper classes provide many
utility methods also. Because of these resons we need wrapper
classes. And since we create instances of these classes we can
store them in any of the collection classes and pass them around as
a collection. Also we can pass them around as method parameters
where a method expects an object. [ Received from Sandesh Sadhale]
Q:What are checked exceptions? A: Checked exceptions are those
which the Java compiler forces you to catch. E.g. IOException are
checked Exceptions. [ Received from Sandesh Sadhale] Q:What are
runtime exceptions? A: Runtime exceptions are those exceptions that
are thrown at runtime because of either wrong input data or because
of wrong business logic etc. These are not checked by the compiler
at compile time. [ Received from Sandesh Sadhale] Q:What is the
difference between error and an exception? A: An error is an
irrecoverable condition occurring at runtime. Such as OutOfMemory
error. These JVM errors and you can not repair them at runtime.
While exceptions are conditions that occur because of bad input
etc. e.g. FileNotFoundException will be thrown if the specified
file does not exist. Or a NullPointerException will take place if
you try using a null reference. In most of the cases it is possible
to recover from an exception (probably by giving user a feedback
for entering proper values etc.). [ Received from Sandesh Sadhale]
Q:How to create custom exceptions? A: Your class should extend
class Exception, or some more specific type thereof. [ Received
from Sandesh Sadhale] Q:If I want an object of my class to be
thrown as an exception object, what should I do? A: The class
should extend from Exception class. Or you can extend your class
from some more precise exception type also. [ Received from Sandesh
Sadhale]
Q:If my class already extends from some other class what should
I do if I want an instance of my class to be thrown as an exception
object? A: One can not do anytihng in this scenarion. Because Java
does not allow multiple inheritance and does not provide any
exception interface as well. [ Received from Sandesh Sadhale] Q:How
does an exception permeate through the code? A: An unhandled
exception moves up the method stack in search of a matching When an
exception is thrown from a code which is wrapped in a try block
followed by one or more catch blocks, a search is made for matching
catch block. If a matching type is found then that block will be
invoked. If a matching type is not found then the exception moves
up the method stack and reaches the caller method. Same procedure
is repeated if the caller method is included in a try catch block.
This process continues until a catch block handling the appropriate
type of exception is found. If it does not find such a block then
finally the program terminates. [ Received from Sandesh Sadhale]
Q:What are the different ways to handle exceptions? A: There are
two ways to handle exceptions, 1. By wrapping the desired code in a
try block followed by a catch block to catch the exceptions. and 2.
List the desired exceptions in the throws clause of the method and
let the caller of the method handle those exceptions. [ Received
from Sandesh Sadhale] Q:What is the basic difference between the 2
approaches to exception handling? 1> try catch block and 2>
specifying the candidate exceptions in the throws clause? When
should you use which approach? A: In the first approach as a
programmer of the method, you urself are dealing with the
exception. This is fine if you are in a best position to decide
should be done in case of an exception. Whereas if it is not the
responsibility of the method to deal with it's own exceptions, then
do not use this approach. In this case use the second approach. In
the second approach we are forcing the caller of the method to
catch the exceptions, that the method is likely to throw. This is
often the approach library creators use. They list the exception in
the throws clause and we must catch them. You will find the same
approach throughout the java libraries we use. [ Received from
Sandesh Sadhale] Q:Is it necessary that each try block must be
followed by a catch
block? A: It is not necessary that each try block must be
followed by a catch block. It should be followed by either a catch
block OR a finally block. And whatever exceptions are likely to be
thrown should be declared in the throws clause of the method. [
Received from Sandesh Sadhale] Q:If I write return at the end of
the try block, will the finally block still execute? A: Yes even if
you write return as the last statement in the try block and no
exception occurs, the finally block will execute. The finally block
will execute and then the control return. [ Received from Sandesh
Sadhale] Q:If I write System.exit (0); at the end of the try block,
will the finally block still execute? A: No in this case the
finally block will not execute because when you say System. exit
(0); the control immediately goes out of the program, and thus
finally never executes. [ Received from Sandesh Sadhale] Q:How are
Observer and Observable used? A: Objects that subclass the
Observable class maintain a list of observers. When an Observable
object is updated it invokes the update () method of each of its
observers to notify the observers that it has changed state. The
Observer interface is implemented by objects that observe
Observable objects. [Received from Venkateswara Manam] Q:What is
synchronization and why is it important? A: With respect to
multithreading, synchronization is the capability to control the
access of multiple threads to shared resources. Without
synchronization, it is possible for one thread to modify a shared
object while another thread is in the process of using or updating
that object's value. This often leads to significant errors. [
Received from Venkateswara Manam] Q:How does Java handle integer
overflows and underflows? A: It uses those low order bytes of the
result that can fit into the size of the type allowed by the
operation. [ Received from Venkateswara Manam] Q:Does garbage
collection guarantee that a program will not run out of memory? A:
Garbage collection does not guarantee that a program will not run
out of memory. It is possible for programs to use up memory
resources faster than they are garbage collected. It is also
possible
for programs to create objects that are not subject to garbage
collection . [ Received from Venkateswara Manam] Q:What is the
difference between preemptive scheduling and time slicing? A: Under
preemptive scheduling, the highest priority task executes until it
enters the waiting or dead states or a higher priority task comes
into existence. Under time slicing, a task executes for a
predefined slice of time and then reenters the pool of ready tasks.
The scheduler then determines which task should execute next, based
on priority and other factors. [ Received from Venkateswara Manam]
Q:When a thread is created and started, what is its