Download How are this() and super() used with constructors?

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1. What is similarities between interface and class?
a. They are both java basic object types
b. They both can contain variables and methods (With difference being class methods have
implementation code whereas the interface methods can only have declarations)
c. They can both be inherited using Inheritance (extends keyword for classes and implements
keyword for interfaces)
2. What are different types of inner classes? Nested -level classes, Member classes, Local classes,
Anonymous classes. Explain them
There are 4 types of inner classes - Member inner class, Local inner class, Static inner class and
Anonymous inner class
1. Member inner class – A member of a class(enclosing class).
2. Local inner class – An inner class that is defined within a block.
3. Static inner class – Like static members, this class itself is static.
4. Anonymous inner class – A class without a name and implements exactly only one interface or
exactly extends one abstract class.
3. What are Seperators?
Separators help define the structure of a program.
The separators used in java program are parentheses, ( ), braces, { }, the period, .,
and the semicolon,
Separators help define the structure of a program.
The separators used in java program are parentheses, ( ), braces, { }, the
period, ., and the semicolon,
()
Encloses arguments in method definitions and calling;
{}
defines blocks of code and automatically initializes arrays
[]
declares array types and dereferences array values
;
terminates statements
,
separates successive identifiers in variable declarations
.
Selects a field or method from an object; separates package names from subpackage and class names
:
Used after loop labels
4. Define JVM,JDK,JRE
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides
runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent.
The JVM performs following main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime
environment.It is the implementation of JVM.It physically exists.It contains set of
libraries + other files that JVM uses at runtime.
Implementation of JVMs are also actively released by other companies besides Sun Micro
Systems.
JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
5. How are this() and super() used with constructors?
this() constructor is invoked within a method of a class, if the execution of the constructor is to be done before the
functionality of that method.
Example
void getValue()
{
this();
…
}
super() constructor is used within the constructor of the sub class, as the very first statement. This process is used
when the super class constructor is to be invoked first, when the sub class object is instantiated everytime.
Example
class SubClass
{
SubClass()
{
super();
…..
}
}
6. What is the difference between Thread.start() & Thread.run() method?
Thread.start() method (native method) of Thread class actually does the job of running the
Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same
thread, so does not solve the purpose of creating a new thread.
7. Why do we need run() & start() method both. Can we achieve it with only run method?
We need run() & start() method both because JVM needs to create a separate thread which can
not be differentiated from a normal method call. So this job is done by start method native
implementation which has to be explicitly called. Another advantage of having these two
methods is we can have any object run as a thread if it implements Runnable interface. This is to
avoid Java’s multiple inheritance problems which will make it difficult to inherit another class
with Thread.
8. What is Deadlock?
Deadlock is a situation where two or more threads are blocked forever, waiting for each other.
This may occur when two threads, each having a lock on one resource, attempt to acquire a lock
on the other's resource. Each thread would wait indefinitely for the other to release the lock,
unless one of the user processes is terminated. In terms of Java API, thread deadlock can occur
in following conditions:
When two threads call Thread.join() on each other.
When two threads use nested synchronized blocks to lock two objects and the blocks lock the
same objects in different order.
9. What are checked and unchecked exception?
1) Checked: are the exceptions that are checked at compile time. If some code within a method
throws a checked exception, then the method must either handle the exception or it must
specify the exception using throws keyword.
For example, consider the following Java program that opens file at locatiobn “C:\test\a.txt” and
prints first three lines of it. The program doesn’t compile, because the function main() uses
FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses
readLine() and close() methods, and these methods also throw checked exception IOException
import java.io.*;
class Main {
public static void main(String[] args) {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
// Print first 3 lines of file "C:\test\a.txt"
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Output:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code unreported exception java.io.FileNotFoundException; must be caught or declared to be
thrown
at Main.main(Main.java:5)
To fix the above program, we either need to specify list of exceptions using throws, or we need
to use try-catch block. We have used throws in the below program. Since
FileNotFoundException is a subclass of IOException, we can just specify IOException in the
throws list and make the above program compiler-error-free.
import java.io.*;
class Main {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);
// Print first 3 lines of file "C:\test\a.txt"
for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Output: First three lines of file “C:\test\a.txt”
2) Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions
are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is
up to the programmers to be civilized, and specify or catch the exceptions.
In Java exceptions under Error and RuntimeException classes are unchecked exceptions,
everything else under throwable is checked.
+-----------+
| Throwable |
+-----------+
/
\
/
\
+-------+
+-----------+
| Error |
| Exception |
+-------+
+-----------+
/ | \
\________/
/|
\
\______/
\
+------------------+
unchecked
checked
| RuntimeException |
+------------------+
/ | |
\
\_________________/
unchecked
Consider the following Java program. It compiles fine, but it throws ArithmeticException when
run. The compiler allows it to compile, because ArithmeticException is an unchecked exception.
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
Java Result: 1
10. Program to show deadlock
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
Deadlock occurs when multiple threads need the same locks but obtain them in different order. A Java
multithreaded program may suffer from the deadlock condition because the synchronized keyword causes
the executing thread to block while waiting for the lock, or monitor, associated with the specified object. Here
is an example:
Example:
11. public class TestThread {
12.
public static Object Lock1 = new Object();
13.
public static Object Lock2 = new Object();
14.
15.
public static void main(String args[]) {
16.
17.
ThreadDemo1 T1 = new ThreadDemo1();
18.
ThreadDemo2 T2 = new ThreadDemo2();
19.
T1.start();
20.
T2.start();
21.
}
22.
23.
private static class ThreadDemo1 extends Thread {
24.
public void run() {
25.
synchronized (Lock1) {
26.
System.out.println("Thread 1: Holding lock 1...");
27.
try { Thread.sleep(10); }
28.
catch (InterruptedException e) {}
29.
System.out.println("Thread 1: Waiting for lock 2...");
30.
synchronized (Lock2) {
31.
System.out.println("Thread 1: Holding lock 1 & 2...");
32.
}
33.
}
34.
}
35.
}
36.
private static class ThreadDemo2 extends Thread {
37.
public void run() {
38.
synchronized (Lock2) {
39.
System.out.println("Thread 2: Holding lock 2...");
40.
try { Thread.sleep(10); }
41.
catch (InterruptedException e) {}
42.
System.out.println("Thread 2: Waiting for lock 1...");
43.
synchronized (Lock1) {
44.
System.out.println("Thread 2: Holding lock 1 & 2...");
45.
}
46.
}
47.
}
48.
}
49. }
50. When you compile and execute above program, you find a deadlock situation and below is the output
produced by the program:
51. Thread
52. Thread
53. Thread
54. Thread
1:
2:
1:
2:
Holding
Holding
Waiting
Waiting
lock 1...
lock 2...
for lock 2...
for lock 1...
Or
One of the main problems with threading is Deadlock, two threads are both suspended waiting
for the other one to do something. The most common cause of deadlock is two threads both
acquiring the same set of (two or more) locks, but in a different order. Consider this code:
Object A = new Object();
Object B = new Object();
Thread 1:
synchronized(A)
{
// <--- preemption
synchronized(B)
{ //...
}
}
Thread 2:
synchronized(B)
{ synchronized(A)
{ //...
}
}
Here's the deadlock scenario:
Thread 1 acquires A, but is then preempted for some reason.
Thread 2 wakes up, acquires B, but can't get A because Thread 1 has it, so is suspended.
Thread 1 wakes up, tries to acquire B, but can't because Thread 2 has it, so is suspended.
Both threads are now suspended forever. They're deadlocked.