Important Question2 Java
Important Question2 Java
Daemon threads in Java are like a service providers for other threads or objects
running in the same process as the daemon thread. Daemon threads are used for
background supporting tasks and are only needed while normal threads are
executing. If normal threads are not running and remaining threads are daemon
threads then the interpreter exits.
When a new thread is created it inherits the daemon status of its parent. Normal
thread and daemon threads differ in what happens when they exit. When the JVM
halts any remaining daemon threads are abandoned: finally blocks are not
executed, stacks are not unwound JVM just exits. Due to this reason daemon
threads should be used sparingly and it is dangerous to use them for tasks that
might perform any sort of I/O.
setDaemon(true/false) ? This method is used to specify that a thread is daemon
thread.
public boolean isDaemon() ? This method is used to determine the thread is daemon
thread or not.
Example:package com.myjava.threads;
public class DaemonThread extends Thread{
public DaemonThread(){
setDaemon(true);
}
public void run(){
System.out.println("Is this thread Daemon? - "+isDaemon());
}
public static void main(String a[]){
DaemonThread dt = new DaemonThread();
// even you can set daemon constrain here also
// it is like dt.setDeamon(true)
dt.start();
}
A protected method can be accessed by the classes within the same package or by
the subclasses of the class in any package.
What is synchronization and why is it important? Explain the use of
synchronization keyword.
Java supports multiple threads to be executed. This may cause two or more
threads to access the same fields or objects. Synchronization is a process which
1.
abstract
extends
the
implements
subclass
is
keyword
to
also
an
abstract
implement
class
interfaces
whereas
and
subclasses
should
provide
4. Abstract
classes
can
have
constructors
but
interfaces
cant
have
constructors.
5. Abstract class have all the features of a normal java class except that we
cant instantiate it. We can useabstract keyword to make a class abstract but
interfaces are a completely different type and can have only public static
final constants and method declarations.
6. Abstract classes methods can have access modifiers as public, private,
protected, static but interface methods are implicitly public and abstract, we
cant use any other access modifiers with interface methods.
7. A subclass can extend only one abstract class but it can implement multiple
interfaces.
8. Abstract classes can extend other class and implement interfaces but
interface can only extend other interfaces.
9. We can run an abstract class if it has
main()
Interfaces are used to define contract for the subclasses whereas abstract
class also define contract but it can provide other methods implementations
for subclasses to use.
What is runtime polymorphism?
Runtime polymorphism or Dynamic Method Dispatchis a process in which a call to an
overridden method is resolved at runtime rather than compile-time.In this process, an
overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the
reference variable..
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
1.
2.
1.
class A{}
class B extends A{}
A a=new B();//upcasting
class Bike{
void run(){System.out.println("running");}
}
class Bank{
int getRateOfInterest(){return 0;}
}
class Test{
public static void main(String args[]){
Bank b1=new SBI();
Bank b2=new ICICI();
Bank b3=new AXIS();
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
class Bike{
int speedlimit=90;
}
class Animal{
void eat(){System.out.println("eating");}
}
15.
16.
17.
18.
19.
20.
21.
22.
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
Output: eating
eating fruits
drinking Milk
Partial Implementations
If a class includes an interface but does not fully implement the methods defined by that interface, then
that class must bedeclared as abstract.
Explain compareTo() and charAt () in reference to string.
charAt():This method returns the character located at the String's specified index. The string indexes
start from zero.
and
if ( s1.compareTo(s2) > 0 )
System.out.println("First string is greater than second.");
else if ( s1.compareTo(s2) < 0 )
System.out.println("First string is smaller than second.");
else
System.out.println("Both strings are equal.");
that the variable is immutable: the value itself can possibly change, but the
assignment to that value cannot.
2. A method declared final cannot be changed in a subclass.
3. A final class cannot be subclassed.
Expalin left and right shift operators with example.
<<
Binary Left Shift Operator. The left operands value is moved left by the
number of bits specified by the right operand.
>>
Binary Right Shift Operator. The left operands value is moved right by the A >> 2 will give 15 which is
number of bits specified by the right operand.
1111
Support to XML parsing: Java has JAXP-APIs to read the xml data and create the xml document using
different xml parsers like DOM and SAX. These APIs provides mechanism to share data among different
applications over the internet.
Support to Web Services : Java has a rich variety of APIs to use xml technology in diverse applications
that supports N-Tiered Enterprise applications over the internet. Features like JAXB , JAXM, JAX-RPC ,
JAXR etc enables to implement web services in java applications. It makes java a most suited internet
language.
Support to java enabled Mobile devices: Java programming language is made in such a way so that it
is compatible with mobile devices also. Java language also works with any java enabled mobile devices
that support MIDP 1.0/2.0 including the symbian OS mobile devices.
Support to Personal Digital Assistants: Java language is compatible with Personal Java 1.1 such as
chaiVM, Jeode, CrEME, and JV-Lite2 or with all the later version and it also support PDAs like
HP/Compaq, iPAQ, Fujitsu-Siemens Pocket Loox and SimPad, HHP, NEC, Samsung, Sharp Electronics,
Toshiba, psion m5, and any other device.
Program that accepts number from user and converts it in to binary using wrapper class method
package com.java2novice.wrapper.integer;
public class MyIntegerToBinary {
public static void main(String a[]){
Integer i = new Integer(20);
String binary = Integer.toBinaryString(i);
System.out.println("Binary value: "+binary);
}}
A final class cannot be subclassed. Doing this can confer security and efficiency benefits, so many
of the Java standard library classes are final, such asjava.lang.System and java.lang.String.
All methods in a final class are implicitly final.
Example:
public final class MyFinalClass {...}
public class ThisIsWrong extends MyFinalClass {...}
Final variables[edit]
A final variable can only be initialized once, either via an initializer or an assignment statement. It
does not need to be initialized at the point of declaration: this is called a "blank final" variable. A
blank final instance variable of a class must be definitely assigned in every constructor of the class in
which it is declared; similarly, a blank final static variable must be definitely assigned in a static
initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases. [5]
(Note: If the variable is a reference, this means that the variable cannot be re-bound to reference
another object. But the object that it references is still mutable, if it was originally mutable.)
Unlike the value of a constant, the value of a final variable is not necessarily known at compile time.
It is considered good practice to represent final constants in all uppercase, using underscore to
separate words.[6]
Example:
public class Sphere {
// pi is a universal constant, about as constant as anything can be.
public static final double PI = 3.141592653589793;
public
public
public
public
final
final
final
final
double
double
double
double
radius;
xPos;
yPos;
zPos;
Or
What is final variable in Java?
Any variable either member variable or local variable (declared inside method or
block) modified by final keyword is called final variable. Final variables are often
declare with static keyword in java and treated as constant. Here is an example of
final variable in Java
public static final String LOAN = "loan";
String pool (String intern pool) is a special storage area in Method Area. When a
string is created and if the string already exists in the pool, the reference of the
existing string will be returned, instead of creating a new object and returning its
reference.
The following code will create only one string object in the heap.
String string1 = "abcd";
String string2 = "abcd";
Here is how it looks:
If string is not immutable, changing the string with one reference will lead to the
wrong value for the other references.
2. Caching Hashcode
The hashcode of string is frequently used in Java. For example, in a HashMap. Being
immutable guarantees that hashcode will always the same, so that it can be cashed
without worrying the changes.That means, there is no need to calculate hashcode
every time it is used. This is more efficient.
In String class, it has the following code:
private int hash;//this is used to cache hash code.
3. Facilitating the Use of Other Objects
To make this concrete, consider the following program:
HashSet<String> set = new HashSet<String>();
set.add(new String("a"));
set.add(new String("b"));
set.add(new String("c"));
for(String a: set)
a.value = "a";
In this example, if String is mutable, it's value can be changed which would violate
the design of set (set contains unduplicated elements). This example is designed for
simplicity sake, in the real Stringclass there is no value field.
4. Security
String is widely used as parameter for many java classes, e.g. network connection,
opening files, etc. Were String not immutable, a connection or file would be changed
and lead to serious security threat. The method thought it was connecting to one
machine, but was not. Mutable strings could cause security problem in Reflection
too, as the parameters are strings.
Here is a code example:
boolean connect(string s){
if (!isSecure(s)) {
throw new SecurityException();
}
//here will cause problem, if s is changed before this by using other references.
causeProblem(s);
}
5. Immutable objects are naturally thread-safe
Because immutable objects can not be changed, they can be shared among
multiple threads freely. This eliminate the requirements of doing synchronization.
In summary, String is designed to be immutable for the sake of efficiency and
security. This is also the reason why immutable classes are preferred in general.