Previous | Home | Next |
Answer: Java Virtual Machine( JVM) is the heart of Java programming language because Most programming languages compile source code directly into machine code while in java, it uses bytecode - a special type of machine code which is easily executed by CPU, or The Java Virtual Machine ( JVM) provides a platform-independent way of executing code, by abstracting the differences between operating systems and CPU architectures.
Answer: The source code for a Java class is called a compilation unit. A compilation unit normally contains a single class definition and is named for that class. The definition of a class named MySimpledemo, for instance, should appear in a file named Mysimpledemo.java. or a compilation unit must have .java extension, and inside the compilation unit there can be a public class that must have the same name as the main file.
Answer: Identifiers are the names of variables, methods, classes, packages and interfaces. In the simple HelloWorld program, HelloWorld, String, args, main and println() are identifiers. Identifiers must be composed of letters, numbers, the underscore _ and the dollar sign $.
Answer: All Possible Combinations of Features and Modifiers:
Modifier | following modifier can be used in front of | |||||
Class & Nested Class | Method | Variable | Constructor | Package | Free-Floating Block | |
public | Yes | Yes | Yes | Yes | No | No |
protected | No | Yes | Yes | Yes | No | No |
private | No | Yes | Yes | Yes | No | No |
none or package or default | Yes | Yes | Yes | Yes | Yes | Yes |
final | Yes | Yes | Yes | No | No | No |
abstract | Yes | Yes | No | No | No | No |
static | No | Yes | Yes | No | No | Yes |
native | No | Yes | No | No | No | No |
transient | No | No | Yes | No | No | No |
volatile | No | No | Yes | No | No | No |
synchronized | No | Yes | No | No | No | Yes |
strictfp | Yes | Yes | No | Yes | No | No |
Answer: In Java, all variables must first be declared before they can be used. A primitive data type is predefined and reserved keyword by the language. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:
Primitive Data Type | Default Value (for fields) | Summary |
boolean | False | 1-bit. May take on the values true and false only. |
byte | 0 | 8-bit signed two's complement integer and cover range from -128 to 127 (inclusive). |
short | 0 | 16-bit signed two's complement integer and cover a range from -32,768 to 32,767 (inclusive). |
int | 0 | 32-bit signed two's complement integer and cover a range from -2,147,483,648 to 2,147,483,647 (inclusive). |
long | 0L | 64-bit signed two's complement integer and cover a range from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 (inclusive). |
float | 0.of | 4 bytes, IEEE 754(IEEE Standard for Binary Floating-Point Arithmetic) and covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (inclusive). |
double | 0.0d | 8 bytes IEEE 754 and covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d(inclusive). |
char | '\u0000' | 16-bit Unicode character and covers a range from '\u0000' (or 0) to '\uffff' (or 65,535) (inclusive). and *Chars are not the same as bytes, ints, shorts or Strings. |
*String (or any object) | Null | The String class is not technically a primitive data type, but considering the special support given to it by the language. |
Answer: A primitive wrapper class is one of eight classes define in the package java.lang. in java language to provide object methods for the eight primitive types, also all of the wrapper classes are immutable. Wrapper classes are used to represent primitive values than an Object is required and does not contain constructors.
The Wrapper class maintains the following information:
- The wrapper name.
- A WrapperInfo object that contains all of the information that pertains to this wrapper. This information gets stored in subclasses of the Wrapper class.
- The wrapper core library name and returned name of the native library that loaded the wrapper.
The primitive wrapper classes and their corresponding primitive types are:
Primitive data type | Primitive Wrapper class |
boolean | Boolean |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Boolean |
*In the wrapper class all Byte, Short, Integer, Long, Float, and Double are in subclasses of the Number class.
Answer: A static variable and static method is declare as static by using static keyword in front them. A static variable is shared by all the instances of that class i.e only one copy of the static variable is maintained in memory and each static member call by main method.
A static method cannot access non-static/instance variables, because a static method is never associated with any instance of a class.
Answer: In Java, garbage collection( included part of JVM) is a form of automatic memory management. it attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program, or collect those object which lose there reference and identity and no longer in used.
JVM perform automatic garbage collection.
The basic principles of garbage collection are:
- Find data objects in a program that cannot be accessed in the future.
- Reclaim the resources used by those objects.
Answer: A class declared abstract by adding a keyword in front of class, and abstract class have following property like it is incompletely implemented, such a class cannot be instantiated, but can be extended by subclasses.
Answer: A final class which can't be extended, means that a final class can not become a superclass nor have a subclass.
An example final class is written below:
final class Demo { // This class cannot be extended } //A Method provides information about, and access to, //a single method on a class or interface. // Every Java program must have one main() method. //following simple code class { public static void main(String[] args) { System.out.println("Hello World!"); } }
Answer: Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body.
Q.55 What is meant by a resource leak ?
Answer: In an abstract class the method/behavior define in that class is partially or concrete implemented in its subclass while is case of interface, the method/behavior can't be implemented in subclass interface.
Q.57 What is singleton class ?
Answer: Following difference.
- Vector are synchronized means method that belongs to its contents is thread safe while Array is unsynchronized means method is not thread safe.
- Vector is a growable array of objects and dynamic while Vector is a set of related data type and static.
Answer: For initialization of instance variables a constructor must be used and constructor must have same name as class name.
Answer: If the two types are compatible, then Java will perform the conversion automatically, However Typecast Objects with a dynamically loaded Class because object references depends on the relationship of the classes involved in the same hierarchy.
Answer:
final- keyword | finally - block | finalize()- method |
used to declare constants means further no modifications | The finally block always executes when the try block exits and usually used to release all the resources utilized inside the try block. | finalize method is called by the garbage collector on an object when the garbage collector determines that there are no more references to the object and free some resource from that object. |
Answer: Main Package in java is-
java.applet.* java.lang.* java.awt.* java.io.* java.math.* java.security.* java.rmi.* java.beans.* java.net.* java.nio.* java.sql.* java.swing.*
Q.63 What is the difference between java.applet.* and java.applet.Applet ?
Answer: In java, java.applet.* is used as a package to import all the classes while java.applet.Applet is utilize a java class.
Answer: Java classes can be grouped together in packages, and name of package is the same as the directory (folder) name which contains the .java files. So default package is that package which is included automatically when the class is created and contain all the information of the class.
E.g. of default package is java.lang or can create default package self for small program.
Answer: A Java class may be either a superclass, a subclass, both, or neither. but a Java superclass is a class which provide complete access of method or variable to its subclass.
Answer: An anonymous class is a local class without a name and it does not use the keywords class, implements or extends. An anonymous class is defined and instantiated in a single succinct expression using the new operator.
Answer: Interface without any method is called Marker or Null Interface like
- Serializable interface
- Externalizable interface
- Cloneable interface
Answer: To achieve multiple inheritance.
Answer: The Serializable interface defines no members but used to indicate that a class may be serialized. If a class is define to be serializable, then its all subclasses are also serializable.
Answer: To prevent a field from being serialized, mark the field with transient keyword.
Answer: An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error must be checked and handled manually. Exceptions can be generated by the Java run-time system (or java virtual machine, JVM ), or they can be manually generated by your code.
Types Of Exception:
Check Exception or Compiletime Exception. An exception which generate by programming error like user written program or code and must be handle at time of compilation of program.
Uncheck Exception or Runtime Exception. An exception which can generate at the runtime of program, the compiler doesn’t force the programmers to catch the exception.
Answer: By using keyword throws( if more than exception is throw ) or throw( if only one exception is throw).
Answer: Exception is throwing by the utilize the keyword throw (for single exception) and throws (for multiple exception ),both the keyword help in catching exceptions that are thrown by the Java run-time system.
Answer: The finally block is always executed before control leaves the try statement. so the code return inside the finally block always executed.
Answer: Yes, it is possible.
//here the syntax of multiple catch try { // Exception Generated code return here } //First Catch used catch (Exception e) { System.out.println(" First exception caught.", e); } // Second Catch used catch (Exception e) { System.out.println(" Second exception caught.", e); }
Answer: Yes, it is possible .
//here the syntax of multiple try try { try { // Exception generated code return here. } catch (Exception e) { System.out.println("Exception: " + e); } } catch (Exception e) { System.out.println("Exception: " + e); }
Answer: Use equals() method.
Answer: A thread is a program which defines a separate path of execution, the thread is the smallest unit of dispatchable code. This means that a single program can perform two or more tasks simultaneously.
Answer: Multithreading is a specialized form of multitasking. A multithreaded program contains two or more parts that can run concurrently each part of such a program is called a thread, and each thread defines a separate path of execution.
Answer: The two way to create a thread is:
- Implement the Runnable interface (java.lang.Runnable)
- By Extending the Thread class (java.lang.Thread)
Java doesn't support multiple inheritance, that's why implements the Runnable is best way to create a Thread than Extending the Thread class.
Now creating a thread by implementation of Runnable
// following Example is for Create a Thread using Runnable interface package r4r.co.in; class MYThread implements Runnable { Thread t; public MYThread(String threadName) { t = new Thread(this, threadName); // Create a new thread. System.out.println(t.getName()); t.start(); // Start the thread. } public void run() { try { for (int i = 0; i < 5; i++) { System.out.println(t + ": " + i); Thread.sleep(100); } } catch (Exception e) { System.out.println(e); } System.out.println(t + " exiting."); } } public class CreateThreadDemo { public static void main(String[] args) { new MYThread("One"); new MYThread("Two"); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted" + e); } System.out.println("My thread exiting."); } }
One Two Thread[One,5,main]: 0 Thread[Two,5,main]: 0 Thread[One,5,main]: 1 Thread[Two,5,main]: 1 Thread[One,5,main]: 2 Thread[Two,5,main]: 2 Thread[One,5,main]: 3 Thread[Two,5,main]: 3 Thread[One,5,main]: 4 Thread[Two,5,main]: 4 Thread[One,5,main] exiting. Thread[Two,5,main] exiting. My thread exiting.
Now another example is for create Thread by extending the Thread class.
//Consider an Example for Create Thread using Extending the Thread class package r4r.co.in; class MYThread extends Thread { Thread t; public MYThread(String threadName) { t = new Thread(this, threadName); // Create a new thread. System.out.println(t.getName()); t.start(); // Start the thread. } public void run() { try { for (int i = 0; i < 5; i++) { System.out.println(t + ": " + i); Thread.sleep(100); } } catch (Exception e) { System.out.println(e); } System.out.println(t + " exiting."); } } public class CreateThreadDemo { public static void main(String[] args) { new MYThread("One"); new MYThread("Two"); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted" + e); } System.out.println("My thread exiting."); } }
One Two Thread[One,5,main]: 0 Thread[Two,5,main]: 0 Thread[Two,5,main]: 1 Thread[One,5,main]: 1 Thread[Two,5,main]: 2 Thread[One,5,main]: 2 Thread[Two,5,main]: 3 Thread[One,5,main]: 3 Thread[Two,5,main]: 4 Thread[One,5,main]: 4 Thread[Two,5,main] exiting. Thread[One,5,main] exiting. My thread exiting.
Answer: For finding the thread is active or not the method isAlive() from package java.lang.Thread.
Answer: Thread to thread communication means one thread able to sleep, wait, resume even dead to another thread on respected method call.
Q.83 What is the difference between sleep and suspend ?
Answer: Since every thread has there own name and priority for identification purposes. So one thread able to start another thread but not become the member of another thread.
Answer: Dead lock is a typically error condition that occur relates specifically to multitasking is deadlock, which occurs when two threads have a circular dependency on each other and a pair of synchronized objects.
Deadlock generally occur for two reasons:
- In general, it occurs when the two threads time-slice in just the right way.
- It may involve more than two threads and two synchronized objects.
// An example of deadlock. package r4r.co.in; class A { synchronized void call(B y) { String name = Thread.currentThread().getName(); System.out.println(name + " initilization A"); try { Thread.sleep(500); } catch (Exception e) { System.out.println(" Interrupted" + e); } System.out.println(name + " trying to initilization B.last()"); y.last(); } synchronized void last() { } } class B { synchronized void bar(A x) { String name = Thread.currentThread().getName(); System.out.println(name + " initilization B "); try { Thread.sleep(1000); } catch (Exception e) { System.out.println(" Interrupted" + e); } System.out.println(name + " trying to initilization A.last()"); x.last(); } synchronized void last() { } } class Deadlock implements Runnable { A x = new A(); B y = new B(); Deadlock() { Thread.currentThread().setName("MainThread"); Thread t = new Thread(this, "ChildThread"); t.start(); x.call(y); // get lock on a in this thread. } public void run() { y.bar(x); // get lock on b in other thread. } public static void main(String args[]) { new Deadlock(); } }
MainThread initilization A ChildThread initilization B MainThread trying to initilization B.last() ChildThread trying to initilization A.last()
Answer: Avoid a Deadlock/ Prevention of Deadlock.
- When a lock is held than never call any method that need other lock ,i.e.- never call synchronized method of another class from a synchronized method.
- When a synchronized method are going to call doesn't able to call another synchronized method, so at that condition kill that method.
- Whenever a program contain two or more than two thread those consume more resource than try to Implementation of " hold and wait" or " suspend and resume" method.
Example to avid Deadlock condition.
// followig example is for avod deadlock condition package r4r.co.in; class Item { int item; boolean flag = false; public synchronized int getItem() { if (!flag) { try { wait(); } catch (Exception e) { } } System.out.println("getItem() method:" + item); flag = false; notify(); return item; } public synchronized void setItem(int item) { if (flag) { try { wait(); } catch (Exception e) { } } this.item = item; System.out.println("setItem() method:" + item); flag = true; notify(); } } class SynchronizedConsumer extends Thread { Item it; SynchronizedConsumer(Item it) { this.it = it; } public void run() { for (int i = 1; i <= 5; i++) { int item = it.getItem(); } } } class SynchronizedProducer extends Thread { Item it; public SynchronizedProducer(Item it) { this.it = it; } public void run() { for (int i = 1; i <= 5; i++) { it.setItem(i); } } } class SynchronizedMain { public static void main(String args[]) { Item it = new Item(); SynchronizedConsumer cons = new SynchronizedConsumer(it); SynchronizedProducer pros = new SynchronizedProducer(it); cons.start(); pros.start(); } }
setItem() method:1 getItem() method:1 setItem() method:2 getItem() method:2 setItem() method:3 getItem() method:3 setItem() method:4 getItem() method:4 setItem() method:5 getItem() method:5
Previous | Home | Next |