Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

Java and Spring Boot Interview Prep

The document contains a comprehensive list of questions categorized by various Java topics, including Core Java, OOP, Exception Handling, String, Nested Classes, Garbage Collection, I/O, Serialization, Multithreading, Concurrency, and Collection Framework. Each category features multiple questions that cover fundamental concepts, differences, and functionalities within Java programming. The document serves as a study guide or reference for Java programming concepts and practices.

Uploaded by

tejas kumbhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java and Spring Boot Interview Prep

The document contains a comprehensive list of questions categorized by various Java topics, including Core Java, OOP, Exception Handling, String, Nested Classes, Garbage Collection, I/O, Serialization, Multithreading, Concurrency, and Collection Framework. Each category features multiple questions that cover fundamental concepts, differences, and functionalities within Java programming. The document serves as a study guide or reference for Java programming concepts and practices.

Uploaded by

tejas kumbhar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as XLSX, PDF, TXT or read online on Scribd
You are on page 1/ 78

No.

Question Type

1 Core java

2 Core java

3 Core java

4 Core java

5 Core java

6 Core java

7 Core java

8 Core java
9 Core java
10 Core java
11 Core java
12 Core java

13 Core java
14 Core java
15 Core java

16 Core java

17 Core java

18 Core java

19 Core java

20 Core java
21 Core java

22 OOPS

23 OOPS

24 OOPS

25 OOPS

26 OOPS

27 OOPS
28 OOPS
29 OOPS
30 OOPS
31 OOPS

32 OOPS
33 OOPS

34 OOPS

35 OOPS

36 OOPS

37 OOPS

38 OOPS

39 OOPS
40 OOPS
41 OOPS
42 OOPS

43 OOPS
44 OOPS
45 OOPS
46 OOPS
47 OOPS
48 OOPS
49 OOPS

50 OOPS

51 OOPS
52 OOPS
53 OOPS

54 OOPS

55 OOPS
56 OOPS
57 OOPS
58 OOPS
59 OOPS

60 OOPS

61 OOPS
62 OOPS
63 OOPS
64 OOPS
65 OOPS
66 OOPS

67 OOPS
68 OOPS
69 OOPS
70 OOPS
71 OOPS
72 OOPS
73 OOPS
74 OOPS
75 OOPS
76 OOPS

77 OOPS

78 OOPS

79 OOPS

80 OOPS

81 OOPS
82 OOPS
83 OOPS
84 OOPS

85 OOPS
86 OOPS

87 OOPS
88 OOPS

89 OOPS

90 OOPS

91 OOPS

92 OOPS
93 OOPS

94 OOPS
95 OOPS

96 Exception Handling
97 Exception Handling
98 Exception Handling
99 Exception Handling
100 Exception Handling
101 Exception Handling

102 Exception Handling


103 Exception Handling

104 Exception Handling

105 String

106 String

107 String

108 String

109 String
110 String
111 String

112 String

113 String

114 String

115 String

116 Nested classes and Interfaces

117 Nested classes and Interfaces

118 Nested classes and Interfaces

119 Nested classes and Interfaces


120 Nested classes and Interfaces
121 Nested classes and Interfaces
122 Nested classes and Interfaces

123 Garbage Collection

124 Garbage Collection

125 Garbage Collection

126 Garbage Collection


127 Garbage Collection
128 Garbage Collection
129 Garbage Collection

130 Garbage Collection

131 Garbage Collection

132 I/O

133 I/O

134 I/O

135 I/O
136 I/O

137 I/O
138 I/O

139 I/O
140 I/O

141 I/O

142 Serialization
143 Serialization

144 Serialization
145 Serialization
146 Serialization

147 Serialization

148 Serialization

149 Miscellaneous

150 Miscellaneous

151 Miscellaneous
152 Miscellaneous

153 Miscellaneous

154 Miscellaneous
155 RMI

156 Multithreading

157 Multithreading

158 Multithreading

159 Multithreading

160 Multithreading

161 Multithreading

162 Multithreading

163 Multithreading

164 Multithreading

165 Multithreading

166 Multithreading
167 Multithreading

168 Multithreading

169 Multithreading
170 Multithreading

171 Multithreading

172 Multithreading
173 Multithreading

174 Multithreading
175 Multithreading

176 Multithreading
177 Multithreading

178 Multithreading

179 Multithreading

180 Multithreading

181 Multithreading
182 Multithreading
183 Multithreading

184 Multithreading
185 Multithreading

186 Multithreading

187 Multithreading

188 Concurrency

189 Concurrency
190 Concurrency

191 Concurrency

192 Concurrency

193 Concurrency

194 Concurrency

195 Concurrency

196 Concurrency

197 Concurrency
198 Concurrency

199 Collection

200 Collection

201 Collection

202 Collection

203 Collection

204 Collection

205 Collection

206 Collection

207 Collection

208 Collection

209 Collection

210 Collection
211 Collection

212 Collection

213 Collection

214 Collection

215 Collection

216 Collection

217 Collection

218 Collection

219 Collection
220 Collection
221 Collection
222 Collection

223 Collection

224 Collection
225 Collection

226 Collection
227 Collection

228 Collection

229 Collection

230 Collection
231 Collection

232 Collection
Question

What is Java?

What are the differences between C++ and Java?

List the features of Java Programming language.

What do you understand by Java virtual machine?

What is the difference between JDK, JRE, and JVM?

How many types of memory areas are allocated by JVM?

What is JIT compiler?

What is the platform?


What gives Java its 'write once and run anywhere' nature?
What is classloader
Is Empty .java file name a valid source file name?
Is delete, next, main, exit or null keyword in java?
If I don't provide any arguments on the command line, then what will the
value stored in the String array passed into the main() method, empty or
NULL?
What if I write static public void instead of public static void?
What is the default value of the local variables?

What are the various access specifiers in Java?

What is the purpose of static methods and variables?

What are the advantages of Packages in Java?

What is the output of the following Java program?

class Test
{
public static void main (String args[])
{
System.out.println(10 + 20 + "Javatpoint");
System.out.println("Javatpoint" + 10 + 20);
}
}

What is the output of the following Java program?

class Test
{
public static void main (String args[])
{
System.out.println(10 * 20 + "Javatpoint");
System.out.println("Javatpoint" + 10 * 20);
}
}
What is the output of the following Java program?

class Test
{
public static void main (String args[])
{
for(int i=0; 0; i++)
{
System.out.println("Hello Javatpoint");
}
}
}

What is object-oriented paradigm

What is an object?

What is the difference between an object-oriented programming language


and object-based programming language?
What will be the initial value of an object reference which is defined as an
instance variable?

What is the constructor?

How many types of constructors are used in Java?


Does constructor return any value?
Is constructor inherited?
Can you make a constructor final?
Can we overload the constructors?

What do you understand by copy constructor in Java?


What are the differences between the constructors and methods?

What is the output of the following Java program?

class Test
{
int i;
}
public class Main
{
public static void main (String args[])
{
Test test = new Test();
System.out.println(test.i);
}
}

What is the output of the following Java program?

class Test
{
int test_a, test_b;
Test(int a, int b)
{
test_a = a;
test_b = b;
}
public static void main (String args[])
{
Test test = new Test();
System.out.println(test.test_a+" "+test.test_b);
}
}

What is the static variable?

What is the static method?

What are the restrictions that are applied to the Java static methods?

Why is the main method static?


Can we override the static methods?
What is the static block?
Can we execute a program without main() method?
What if the static modifier is removed from the signature of the main
method?
Can we make constructors static?
Can we make the abstract methods static in Java?
Can we declare the static variables and methods in an abstract class?
What is this keyword in java?
Can we assign the reference to this variable?
Can this keyword be used to refer static members?
What are the advantages of passing this into a method instead of the
current class object itself?

What is the Inheritance?


Which class is the superclass for all the classes?
Why is multiple inheritance not supported in java?

What is aggregation?

What is composition?
What is the difference between aggregation and composition?
Why does Java not support pointers?
What is super in java?
Can you use this() and super() both in a constructor?

What is object cloning?

What is method overloading?


Why is method overloading not possible by changing the return type in java?
Can we overload the methods by making them static?
Can we overload the main() method?
What is method overloading with type promotion?
What is the output of the following Java program

class OverloadingCalculation3{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}

public static void main(String args[]){


OverloadingCalculation3 obj=new OverloadingCalculation3();
obj.sum(20,20);//now ambiguity
}
}

What is method overriding:


Can we override the overloaded method?
Can we override the private methods?
Can we change the scope of the overridden method in the subclass?
Can you have virtual functions in Java?
What is covariant return type?
What is the final keyword?
Can you declare the main method as final?
Can we declare a constructor as final?
Can we declare an interface as final?

What is the difference between compile-time polymorphism and runtime


polymorphism?

What is Java instanceOf operator?

What is the abstraction?

What is the difference between abstraction and encapsulation?

What is the abstract class?


Can there be an abstract method without an abstract class?
Can you use abstract and final both with a method?
Is it possible to instantiate the abstract class?

What is the interface?


What is a marker interface?
Can we define private and protected modifiers for the members in
interfaces?
When can an object reference be cast to an interface reference?

How to make a read-only class in Java?

How to make a write-only class in Java?

What are the advantages of Encapsulation in Java?

What is the package?


Do I need to import java.lang package any time? Why?
Can I import same package/class twice? Will the JVM load the package twice
at runtime?
What is the static import?

How many types of exception can occur in a Java program?


What is Exception Handling?
Explain the hierarchy of Java Exception classes?
What is the base class for Error and Exception?
What is finally block?
Can finally block be used without a catch?

What is the difference between throw and throws?


Can an exception be rethrown?
Can subclass overriding method declare an exception if parent class method
doesn't throw an exception?

What is String Pool?

How many ways can we create the string object?


How many objects will be created in the following code?
String s = new String("Welcome");

What are the differences between String and StringBuffer?

What are the differences between StringBuffer and StringBuilder?


How can we create an immutable class in Java?
What is the purpose of toString() method in Java?

Why CharArray() is preferred over String to store the password?

Name some classes present in java.util.regex package.

How the metacharacters are different from the ordinary characters?


Write a regular expression to validate a password. A password must start
with an alphabet and followed by alphanumeric characters; Its length must
be in between 8 to 20.

What are the advantages of Java inner classes?

What are the disadvantages of using inner classes?

What are the types of inner classes (non-static nested class) used in Java?

Is there any difference between nested classes and inner classes?


Can we access the non-final local variable, inside the local inner class?
Can a class have an interface?
Can an Interface have a class?

What is Garbage Collection?

What is gc()?

How is garbage collection controlled?

How can an object be unreferenced?


What is the purpose of the finalize() method?
Can an unreferenced object be referenced again?
What kind of thread is the Garbage collector thread?

What is the difference between final, finally and finalize?

What is the purpose of the Runtime class?

Give the hierarchy of InputStream and OutputStream classes.

What do you understand by an IO stream?

What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?

What are the super most classes for all the streams?
What are the FileInputStream and FileOutputStream?
What is the purpose of using BufferedInputStream and
BufferedOutputStream classes?
How to set the Permissions to a file in Java?

What are FilterStreams?


What is an I/O filter?

In Java, How many ways you can take input from the console?

What is serialization?
How can you make a class serializable in Java?
How can you avoid serialization in child class if the base class is
implementing the Serializable interface?
What is Deserialization?
What is the transient keyword?

What is Externalizable?

What is the difference between Serializable and Externalizable interface?

What are wrapper classes?

What is object cloning?

What is a native method?


What is the purpose of the strictfp keyword?

What is the purpose of the System class?

What is a singleton class?


What is RMI? (Remote method Invocation)

What is multithreading?

What is the thread?

Differentiate between process and thread?

What do you understand by inter-thread communication?

What is the purpose of wait() method in Java?

Why must wait() method be called from the synchronized block?

What are the advantages of multithreading?

What are the states in the lifecycle of a Thread?

What is the difference between preemptive scheduling and time slicing?

What is context switching?

Differentiate between the Thread class and Runnable interface for creating a
Thread?
What does join() method?

Describe the purpose and working of sleep() method.

What is the difference between wait() and sleep() method?


Is it possible to start a thread twice?

Can we call the run() method instead of start()?

What about the daemon threads?


Can we make the user thread as daemon thread if the thread is started?

What is shutdown hook?


When should we interrupt a thread?

What is the synchronization?


What is the purpose of the Synchronized block?

What is static synchronization?

What is the difference between notify() and notifyAll()?

What is the deadlock?

How to detect a deadlock condition? How can it be avoided?


What is Thread Scheduler in java?
Does each thread have its stack in multithreaded programming?

How is the safety of a thread achieved?


What is race-condition?

What is the volatile keyword in java?

What do you understand by thread pool?

What are the main components of concurrency API?

What is the Executor interface in Concurrency API in Java?


What is BlockingQueue?

What is the difference between Java Callable interface and Runnable


interface?

What is the Atomic action in Concurrency in Java?

What is lock interface in Concurrency API in Java?

Explain the ExecutorService Interface.

What is the difference between Synchronous programming and


Asynchronous programming regarding a thread?

What do you understand by Callable and Future in Java?


What is the difference between ScheduledExecutorService and
ExecutorService interface?
Define FutureTask class in Java?

What is the Collection framework in Java?

What are the main differences between array and collection?

Explain various interfaces used in Collection framework?

What is the difference between ArrayList and Vector?

What is the difference between ArrayList and LinkedList?

What is the difference between Iterator and ListIterator?

What is the difference between Iterator and Enumeration?

What is the difference between List and Set?

What is the difference between HashSet and TreeSet?

What is the difference between Set and Map?

What is the difference between HashSet and HashMap?

What is the difference between HashMap and TreeMap?


What is the difference between HashMap and Hashtable?

What is the difference between Collection and Collections?

What is the difference between Comparable and Comparator?

What do you understand by BlockingQueue?

What is the advantage of Properties file?

What does the hashCode() method?

Why we override equals() method?

How to synchronize List, Set and Map elements?

What is the advantage of the generic collection?


What is hash-collision in Hashtable and how it is handled in Java?
What is the Dictionary class?
What is the default size of load factor in hashing based collection?

What do you understand by fail-fast?

What is the difference between Array and ArrayList?


What is the difference between the length of an Array and size of ArrayList?

How to convert ArrayList to Array and Array to ArrayList?


How to make Java ArrayList Read-Only?

How to remove duplicates from ArrayList?

How to reverse ArrayList?

How to sort ArrayList in descending order?


How to synchronize ArrayList?

When to use ArrayList and LinkedList?


Keyword
High Level, Object Oriented, Robust, Secure, Platform independent, High
Performance, Multithreaded, Portable
James Gosling (1991)

1. platform dependent v/s independent


2. System programming v/s application programming
3. supports goto v/s no goto
4. multiple inhertence v/s only with interface
5. operator overloading v/s no operator overloading
6. pointer support v/s restricted pointer support (internal only)
7. Compiler only v/s Compiler + interpreter
8. Call by value and Call by reference vs Call by value
9. Depends on third party library for thread v/s has thread support
10. No documentation comment vs documentation comment /**...*/
11. low level v/s high level
12. No GC v/s GC

1. Object Oriented
2. Portable
3. Platform Independent
4. Secured
5. Robust (GC and Exception Handling)
6. High Performance
7. Multithreaded
8. Distributed(RMI and EJB)
9. Dynamic

Enables computer to run java code


Acts like runtime engine
ByteCode -> Machine Code
1. JVM: For running the java code (Bytecode -> Machine Code).
2. JRE: Provides files for JVM (rt.jar, other files)
3. JDK: Provides development tools. (Loader, Debugger, Documentation
generator, compiler)
1. Class (method) Area
2. Heap
3. Stack
4. Program Counter Register
5. Native Method Area
Improves Performance. Can find the repeated method calls and convert the
bytecode to machine code
Environment in which hardware or software can run.
Java is software platform
Bytecode
Used to load class files into memory Area
1. Bootstrap ClassLoader: rt.jar
2. Application ClassLoader: App.class
3. Extension ClassLoader: Third Party class files
yes
no. but null is a keyword

Empty
No problem.
No value
define access scope
1. public: any
2. private: within class
3. default: within package
4. protected: within package + subclass
1. Part of class and not object
2. Shared across all the objects
3. Can be accessed without creating class
1. Packages avoid the name clashes.
2. The Package provides easier access control.
3. We can also have the hidden classes that are not visible outside and used
by the package.
4. It is easier to locate the related classes.

30Javatpoint
Javatpoint1020

200Javatpoint
Javatpoint200
Compilation error: Expected Boolean but got int
It is programming paradigm based on objects.
Data and methods are defined in a class.
Objects are instance of class
Bottom up approach in program design
Details are hidden from user using abstraction
real time entity, state and behavior, instance of class
Object can be created using new keyword
1.all concepts of OOPS v/s not all (inheritance and polymorphysm)
2. Does not have inbuilt objects v/s has inbuilt objects (window object of
javascript)
3. Java, C++ v/s javascript, vbscript

Null.

1.Special type of method


2. Used for object creation
3. Called when new keyword is used
4. Name must be same as class name
5. Does not have return type
6. Memory is allocated for the object
1.Default Constructor
2.Parameterized Constructor
Used for initializing instance variables and perform tasks
Yes. Current instance of the class (Implicitly)
No
No
yes. Example: Override default constructor with parameterized constructor
No copy constructor in java
Alternatives:
1. By constructor: Pass object as parameter to constructor
2. assign value of one object to another
3. Object.clone()
1. initialize state v/s expose behavior
2. must not have return type v/s must have
3. invoked implicitly v/s explicitly
4. compiler provides default constructor v/s not possible
5. name must be same v/s may or may not be same

Output : 0

Output: Compilation Error


Reason: No default constructor
1. Belongs to class rather than object
2. Shared between all the objects
3. Stored in class area while class loading
4. Stored only once. Memory efficient
5. Example: College name, Company name
1. Belongs to class rather than object
2. No need to create object to call
1. cannot call not static method or variable
2. cannot contain this or super keywords
1. object is required to call
2. JVM will have to create object which will take space
No
1. Used to initialize static variables
2. Called before main method and at the time of class loading
no. possible before JDK 1.7 using static block

Runtime error:NoSuchMethodError
Compilation error : modifier static not allowed here
No
Yes
Refers to current object
No. Reason: final variable
Yes. Not best practice
1. final variable
2. Can be used with synchronized blocks

When child object inherits all the properties of parent object


Is-a relationship

Advantages:
1. Code reusability
2. Overriding (runtime polymorphism)

Types:
1. Single: A - B
2. Multilevel: A - B - C
3. Multiple (Not supported) : A, B > C
4. Hierarchical: A < B, C
4. Hybrid = Hierachical + Multiple (Not supported) A < B, C > D
Object class
Ambiguity
1. Aggregation class contains the reference to the class it own
2. has-a relationship
3. Person class has Address class
1. If the contained object cannot exist without the existence of container
object, then it is called composition.
2. Particular case of aggregation
weak v/s strong relation
Unsafe/Unsecure and complex to understand
Refers to immediate parent class
No
1. Used to create clone of object
2. Object.clone
3. java.lang.Cloneable : CloneNotSupportedException
1. Polymorphism technique
2. Same method name but different signature
Ambiguity
No
Yes
Datatype can be promoted if no matching found
error: reference to sum is ambiguous
If a subclass provides a specific implementation of a method that is already
provided by its parent class, it is known as Method Overriding. It is used for
runtime polymorphism and to implement the interface methods.
Yes
No
Yes. but only upwards
Yes. All functions are virtual
Different return type while overriding
#VALUE!
Yes
No
No
1. call to method is decided at compile time v/s runtime
2. static binding v/s dynamic binding
3. overloading v/s overriding
4. faster execution v/s slower execution
5. less flexibility v/s more flexibility
type comparison operator
dog instanceof Animal //true
hide the implimentation details and only show functionality to the user.

Ways to achive abstraction:


1. Abstract keyword
2. Interface
Abstraction : hides implementation details
Encapsulation : wraps the code and data in single unit
1. Cannot create object of abstract class
2. Needs to be extended
No
No
No
1.Blueprint for a class. Used to achive full abstraction and multiple
inheritance
2. is-a relationship
3. Java 8 update: default, static and private methods
Does not have any abstract methods
Examples: Serializable, Clonable

No
When object implements interface
1. Make all fields private
2. Use getters only. No setters
1. Make all fields private
2. Use setters only. No getters
1. Can make class read or write only
2. Have more control over read and write by controlling behaviour of getters
and setters
1. Group similar type of classes, interfaces and subpackages
2. Access protection/control
3. Remove name collisions
4. Inbuilt packages and user defined packages
No. It is by default loaded internally by the JVM.

Yes. No.
Used to access static members of class
1. Checked : Compile time : SQLException, ClassNotFoundException
2. Unchecked : Runtime : Arithmatic, NullPointer
3. Error : Not recoverable : OutOfMemoryError, AssertionError
Mechanism which is used to decide how handle error
#VALUE!
Throwable class
Executes regaurdless exception is handled or not
yes
1. used to throw exception v/s declare exceptions
2. followed by and instance v/s followed by class
3. Used within method v/s with method signature
4. cannot throw multiple v/s can declare multiple
Yes

Yes but only unchecked exception not checked.


1. space reserved in heap memory.
2. Checked if string is alread there
3. Saves memory by avoiding duplicacy
1. String Literal (String s1="Welcome"; )
2. By new keyword (String s=new String("Welcome");)

2 objects. One in string pool and One in Heap (non pool)


1. Immutable v/s Mutable
2. Slow and consumes for memory while concat v/s fast and less memory
3. Overrides equals method of Object class v/s don't
1. Thread safe v/s not thread safe
2. less efficient v/s more efficient
Make class and all its fields final
Returns string representation of object
Strings are stored in string pool which can be extracted by memory dump
and can be viewed as text until it is cleared by garbage collection.
You can set CharArray() blank when you are done with password.
1. MatchResult interface
2. Matcher class
3. Pattern class
4. PatternSyntaxException class
Metacharacters have special meaning for regular expression engine
^$.*+
Escape with backslash (/)

^[a-zA-Z][a-zA-Z0-9]{7,19}
1. Inner class can access members of outer class even private
2. Less code needs to be written
1. Increases workload on JVM
2. IDE provides less support
1. Member inner class : Class within class
2. Local inner class : Class within method
3. Anonymous class : Created for implementing the interface or extending
the class
Yes, inner classes are non-static nested classes. In other words, we can say
that inner classes are the part of nested classes.
No
Yes
Yes
1. Process of removing unused objects from memory
2. Performed automatically
1. Used to trigger garbage collection for cleaning process.
2. Found in system and runtime class
3. System.gc();
1. Garbage collection is managed by JVM
2. It is performed when there is not enough space in the memory
3. We can externally call System.gc() method but gc is not guaranteed.

1. By nulling the reference.


Employee e=new Employee();
e=null;
2. By assigning reference of nother object.
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;
3. Using anonymous objects.
new Employee();
1. Ran just before the garbage collection
2. Can be used to clear the objects which are not created using the new
keyword.
3. Part of Object class
public void finalize()
{
System.out.println("Object is garbage collected");
}
Yes. Using weakreference
Daemon thread
1. Object cannot be assigned again vs. finally block vs. garbage collection
method
2. keyword vs. block vs. method

1. Interact with JRE


2. Provides methods to execute process, invoke GC, get total and free
memory.
Runtime.getRuntime().exec("notepad");
3. Only one instance of java.lang.Runtime class.
4. The Runtime.getRuntime() method returns the singleton instance of
Runtime class.
1. File
2. ByteArray
3. Filtered -> Data, Buffered, PrintStream
4. Piped
5.Object
Stream is a sequence of data coming from source to destination.
Type of streams created automatically.
1. System.out : Standard output stream
2. System.in : Standard input stream
3. System.err : Standard error stream
1. Character oriented v/s Byte oriented
2. 16 bit bytes v/s 8 bit bytes
3. FileReader, FileWriter v/s FileInputStream, FileOutputStream
1. ByteStream and CharacterStream
2. ByteStream -> InputStream, OutputStream
3. CharacterStream -> Reader, Writer
FileOutputStream:
1. Used for writing data into file
2. Use FileOutputStream for writing primitive value
3. Can write byte oriented as well as character oriented data
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();

FileInputStream:
1. Used for reading data from file
2. Used for reading byte oriented data such as image, audio, video also
characters
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);

Internally uses buffere to improve performance


Using FilePermission and PermissionCollection class
1. Add additional functionality to the other stream classes
2. Acts like interface which reads the data from stream, filters it and passes
the filtered data to caller.
3. Example: add the line numbers to the destination file
Reads data from one stream, modifies it and writes to another stream.

1. BufferedReader class:
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String name = reader.readLine();

2. Scanner class:
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();

3. Console class:
Console c=System.console();
String name = c.nextLine();
1. Writing state of an object into file/storage
2. Hibernate, JPA, EJB, JMS, RMI (Remote method invocation)
3. Transfer state of object over network (marshaling)
4. Serializable interface is used for serialization

Implement serializable interface


Impliment readObject and writeObject methods and throw
NotSerializableException
1. Process of reversing the serialization process on object to reconstruct the
object
2. ObjectInputStream deserializes the object
ObjectInputStream in=new ObjectInputStream(new
FileInputStream("f.txt"));
Student s=(Student)in.readObject();
Field should not be serialized
1. Interface Used to write state of an object into byte stream in compressed
format
1. Marker Interface v/s not Marker Interface (writeExternal() and
readExternal())
2. Easy to impliment but lower performance v/s complex to implement but
higher performance
3. No constructor is called v/s default constructor is called

1. primitive -> object


2. primitive -> object = autoboxing
3. object -> primitive = unboxing
4. Wrappers present in java.lang
1. Create exact copy of an object
2. clone() method object class is used
3. java.lang.Clonable otherwise CloneNotSupportedException
protected Object clone() throws CloneNotSupportedException
1. Methods which are implimented in language other than java
2. can also be called as foreign methods
To get the same results on different platform for floating point operations

Used for utilizing system resources


1. Standard input
2. Standard output
3. Standard error
4. Load the file
5. Stop the application System.exit(0);

1. Singleton classes can have only one instance at max


2. make constructor private
3. implement static getInstance() method

public static Singleton getInstance()


{
if(singleIinstance == null)
{
singleInstance = new Singleton();
}
return singleInstance;
}
1. API helps to create distributed application in java.
2. Allows to call methods on an object running in different JVM
3. Communication using stub and skeleton
1. Process of executing multiple thread simultaneously
2. Used to obtain multitasking
3. Improves performance
4. Threads are lightweight
5. Cost of communication is low
1. Thread is lightweight subprocess.
2. Each thread runs in different stackframe.
3. Thread shares process resources.
1. Processes are independednt v/s thread is subset of process
2. context switching is faster in threads
1. Process of communication between synchronized thread is called --
2. Used to avoid thread polling
3. It can be obtained by wait(), notify(), notifyAll() methods
1. Used for inter-thread communication
2. Method of Object class
3. Used to pause the current thread from execution until other thread calls
notify() or notifyAll() method.
public final void wait()
1. java.lang.IllegalMonitorStateException
2. Also used for inter thread communication
1. Always reactive to input even when some background task is running.
2. Faster execution of tasks
3. Better utilization of cache
4. Can reduce number of required servers
1. New: thread object is created using new keyword.
2. Runnable: After start() method is called.
3. Running: After thread scheduler picks up the thread.
4. Waiting/Blocked: When thread is waiting
5. Terminated/Dead: when run() method exits.
Preemptive Scheduling: Highest priority task executes first.
Time slicing: Task is executed for predetermined amount of time and then
enters the thread pool of ready tasks.
1. Stores the state of process or thread while switching process or thread so
that it can be restored while resuming
2. Enables multiple process to share the same CPU.

Thread class: By Extending Thread Class


- Cannot extend any other class
- Each Thread creates unique object
- Provides getPriority(), isAlive() methods
Runnable Interface: By implementing Runnable Interface
+ Can extend other classes
+ All thread share the same object
+ Provides only run() method
It causes current running thread to stop executing until the thread it joins
with completes the task
public void join()throws InterruptedException
public void join(long milliseconds)throws InterruptedException
Used to block a thread for perticular time
public static void sleep(long milliseconds)throws InterruptedException
public static void sleep(long milliseconds, int nanos)throws
InterruptedException
1. Defined in Object class v/s Thread class
2. Releases lock v/s Does not release lock
No. java.lang.IllegalThreadStateException
Yes. But it will not create a Thread. It will not create new stack. No context
switching.
If we call start() then it internally calls the run() and create new stack
It is low priority thread used to provide background support and services to
the user threads.
They automatically get terminated if there is no user thread.
setDaemon(boolean status) //Set thread as daemon
isDaemon() //Check of thread is daemon thread
No. IllegalThreadStateException

Thread which is used to for cleanup purpose and save states.


It is used implicitly called before JVM shuts down.
Runtime runtime = Runtime.getInstance();
runtime.addShutDownHook(new MyThread());
It is more reliable then finalizer()
Can be stopped by calling runtime.halt(int)
When we want to change state of thread which is in sleep/wait state

Capability to control the access of mutiple threads to any shared resource


Avoids. 1.Thread Interference. 2. Consistency Problem
Allows only 1 thread to be executed at 1 time
Synchronized can be achived by
1. synchronized method
2. synchronized block
3. static syncronization
To lock a resource for a single thread at a time
If we use synchronization on static method then the lock will be on the class
rather that object
notify() : Unblock one waiting thread
notifyAll() : Unblock all waiting threads
Can break our code at runtime.
When one thread is waiting for resource which is held by some other waiting
thread
By Collecting Thread dump
Ways to avoid:
1. Avoid nested lock
2. Avoid unecessary lock
3. Using thread join
1. Used to sepervise the threads
2. Decides which thread to execute
Scheduling mechanisms: i) Pre-emptive 2) Time slicing
Also Decides:
1. Priority of Thread
2.waiting time of thread
3. Check nature of thread
Yes

If class or method can be accessed by mutiple threads at same time without


race condition then class is thread safe.
Can be achived by
1. Synchronization
2. Using volatile keyword
3.Using lock based mechanism
4.Using atomic wrapper classes
When multiple thread tries to access same resource
Used to achive thread safety.
Change in volatile variable is visible to all threads.

1. Java Thread pool represents a group of worker threads, which are waiting
for the task to be allocated.
2. Threads in the thread pool are supervised by the service provider which
pulls one thread from the pool and assign a job to it.
3. After completion of the given task, thread again came to the thread pool.
4.The size of the thread pool depends on the total number of threads kept at
reserve for execution.
Advantages:
1. Using a thread pool, performance can be enhanced.
2. Using a thread pool, better system stability can occur.

Can be developed using java.util.concurrent package.


Packages:
1. Executor
2. ExecutorService
3. ScheduledExecutorService
4. Future
5. ThreadFactory
6. BlockingQueue
7. DelayQueue
8. Locks

The execute() method in executor interface is used to execute some given


commands
Executor e = Executor.newCacheThreadPool();
executor.execute(new DemoObject());
ThreadPoolExecutor pool = (ThreadPoolExecutor)e;
pool.shutdown();
java.util.concurrent.BlockingQueue
BlockingQueue waits for space availability before inserting a new value and
waits for queue to be non empty before retrieving value
BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10);
1. Can return result v/s cannot return result.
2. Can throw checked exeption v/s cannot throw checked exception
3. Callable cannot be used before java 5.
1. The operation can happen all at once without possibility of interruption.
2. Atomic operation cannot be stopped in between
3. All read and write operation of primitive and volatile variable are atomic
4. Atomic methods are present in java.util.concurrent package

1. java.util.concurrent.locks.Lock interface is used as synchronization


mechanism. It works similar to synchronization block.
Lock Interface v/s synchronize block
1. Gives guarantee of sequence of access for waiting thread v/s no
2. Provides option of timeout if lock is not granted v/s no
3. The methods of Lock interface (lock() and unlock() methods) can be called
from different methods v/s entire must be contained in method
SubInterface of Executor Interface which adds the features to manage the
lifecycle.
Synchronous programming : Thread can perform a new task only after it
completes the current task
Synchronous programming : Multiple threads can work on same task. Better
for efficiency.

Java Callable interface : In Java5 callable interface was provided by the


package java.util.concurrent. It is similar to the Runnable interface but it can
return a result, and it can throw an Exception. It also provides a run() method
for execution of a thread. Java Callable can return any object as it uses
Generic.
public interface Callable<V>

Java Future interface: Java Future interface gives the result of a concurrent
process. The Future interface returns the object of
java.util.concurrent.Future.

Java Future provides following methods for implementation.

cancel(boolean mayInterruptIfRunning): It is used to cancel the execution of


the assigned task.
get(): It waits for the time if execution not completed and then retrieved the
result.
isCancelled(): It returns the Boolean value as it returns true if the task was
canceled before the completion.
isDone(): It returns true if the job is completed successfully else returns false.
SheduledExecutorService allows to execute task with delay or every fixed
time interval
Implements Future Interface. Result can be obtained if execution of one task
is completed. If execution is completed then it can't be restarted or
cancelled.
1. Combination of classes and interfaces
2. Used to store and modify data which is stored in object form
1. Fixed size v/s dynamic size
2. Only can store objects of same type v/s can store object of different type
3. Does not include in-built methods for searching, sorting v/s includes
1. Collection Interface
2. List Interface
3. Queue Interface: FIFO
4. Dequeue Interface: FIFO and LIFO
5. Map Interface
1. Not thread safe v/s Thread safe
2. Not synchronized v/s synchronized
3. Not legacy v/s Legacy
4. Increases size by 50% v/s doubles the size
1. Uses dynamic array v/s uses doubly linkedlist
2. Not efficient for manipulation v/s efficient
3. Better to store and fetch data v/s better to manipulate data
4. Provides random access v/s does not provide random access
5. Less overhead v/s more because it stores addresses of the object as well
1. Traverse in forward direction only v/s traverse in both directions
2. Can be used with List, Set, Queue v/s Only List
3. Can only perform remove operation v/s remove, add, set
1. Can traverse legacy and non legacy elements v/s only legacy
2. Fail fast v/s not fail fast
3. slower v/s faster
4. can perform remove operation v/s cannot
1. Can contain duplicate elements v/s cannot
2. Ordered collection v/s unordered
3. Contains one legacy class (Vector) v/s no legacy class
4. Can allow multiple null values v/s single null value
1. No order v/s ascending order
2. Implemented using HashTable v/s Implemented using Tree structure.
3. Faster v/s slower
4. Backed by HashMap v/s Backed by TreeMap
TreeSet cannot hold null value
1. Contains values v/s Contains keys and Values
2. Contains unique values v/s unique keys with duplicate values
3. can contains single null value v/s single null key and multiple null values
same as above
1. Implements Set interface v/s Implements Map interface
Same as above : HashSet v/s TreeSet
TreeMap cannot hold null key
1. Not thread safe v/s Thread safe
2. Not synchronized v/s synchronized
3. Not legacy v/s Legacy
4.Can have one null key and n null values v/s cannot have null key or value
5. Extends AbstractMap class v/s Extends Dictionary class
1. Inteface v/s class
2. Provides datastructure interfaces v/s Provides methods sort and
synchronize
1. Can provide only one sort of sequence v/s Can provide multiple
2. compareTo() v/s compare()
3. java.lang v/s java.util
4. Actual class is modified v/s not modified

1. Extends queue interface.


2. Provides concurrency (thread safe) for operations like insertion, retrieval,
deletion
3. While retrieving it waits for ths queue to be non empty
4. While insertion it waits for available space
5. Cannot contain null elements
public interface BlockingQueue<E> extends Queue <E>

1. If you change property in property file then you don't need to recompile
the code
2. Used to store information which is changed frequently

FileReader reader=new FileReader("db.properties");


Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
1. The hashCode() method returns hash code value (integer value).
2. hashCode() method provides same integer number if two numbers are
identical.
3.If two objects do not produce same result with equals() method then
hashCode() method will provide different result;
1. We use equals(obj) method to check if two objects are same or not
2. We override equals method if we want to compare objects based on
property.

The Collections class provides these methods


1. public static List synchronizedList(List list){};
2. public static Set synchronizedSet(Set set
3. public static SortedSet synchronizedSortedSet(SortedSet sortedSet){};
4. public static Map synchronizedMap(Map map){}
5. public static SortedMap synchronizedSortedMap(SortedMap sortedMap){}
1. No need of type casting
2. Type safe and checked at compile time
1. Two different keys with same hash value is know as hash-collision. Two
different entries will be kept in same hash bucket.
2. Ways to avoid hash collision : i)Separate Chaining ii)Open addressing
Provides the capability to store key value pairs
0.75
Immediately throws exception if any structural modification is done
ConcurrentmodificationException
1. Fixed size v/s dynamic size
2. Can store primitive datatypes and Objects v/s only objects
3. Does not provide in-built methods v/s provides
array.length; v/s arrayList.size();
1. Arrays.asList(array);
2. arrayList.toArray(new int[6]);
Collections.unmodifiableCollection(list);
1. HashSet
2. LinkedHashSet
3. list.stream().distinct().collect(Collectors.toList());
1. Manual way
2. Collections.reverse(list);
1. Collections.sort(list, (a, b)-> b-a);
2. Collections.sort(list, Collections.reverseOrder());
Collections.synchronizedList(list);
ArrayList: Searh operation
LinkedList: Manipulation
Explaination

Java is the high-level, object-oriented, robust, secure programming language, platform-independent,


high performance, Multithreaded, and portable programming language. It was developed by James
Gosling in June 1991. It can also be known as the platform as it provides its own JRE and API.

Javatpoint 3rd Question

Java Virtual Machine is a virtual machine that enables the computer to


run the Java program. JVM acts like a run-time engine which calls the
main method present in the Java code. JVM is the specification which
must be implemented in the computer system. The Java code is compiled
by JVM to be a Bytecode which is machine independent and close to the
native code.

#VALUE!

#VALUE!
Keyword = Object Reference
#VALUE!
1. File
2. ByteArray
3. Filtered -> Data, Buffered, Pushback
4. Piped
5.Object
1. boolean = Boolean
2. char = Character
3. byte = Byte
4. short = Short
5. int = Integer
6. long = Long
7. float = Float
8. double = Double
No. Question Type
1 Introduction

2 Introduction

3 Dependency Injection
4 Dependency Injection

5 Dependency Injection

6 Dependency Injection

7 Basics

8 Basics

9 Basics

10 Basics
11 Basics
12 Basics
13 Basics

14 AOP
15 Dependency Injection

16 Dependency Injection

17 Dependency Injection

18 Dependency Injection

19 Spring Boot

20 Spring Boot
21 Spring Boot

22 Spring Boot
Question
What is Spring Framerwork?

Core features?

What is Inversion of Control?


How to achieve Inversion of Control?

What is dependency Injection?

Ways to implement dependency injection

What is Component?

What is Bean?

Bean LifeCycle

What is AppConfig/SpringConfig class


What is AnnotationConfigApplicationContext class
What is @Autowired annotation?
What is scope of Bean?

What is Spring AOP?


What is Circular Depedencies?

How to handle Circular dependencies?

What is bean factory?

What is difference between bean factory and application c

How Spring Boot is different?

What is @SpringBootApplication?
What is @RestController?

What is difference between @RequestParam and @PathVar


Explaination
Open source framework build for creating enterprice applications

1. Inversion of Control
2. Dependency Injection
3. Spring Container
4. Spring MVC
5. Spring Data Access (ORM)
6. Simplified Configuration
7. Real Time Capabilities

Framework controls object creation and Dependency


Management

Advantage:
1. Minimum impact on other classes while modification
2. Easies testing
Using dependency injection
1. Design pattern which is used to implement inversion of control
principle.
2. Dependencies are maintained in Spring IoC container via
AppConfig
1. Contructor Injection (Best)
2. Setter Injection (Optional)
3. Field Injection (Cannot test)
4. Method Injection (Optional/Inject Dynamically/Rarely used)
`@Component annotation is used to indicate that a class is
spring managed component
Component refers to a class or bean that is managed by spring
IoC

A spring bean is an object that is instantiated, configured and


managed by the spring IoC container.
These beans are building blocks of Spring Application.
`@Bean annotation in Spring Boot is used to indicate that a
method is a bean method and produces a bean to be managed
by the spring container
Every component is a bean but every bean is not a comonent

1. Spring IoC container started


2. Bean Instantiated
3. Bean Injected
4. Bean Initialized
5. Bean Used
6. Bean Destroyed
We define beans with @Configuration and @Component scan
annotation
It is IoC container responsible for managing beans
It is used to inject the bean from IoC container
Refers to how many instances will be created.
1. Singleton: Only one instance (default)
2. Prototype: Multiple instance
3. Request:
4. Session:
5. Application:
Spring Aspect Oriented Programming allows use to separate
cross cutting concerns from business logic
1. Logging
2. Security
3. Transaction
When two dependencies depend on each other
1. Change code structure
2. Use @Lazy annotation
3. Use setter injection
Load the beans from beans.xml instead of
AnnotationConfigApplicationContext
1. Lazy initialization v/s Eager
2. Not easy integration with AOP v/s Easy integration with AOP
3. Not suitable for big projects v/s Suitable
1. Embedded tomcat server
2. Autoconfiguration
3. Starter template
Combination of @EnableAutoConfiguration + @Congiguration +
@ComponentScan
Combination of @Controller + @ResponseBody
1. @RequestParam = extract from query param
2. @PathVariable = extract from URI itself

You might also like