You are on page 1of 17

1.What is the most important feature of Java?

Java is a platform independent language.This is basic core java interview question.

2. What do you mean by platform independence?

Platform independence means that we can write and compile the java code in one platform (eg
Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).This is basic
core java interview questions.

3. What is a JVM?
JVM is an acronym for Java Virtual Machine ,Its is an abstract machine which provides the runtime
environment in which java bytecode can be executed.JVMs(Java Virtual Machine) are available for many
hardware and software platforms(so JVM is platform dependent)

4. Are JVM's platform independent?

JVM's are not platform independent. JVM's are platform specific run time implementation provided by the
vendor.

5. What is the difference between a JDK and a JVM?

JDK is Java Development Kit which is for development purpose and it includes execution environment
also. But JVM is purely a run time environment and hence you will not be able to compile your source files
using a JVM.

6. What is a pointer and does Java support pointers?

Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks
and reliability issues hence Java doesn't support the usage of pointers.

7. What is the base class of all classes?

java.lang.Object

8. Does Java support multiple inheritance?

Java doesn't support multiple inheritance.

9. Is Java a pure object oriented language?

Java uses primitive data types and hence is not a pure object oriented language.

10. Are arrays primitive data types?

In Java, Arrays are objects.

11. What is difference between Path and Classpath?


Path and Classpath are operating system level environment variales. Path is used define where the
system can find the executables(.exe) files and classpath is used to specify the location .class files.

12. What are local variables?

Local varaiables are those which are declared within a block of code like methods. Local variables should
be initialised before accessing them.

13. What are instance variables?

Instance variables are those which are defined at the class level. Instance variables need not be
initialized before using them as they are automatically initialized to their default values.

14. How to define a constant variable in Java?

The variable should be declared as static and final. So only one copy of the variable exists for all
instances of the class and the value can't be changed also. static final int PI = 2.14; is an example for
constant.

15. Should a main() method be compulsorily declared in all java classes?

No not required. main() method should be defined only if the source class is a java application.

16. What is the return type of the main() method?

Main() method doesn't return anything hence declared void.

17. Why is the main() method declared static?

main() method is called by the JVM even before the instantiation of the class hence it is declared as
static.

18. What is the arguement of main() method?

main() method accepts an array of String object as arguement.

19. Can a main() method be overloaded?

Yes. You can have any number of main() methods with different method signature and implementation in
the class.

20. Can a main() method be declared final?

Yes. Any inheriting class will not be able to have it's own default main() method.

21. Does the order of public and static declaration matter in main() method?
No. It doesn't matter but void should always come before main().

22. Can a source file contain more than one class declaration?

Yes a single source file can contain any number of Class declarations but only one of the class can be
declared as public.

23. What is a package?

Package is a collection of related classes and interfaces. package declaration should be first statement in
a java class.

24. Which package is imported by default?

java.lang package is imported by default even without a package declaration.

25. Can a class declared as private be accessed outside it's package?

Not possible.

26. Can a class be declared as protected?

A class can't be declared as protected. only methods can be declared as protected.

27. What is the access scope of a protected method?

A protected method can be accessed by the classes within the same package or by the subclasses of the
class in any package.

28. What is the purpose of declaring a variable as final?

A final variable's value can't be changed. final variables should be initialized before using them.

29. What is the impact of declaring a method as final?

A method declared as final can't be overridden. A sub-class can't have the same method signature with a
different implementation.

30. I don't want my class to be inherited by any other class. What should i do?

You should declared your class as final. But you can't define your class as final, if it is an abstract class. A
class declared as final can't be extended by any other class.

31.Why wait and notify is declared in Object class instead of Thread ?

Another tough java question, how can you answer this question if you are not designed Java
programming language. anyway some common sense and deep knowledge of Java programming helps
to answer such tough core java interview question. See this blog post to learn Why wait and notify is
declared in Object class and not in Thread.

32.Why multiple inheritance is not supported in Java ?

I found this core Java question really tough to answer because your answer may not satisfy Interviewer, in
most cases Interviewer is looking for specific points and if you can bring them, they would be happy. Key
to answer this kind of tough question in Java is to prepare topic well to accommodate any follow-ups.

33.Why Java does not support operator overloading ?

One more similar category of tough Java question. C++ supports operator overloading than why not
Java? this is the argument Interviewer will give to you and some time even say that + operator is
overloaded in Java for String concatenation, Don't be fooled with such arguments.

34.Why String is immutable in Java?

My favorite Java interview question, this is tough, tricky but same time very useful as well. Some
interviewer also ask this question as Why String is final in Java. look at this post for some points which
make sense on Why String is final or immutable in Java

35.Why char array is preferred to store password than String in Java?

Another tricky Java question which is based on String and believe me there are only few Java
programmer which can answer this question correctly. This is a real tough core Java interview question
and again solid knowledge of String is required to answer this.

36.How to create thread-safe singleton in Java using double checked locking?

This Java question is also asked as What is thread-safe singleton and how to do you write it. Well
Singleton created with double checked locking before Java 5 was broker and its possible to have multiple
instance of Singleton if multiple thread try to create instance of Singleton at same time. from Java 5 its
easy to create thread safe Singleton using Enum. but if interviewer persist with double checked locking
then you have to write that code for them. remember to use volatile variable. See 10 Java singleton
interview question for more details on this topic.

37.Write Java program to create deadlock in Java and fix it ?

One of the classical but tough core Java interview question and you are likely to fail if you have not
involved in coding of multi-threaded concurrent Java application.

38.What happens if your Serializable class contains a member which is not serializable? How do you fix
it?

Any attempt to Serialize that class will fail with NotSerializableException, but this can be easily solved by
making that variable transient for static in Java. See Top 10 Serialization interview question answers in
Java for more details.
39.Why wait and notify called from synchronized method in Java?

Another tough core Java question for wait and notify. They are called from synchronized method or
synchronized blockbecause wait and modify need monitor on Object on which wait or notify get called.

40.Can you override static method in Java?

if I create same method in subclass is it compile time error? No you can not override static method in
Java but its not a compile time error to declare exactly same method in sub class, That is called method
hiding in Java.

41. How could Java classes direct program messages to the system console, but error messages, say to
a file?

The class System has a variable out that represents the standard output, and the variable err that
represents the standard error device. By default, they both point at the system console. This how the
standard output could be re-directed: Stream st = new Stream (new FileOutputStream
(techinterviews_com.txt)); System.setErr(st); System.setOut(st);

42. Whats the difference between an interface and an abstract class?

An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract
classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other
hand, you can implement multiple interfaces in your class.

43. Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.

44. Explain the usage of the keyword transient?

This keyword indicates that the value of this member variable does not have to be serialized with the
object. When the class will be de-serialized, this variable will be initialized with a default value of its data
type (i.e. zero for integers).

45. How can you force garbage collection?

You cant force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be
started immediately.

46. How do you know if an explicit object casting is needed?

If you assign a superclass object to a variable of a subclasss data type, you need to do explicit casting.
For example: Object a;Customer b; b = (Customer) a; When you assign a subclass to a variable having a
supeclass type, the casting is performed automatically.

47. Whats the difference between the methods sleep() and wait()?

The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of
up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The
method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

48. Can you write a Java class that could be used both as an applet as well as an application?

Yes. Add a main() method to the applet.

49. Whats the difference between constructors and other methods?

Constructors must have the same name as the class and can not return a value. They are only called
once while regular methods could be called many times.

50. Can you call one constructor from another if a class has multiple constructors?

Yes. Use this() syntax.

51. Explain the usage of Java packages?

This is a way to organize files when a project consists of multiple modules. It also helps resolve naming
conflicts when different packages have classes with the same names. Packages access level also allows
you to protect data from being used by the non-authorized classes.

52. If a class is located in a package, what do you need to change in the OS environment to be able to
use it?

You need to add a directory or a jar file that contains the package directories to the CLASSPATH
environment variable. Lets say a class Employee belongs to a package com.xyz.hr; and is located in the
file c:/dev/com.xyz.hr.Employee.java. In this case, youd need to add c:/dev to the variable CLASSPATH.
If this class contains the method main(), you could test it from a command prompt window as follows:
c:>java com.xyz.hr.Employee.

53. Whats the difference between J2SDK 1.5 and J2SDK 5.0?

Theres no difference, Sun Microsystems just re-branded this version.

54. What would you use to compare two String variables the operator == or the method equals()?

Id use the method equals() to compare the values of the Strings and the = = to check if two variables
point at the same instance of a String object

55. Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are
written?

Yes, it does. The FileNoFoundException is inherited from the IOException. Exceptions subclasses have
to be caught first.

56. Can an inner class declared inside of a method access local variables of this method?

Its possible if these variables are final.


57. What can go wrong if you replace && with & in the following code:
String a=null; if (a!=null && a.length()>10) {} A single ampersand here would lead to a
NullPointerException.

58. Whats the main difference between a Vector and an ArrayList?

Java Vector class is internally synchronized and ArrayList is not.

59. When should the method invokeLater()be used?

This method is used to ensure that Swing components are updated through the event-dispatching thread.

60. How can a subclass call a method or a constructor defined in a superclass?

Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in
the first line of the subclasss constructor.

61. Whats the difference between a queue and a stack?

Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule.

62. You can create an abstract class that contains only abstract methods. On the other hand, you can
create an interface that declares the same methods. So can you use abstract classes instead of
interfaces?

Sometimes. But your class may be a descendant of another class and in this case the interface is your
only option.

63. What comes to mind when you hear about a young generation in Java?

Garbage collection.

64. What comes to mind when someone mentions a shallow copy in Java?

Object cloning.

65. If youre overriding the method equals() of an object, which other method you might also consider?

hashCode()

66. You are planning to do an indexed search in a list of objects. Which of the two Java collections should
you use: ArrayList or LinkedList?

ArrayList

67. How would you make a copy of an entire Java object with its state?

Have this class implement Cloneable interface and call its method clone().
68. How can you minimize the need of garbage collection and make the memory use more effective?

Use object pooling and weak object references.

69. There are two classes: A and B. The class B need to inform a class A when some important event has
happened. What Java technique would you use to implement it?

If these classes are threads Id consider notify() or notifyAll(). For regular classes you can use the
Observer interface.

70. What access level do you need to specify in the class declaration to ensure that only classes from the
same directory can access it?

You do not need to specify any access level, and Java will use a default package access level.

What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
This is a very popular tricky Java question and its tricky because many programmer think that finally block always
executed. This question challenge that concept by putting return statement in try or catch block or
calling System.exit from try or catch block. Answer of this tricky question in Java is that finally block will
execute even if you put return statement in try block or catch block but finally block won't run if you
call System.exit form try or catch.

Can you override private or static method in Java ?


Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in
Java. Anyway, you can not override private or static method in Java, if you create similar method with same return
type and same method arguments that's called method hiding. See Can you override private method in Java or more
details.

Does Java support multiple inheritance ?


This is the trickiest question in Java, if C++ can support direct multiple inheritance than why not Java is the argument
Interviewer often give. See Why multiple inheritance is not supported in Java to answer this tricky Java question.

What will happen if we put a key object in a HashMap which is already there ?
This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing
and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap
doesn't allow duplicate keys. See How HashMap works in Java for more tricky Java questions from HashMap.

If a method throws NullPointerException in super class, can we override it with a method which throws
RuntimeException?
One more tricky Java questions from overloading and overriding concept. Answer is you can very well throw super
class of RuntimeException in overridden method but you can not do same if its checked Exception. See Rules of
method overriding in Javafor more details.

What is the issue with following implementation of compareTo() method in Java


public int compareTo(Object o){
Employee emp = (Employee) emp;
return this.id - o.id;
}

where id is an integer number ?


Well three is nothing wrong in this Java question until you guarantee that id is always positive. This Java question
becomes tricky when you can not guaranteed id is positive or negative. If id is negative than subtraction may
overflow and produce incorrect result. See How to override compareTo method in Java for complete answer of this
Java tricky question for experienced programmer.

How do you ensure that N thread can access N resources without deadlock
If you are not well versed in writing multi-threading code then this is real tricky question for you. This Java question
can be tricky even for experienced and senior programmer, who are not really exposed to deadlock and race
conditions. Key point here is order, if you acquire resources in a particular order and release resources in reverse
order you can prevent deadlock. See how to avoid deadlock in Java for a sample code example.

What is difference between CyclicBarrier and CountDownLatch in Java


Relatively newer Java tricky question, only been introduced form Java 5. Main difference between both of them is that
you can reuseCyclicBarrier even if Barrier is broken but you can not reuse CountDownLatch in Java.
See CyclicBarrier vs CountDownLatch in Java for more differences.

What is difference between StringBuffer and StringBuilder in Java ?


Classic Java questions which some people thing tricky and some consider very easy. StringBuilder in Java is
introduced in Java 5 and only difference between both of them is that
Stringbuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs
StringBuffer for more differences

1) You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
This thread interview questions is mostly asked in first round or phone screening round of interview and purpose of
this multi-threading question is to check whether candidate is familiar with concept of "join" method or not. Answer of
this multi-threading questions is simple it can be achieved by using join method of Thread class.

2) What is the advantage of new Lock interface over synchronized block in Java? You need to implement a
high performance cache which allows multiple reader but single writer to keep the integrity how will you
implement it?
The major advantage of lock interfaces on multi-threaded and concurrent programming is they provide two separate
lock for reading and writing which enables you to write high performance data structure
like ConcurrentHashMap and conditional blocking. This java threads interview question is getting increasingly popular
and more and more follow-up questions come based upon answer of interviewee. I would strongly suggest
reading Locks before appearing for any java multi-threading interview because now days Its heavily used to build
cache for electronic trading system on client and exchange connectivity space.

3) What are differences between wait and sleep method in java?


Another frequently asked thread interview question in Java mostly appear in phone interview. Only major difference is
wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-
thread communication while sleep is used to introduce pause on execution. See my post wait vs sleep in Java for
more differences

4) Write code to implement blocking queue in Java?


This is relatively tough java multi-threading interview question which servers many purpose, it checks
whether candidate can actually write Java code using thread or not, it sees how good candidate is on understanding
concurrent scenarios and you can ask lot of follow-up question based upon his code. If he
uses wait() and notify() method to implement blocking queue, Once interviewee successfully writes it you can
ask him to write it again using new java 5 concurrent classes etc.

5) Write code to solve the Produce consumer problem in Java?


Similar to above questions on thread but more classic in nature, some time interviewer ask follow up questions How
do you solve producer consumer problem in Java, well it can be solved in multiple way, I have shared one way to
solve producer consumer problem using BlockingQueue in Java , so be prepare for surprises. Some time they even
ask to implement solution of dining philosopher problem as well.

6) Write a program which will result in deadlock? How will you fix deadlock in Java?
This is my favorite java thread interview question because even though deadlock is quite common while

writing multi-threaded concurrent program many candidates not able to write deadlock free code and they simply
struggle. Just ask them you have n resources and n thread and to complete an operation you require all resources.
Here n can be replace with 2 for simplest case and higher number to make question more intimidating. see How to
avoid deadlock in java for more information on deadlock in Java.

7) What is atomic operation? What are atomic operations in Java?


Simple java thread interview questions, another follow-up is do you need to synchronized an atomic operation? :) You
can read more about java synchronization here.

8) What is volatile keyword in Java? How to use it? How is it different from synchronized method in Java?
Thread questions based on volatile keyword in Java has become more popular after changes made on it on Java 5
and Java memory model. Its good to prepare well about how volatile variables ensures visibility, ordering and
consistency in concurrent environment.

9) What is race condition? How will you find and solve race condition?
Another multi-threading question in Java which appear mostly on senior level interviews. Most interviewer grill on
recent race condition you have faced and how did you solve it and some time they will write sample code and ask you
detect race condition. See my post on Race condition in Java for more information. In my opinion this is one of the
best java thread interview question and can really test the candidate's experience on solving race condition or writing
code which is free of data race or any other race condition. Best book to get mastery of this topic is "Concurrency
practices in Java'".

10) How will you take thread dump in Java? How will you analyze Thread dump?
In UNIX you can use kill -3 and then thread dump will print on log on windows you can use "CTRL+Break". Rather
simple and focus thread interview question but can get tricky if he ask how you analyze it. Thread dump can be useful
to analyze deadlock situations as well.

11) Why we call start() method which in turns calls run() method, why not we directly
call run() method ?
Another classic java multi-threading interview question This was my original doubt when I started programming in
thread. Now days mostly asked in phone interview or first round of interview at mid and junior level java interviews.
Answer to this question is that, when you call start() method it creates new Thread and execute code declared
in run() while directly calling run() method doesnt create any new thread and execute code on same calling
thread. Read my post Difference between start and run method in Thread for more details.

12) How will you awake a blocked thread in java?


This is tricky question on threading, blocking can result on many ways, if thread is blocked on IO then I don't think
there is a way to interrupt the thread, let me know if there is any, on the other hand if thread is blocked due to result of
calling wait(), sleep() or join() method you can interrupt the thread and it will awake by
throwing InterruptedException. See my post How to deal with blocking methods in Java for more information on
handling blocked thread.

Question #12:-Is there is any way to create instance of Java Object with out using new operator? You can use
Class.forName to create instance of object.

Class.forName("Your Class Name").newInstance();

Q. Can you write an algorithm to swap two variables?


A.

?
1
2 package algorithms;
3
public class Swap {
4
5
public static void main(String[ ] args) {
6 int x = 5;
7 int y = 6;
8
9 //store 'x' in a temp variable
10 int temp = x;
x = y;
11
y = temp;
12
13 System.out.println("x=" + x + ",y=" + y);
14 }
15 }
16

Q. Can you write code to bubble sort { 30, 12, 18, 0, -5, 72, 424 }?
A.

?
1 package algorithms;
import java.util.Arrays;
2
3 public class BubbleSort {
4
5
6
7
public static void main(String[ ] args) {
8 Integer[ ] values = { 30, 12, 18, 0, -5, 72, 424 };
9 int size = values.length;
10 System.out.println("Before:" + Arrays.deepToString(values));
11
12 for (int pass = 0; pass < size - 1; pass++) {
for (int i = 0; i < size - pass - 1; i++) {
13 // swap if i > i+1
14 if (values[i] > values[i + 1])
15 swap(values, i, i + 1);
16 }
17 }
18
System.out.println("After:" + Arrays.deepToString(values));
19 }
20
21 private static void swap(Integer[ ] array, int i, int j) {
22 int temp = array[i];
23 array[i] = array[j];
array[j] = temp;
24
}
25 }
26
27

Q. Is there a more efficient sorting algorithm?


A. Although bubble-sort is one of the simplest sorting algorithms, it's also one of the slowest. It has
the O(n^2) time complexity. Faster algorithms include quick-sort and heap-sort. The Arrays.sort( )
method uses the quick-sort algorithm, which on average has O(n * log n) but can go up to O(n^2) in
a worst case scenario, and this happens especially with already sorted sequences.

Q. Write a program that will return whichever value is nearest to the value of 100 from two given int
numbers?
A. You can firstly write the pseudo code as follows:

Compute the difference to 100.


Find out the absolute difference as negative numbers are valid.
Compare the differences to find out the nearest number to 100.
Write test cases for +ve, -ve, equal to, > than and < than values.
?
1 package chapter2.com;
2
3
4
public class CloseTo100 {
5
6
7
8
9
10
public static int calculate(int input1, int input2) {
11
12 //compute the difference. Negative values are allowed as well
13
14 int iput1Diff = Math.abs(100 - input1);
15
16 int iput2Diff = Math.abs(100 - input2);
17
18
19
20 //compare the difference
21
22 if (iput1Diff < iput2Diff) return input1;
else if (iput2Diff < iput1Diff) return input2;
23 else return input1; //if tie, just return one
24 }
25
26 public static void main(String[ ] args) {
27 //+ve numbers
28 System.out.println("+ve numbers=" + calculate(50,90));
29
//-ve numbers
30 System.out.println("-ve numbers=" + calculate(-50,-90));
31
32 //equal numbers
33 System.out.println("equal numbers=" + calculate(50,50));
34
35 //greater than 100
36 System.out.println(">100 numbers=" + calculate(85,105));
37
System.out.println("<100 numbers=" + calculate(95,110));
38 }
39 }
40
41

Output:

+ve numbers=90
-ve numbers=-50
equal numbers=50
>100 numbers=105
<100 numbers=95

Q. Can you write a method that reverses a given String?


A.
?
1 public class ReverseString {
2
3
4
5
6 public static void main(String[ ] args) {
7
System.out.println(reverse("big brown fox"));
8
9 System.out.println(reverse(""));
10
11 }
12
13
14
15 public static String reverse(String input) {
16
17 if(input == null || input.length( ) == 0){
18
19 return input;
20
}
21
22
23
24 return new StringBuilder(input).reverse( ).toString( );
25
26 }
27
28 }
29

It is always a best practice to reuse the API methods as shown above with the
StringBuilder(input).reverse( ) method as it is fast, efficient (uses bitwise operations) and knows how
to handle Unicode surrogate pairs, which most other solutions ignore. The above code handles null
and empty strings, and a StringBuilder is used as opposed to a thread-safe StringBuffer, as the
StringBuilder is locally defined, and local variables are implicitly thread-safe.

Some interviewers might probe you to write other lesser elegant code using either recursion or
iterative swapping. Some developers find it very difficult to handle recursion, especially to work out
the termination condition. All recursive methods need to have a condition to terminate the recursion.

?
1 public class ReverseString2 {
2
3 public String reverse(String str) {
// exit or termination condition
4 if ((null == str) || (str.length( ) <= 1)) {
5 return str;
6 }
7
8
9 // put the first character (i.e. charAt(0)) to the end. String indices are 0
// and recurse with 2nd character (i.e. substring(1)) onwards
10 return reverse(str.substring(1)) + str.charAt(0);
11 }
12 }
13
There are other solutions like
?
1
2 public class ReverseString3 {
3
4 public String reverse(String str) {
5 // validate
6 if ((null == str) || (str.length( ) <= 1)) {
return str;
7 }
8
9 char[ ] chars = str.toCharArray( );
10 int rhsIdx = chars.length - 1;
11
12 //iteratively swap until exit condition lhsIdx < rhsIdx is reached
13 for (int lhsIdx = 0; lhsIdx < rhsIdx; lhsIdx++) {
char temp = chars[lhsIdx];
14 chars[lhsIdx] = chars[rhsIdx];
15 chars[rhsIdx--] = temp;
16 }
17
18 return new String(chars);
19 }
}
20
21

Or
?
1 public class ReverseString4 {
2
3 public String reverse(String str) {
// validate
4 if ((null == str) || (str.length( ) <= 1)) {
5 return str;
6 }
7
8
9 char[ ] chars = str.toCharArray( );
int length = chars.length;
10
int last = length - 1;
11
12 //iteratively swap until reached the middle
13 for (int i = 0; i < length/2; i++) {
14 char temp = chars[i];
15
16
chars[i] = chars[last - i];
17
chars[last - i] = temp;
18 }
19
20 return new String(chars);
21 }
22
23
24 public static void main(String[] args) {
25 String result = new ReverseString4().reverse("Madam, I'm Adam");
System.out.println(result);
26 }
27 }
28
29

12.Why would you use a synchronized block vs. synchronized method?


Synchronized blocks place locks for shorter periods than synchronized methods.
13.Can an inner class declared inside of a method access local
variables of this method?
Its possible if these variables are final.
14.Explain the user defined Exceptions?
User defined Exceptions are the separate Exception classes defined by the user for specific
purposed. An user defined can created by simply sub-classing it to the Exception class. This
allows custom exceptions to be generated (using throw) and caught in the same way as
normal exceptions.
Example:
class myCustomException extends Exception {
/ The class simply has to exist to be an exception
}

(Q) What is the difference between wait() and sleep() in Java?


(A) wait() method takes integer value (time) to make the process wait. While sleep() is used
to pause the execution.

(Q) What is the difference between Thread.start() method and


Thread.run() method?
(A) Thread.strat() method is used to run the Thread.run() method in a thread. run() method
is used to start the thread.

You might also like