├── BasicConcepts.java ├── Collection.java ├── Design-Patterns.java ├── Design-Principle.java ├── ExceptionHandling.java ├── Generics.java ├── Inner-classes.java ├── JVM Architecture.java ├── Java8.java ├── Language-Fundamentals.java ├── MultiThreading.java ├── OOPS in java.java ├── README.md ├── Serialization.java ├── enum.java ├── file IO.java ├── file-NIO.java ├── flow control.java └── java-lang.java /BasicConcepts.java: -------------------------------------------------------------------------------- 1 | 2 | Operators: 3 | 4 | How many types of operators are present in java? 5 | There are : 6 | 1. Arithmetic Operators 7 | 2. Unary Operators 8 | 3. Assignment Operator 9 | 4. Relational Operators 10 | 5. Logical Operators 11 | 6. Bitwise Operators 12 | 7. Shift Operators 13 | 8. Ternary Operator 14 | 15 | What are Arithmetic operators? 16 | Arithmetic operators are used to perform simple arithmetic operations on primitive data types. 17 | These are; 18 | + Addition Operator 19 | - Subtraction Operator 20 | * Multiplication Operator 21 | / Division 22 | % Modulo operator 23 | 24 | Can we add two short values to a short type? 25 | No we cannot. Addition of two short type numbers will be int. If we Try to assign it too short we 26 | will get an error. 27 | 28 | 👉🏻 Any operation between two integer type variables which are smaller than int, will always results in 29 | an int. 30 | 31 | What are Unary Binary and Ternary operators? 32 | Unary Operators are the operators which operate on only one operand. 33 | Binary Operators operate on two operands and Ternary operators operate on Three operands. 34 | 35 | 👉🏻 We have Arithmetic, Assignment, Relational, Logical, Bitwise, Shift Operators which takes 36 | two operands to operate on. 37 | 38 | Explain Unary operators. 39 | Unary operators are such operators which needs only one operand and are used to increment decrement 40 | value or inverting the value. 41 | 42 | 1. Unary plus + : used for giving positive values. 43 | 2. Unary minus - : used for negating the values 44 | 45 | 3. Increment operator ++ : increments the value by 1. 46 | There two ways in which we can use this operator, 47 | -> Post-increment and Pre-increment 48 | a++; ++a; 49 | Post pre 50 | 51 | -> What is the difference between ++a and a++ under increment operators? 52 | In post increment the value gets incremented by 1 after computing the result. 53 | 54 | 4. Decrement operator -- : decrements value by 1. 55 | Two ways to use this, post decrement and pre decrement. 56 | 57 | 5. Logical not operator ! : which is used for inverting a boolean value. 58 | 59 | What is Assignment Operator, and what are Compound Assignment operators? 60 | Assignment operator: '=' 61 | This operator is used to assign a value to any variable. 62 | It assigns value given on the right hand side of the operator to the left hand side variable. 63 | 64 | variable = value; 65 | 66 | Compound Assignement : 67 | Combining Assignment operator with other operators. 68 | These are compound statements: 69 | +=, -=, *=, /=, %= 70 | 71 | Which operators are used to compare the primitives with each other? 72 | Relational Operators. 73 | These operators are used compare two operands. like, if an element is equals to another or not. Such operators return boolean result. 74 | 75 | These are some relational operators: 76 | 77 | 1. == (equal to): returns true if left hand side value is equal to right one. 78 | 79 | a= 10, b= 20 80 | System.out.println((a==b)); prints false 81 | 82 | 2. != (Not equal to): returns true if left side value is not equal to right one. 83 | 84 | System.out.println((a!=b)); prints true 85 | 86 | 3. < (less than): returns true if left side value is less than the right one. 87 | 88 | System.out.println((a (greater than) 91 | 92 | 5. <= (less than or equals to) : this will return true if the value at left side is either less than 93 | or equal to the value at right side. 94 | 95 | 6. >= (greater than or equal to) 96 | 97 | What is the difference between the statement a = a+b and a+=b? 98 | This compound assignment [+=] implicitly cast the result of addition into the type of variable used 99 | to hold the result. 100 | 101 | Can we cast an int value into byte variable? 102 | Yes we can cast. 103 | int a = 10; 104 | byte b = (byte) a; 105 | 106 | What will happen if the value of int is larger than the byte? 107 | An int is 32 bit long, while byte is 8 bit long. When we cast an int to byte, the higher 24 bits 108 | will be lost as byte can only hold value from -128 to 128. 109 | 110 | What is difference between equal to (==) and .equals() ? 111 | The equality operator is a binary operator which is provided by java to compare primitives and objects. 112 | Whereas .equals() is a method defined by Object class, which is used to compare objects. 113 | 114 | In order to compare objects: 115 | Equality operator (==) returns true only if both objects references points to the same object. 116 | while equals() returns true if both have same value. 117 | 118 | What will this return : 3*0.1 == 0.3? True or False? 119 | Logically this should return true, But This will return false. 120 | Because some floating point numbers can not be represented exactly. 121 | 122 | What are logical operators? 123 | Logical operators are used to perform the logical AND and logical OR operations. 124 | Operands with logical statements are conditions, which results into true or false. 125 | 126 | 1. && (Logical AND): returns true when both conditions are true. 127 | 128 | 2. || (Logical OR) : This returns true either the condition present in left side returns true or 129 | condition at right returns true. 130 | 131 | 👉🏻 Relational operators and Logical operators are used mostly in looping statements and conditional 132 | statements. 133 | 134 | What are Bitwise Logical Operators in java? 135 | Bitwise operators are used to perform operations on individual bits of number for example, 136 | These are the bitwise operators: 137 | 138 | 1. Bitwise AND Operator & : which returns bit by bit AND of input values. 139 | 2. Bitwise OR Operator | : which returns bit by bit OR of input values. 140 | 3. Bitwise XOR Operator ^ : which returns bit by bit XOR of input values. 141 | 4. Bitwise Complement Operator ~ : the unary operator which returns one-s complement representation 142 | of input value. 143 | 144 | We can use these operators with any of the integer type. 145 | 146 | We can also use Bitwise OR and Bitwise AND operators in conditional statements. 147 | 148 | What is difference between Logical OR and Bitwise OR? 149 | While operating, The logical OR operator does not check second condition if first condition is true. 150 | It checks second condition only if first condition is false. 151 | Whereas the bitwise OR operator always checks both conditions, whether first condition is true or not. 152 | 153 | What is Ternary Operator (Conditional) in java? 154 | In java, Ternary operator is a shorter version of if-else statement. 155 | It has three operands: 156 | 157 | Condition ? If true : if false 158 | 159 | Explain Shift operators in java. 160 | There are two types of Shift operators: 161 | Left Shift << 162 | Right Shift >> 163 | 164 | The Left shift operator in java is used to shift all the bits in a value to the left side of a 165 | specified number of times. 166 | 167 | And Right shift operator is used to move left operands value to the right by the number of bits 168 | specified by the right operand. 169 | 170 | What is the difference between >>(Bitwise right shift operator) and >>>(bitwise zero fill right shift)? 171 | This '>>>' is also used to shift the bits towards right. But it is different from the regular '>>', 172 | as it does not protect the sign bit of the number, while '>>' protects the sign bit. 173 | 👉🏻 '>>>' this always fills 0 in the sign bit. 174 | 175 | What is the precedence of operators available in java? 176 | When it comes to hybrid equations, which have more than one or two operators, 177 | then the operators which have higher precedence are solved first. 178 | 179 | What is instanceof operator? 180 | This operator is used to check if an object is an instance of a Class or a subclass. 181 | 182 | object instanceof class/subclass/interface 183 | 184 | -> This operator is used for Type Checking. 185 | 186 | 187 | -------------------------------------------------------------------------------- /Collection.java: -------------------------------------------------------------------------------- 1 | 2 | What is Java Collection Framework? 3 | A java collection framework is a collection of interfaces and classes which are used to store and 4 | process data efficiently, as a Collection is something which is used to store Data objects. 5 | 6 | This framework was introduced in Java version 1.2. 7 | -> Reduced the development effort. 8 | -> Code quality is enhanced. 9 | 10 | What are the basic interfaces of collection framework? 11 | 12 | 1. Collection 13 | 2. List 14 | 3. Set 15 | 4. Queue 16 | 5. Map 17 | 18 | Why Map Interface does not extend Collection interface? 19 | The Map is way different than collection. In Map there are no elements, it has key-value pairs. 20 | 👉🏻 It does not fit into the Group of elements Paradigm. 21 | 22 | However there are many methods to retrieve keys and values as collection. 23 | 24 | What is the difference between Collection and Collections? 25 | 26 | Why Collection Interface does not extend Serializable and Cloneable interfaces? 27 | 'There is no need to do it!' 28 | Collection is not supposed to do what Cloneable and Serializable interfaces do. 29 | 30 | What they do? 31 | They are just the marker interfaces which are actually empty interfaces. 32 | 33 | 👉🏻 If Collection Interface implements these interfaces then it will mandate cloning and serialization 34 | in all implementation, which is less flexible and more restrictive. 35 | 36 | When we had Array, Why do we need collection? 37 | We know Array is a group of primitives.. which holds homogeneous data. 38 | It has also some limitations like, arrays are always fixed in size. 39 | So to overcome these problems, collection were introduced. 40 | Collection, which can also be called a container, is a group of individual objects. 41 | 42 | How can it solve the problems that we had in array? 43 | 44 | Collections are grow-able in Nature, 45 | that means we aren't bound to declare size of any collection at declaration as we are with arrays. 46 | Size of collections can be increased or decreased on the base of our programming requirement. 47 | You can add or remove any number of elements in collection. 48 | 49 | hence collections solve the first limitation. 50 | 51 | And next, 52 | we only can have homogeneous type of data elements in array, 53 | But Collections can have any kind of data element. They can be homogeneous or heterogeneous. 54 | 55 | when we should use arrays and when collection? 56 | Array are recommended to use if we know the size in advance.. 57 | because Performance-wise Arrays are better to use than Collections. 58 | 59 | From Memory point of view, we should not use 'Arrays'.. 60 | Suppose we take an array of 100 size. And if we only have 10 elements in it, so, 61 | here the rest of the memory blocks get wasted. Thats why arrays are not recommended to use in memory point of view. 62 | On the other hand, Collections are grow-able or resizable in nature, and it uses memory as per required only. 63 | 64 | What is the difference between Array and ArrayList? 65 | The very first difference between Array and ArrayList is, 66 | Array can contain primitive or Objects whereas ArrayList can only contain Objects. 67 | next is 68 | Arrays are fixed in size whereas ArrayList size is dynamic. 69 | And, ArrayList accepts duplicate objects unlike arrays.. 70 | Array does not provide a lot of features like ArrayList, such as add(), addAll(), removeAll() etc.. 71 | 72 | So ArrayList is the obvious choice when we work on list.. But if the size of list is fixed and if we are using the list of primitives then we should use Arrays.. Although collection use auto boxing to reduce the coding effort but still it makes them slow.. so would use array with primitives. 73 | And if are working on multidimensional situation, then also using array [][] is way more easy than List>.. 74 | 75 | How LinkedList is different from ArrayList? 76 | ArrayList and LinkedList both implement the List interface but there are some differences between them.. 77 | 78 | ArrayList is an indexed based data structure.. The underlying data structure for ArrayList is a resizable or growable Array. 79 | 80 | And LinkedList is a data structure which stores data and its address as list of nodes.. here, every node is linked to its previous and next node using pointers.. That is, the address part of the element points to the next element of the linked list.so see the address that the first node is having.. is actually the address of the next node. 81 | 82 | This is how we create ArrayList, and linkedLists 83 | 84 | ArrayList al = new ArrayList(); 85 | //and to add elements.. these are the methods.. (explain the suggestions) 86 | al.add("John"); 87 | al.add("Rohn"); 88 | 89 | LinkedList lList = new LinkedList(); 90 | lList.add(""); 91 | 92 | Since ArrayList is index based data structure, it provides random access to its elements with the performance of O(1).. that is, we can access any element by the index.. Linked list also allows to get any element by index, but internally it traverse the list from start to read at the index node, then return the element. So the performance is O(n) which is slower than of arrayList. Therefore the ArrayList is recommended to use retrieving data.. 93 | 94 | Next thing is, Insertion and removal of any element is faster in LinkedList compared to ArrayList. Because one insertion or deletion in middle requires n number of shifts.. So there is no concept of resizing array when element is added in middle.. 95 | 96 | and in linkedList it requires only one change in the address pointer of the particular node to add or remove any element. 97 | 98 | Next is, 99 | LinkedList consumes more memory than ArrayList because every node in LinkedList stores reference of previous and next elements..' 100 | 101 | What are the different ways to iterate over a list? 102 | To access or to get elements from collection there are many ways present in java. 103 | 1. Loops (classic for loop) 104 | 2. Cursors 105 | In java these are the cursors available for collections: 106 | 1. Iterator 107 | 2. ListIterator 108 | 3. Enumeration 109 | 110 | What is the difference between Iterator and ListIterator and Enumeration? 111 | 112 | What are the legacy implementations? 113 | Vector is a legacy class. 114 | Legacy class: The classes that were already there before introducing collection framework. 115 | 116 | Sub Class of Vector -> Stack, is also a legacy class. 117 | 118 | Vector is implemented on a growable or a resizable array. 119 | -> It is an ordered collection 120 | -> allows duplicates. 121 | 122 | Vector v = new Vector(); 123 | 124 | Stack implements the stack data structure. It is based on the principle of Last In First Out. 125 | 👉🏻 element which is inserted in last, will be the first one to come out. 126 | 127 | Stack s = new Stack(); 128 | 129 | -> to insert any object : push() 130 | -> to remove the top element : pop() 131 | 132 | What are the similarities and difference between ArrayList and Vector? 133 | 134 | Which collection classes provide random access of its elements? 135 | These are the collection classes which provide random access: 136 | ArrayList, Vector, Stack, HashMap, TreeMap, Hash-table. 137 | 138 | What are Stack and Queue? How they are different? 139 | Stack and Queue are used to store data before processing them. 140 | 141 | Queue represents an ordered list of objects which is limited to insert elements 142 | at the end of the list and removing from the start.. 143 | 144 | This is how we create a queue, 145 | 146 | Queue q = new LinkedList<>(); 147 | 148 | being an interface it needs the concrete classes to create objects, 149 | PriorityQueue and LinkedList are most common to use. 150 | 151 | And to add element, 152 | q.add(10); 153 | q.add(20); 154 | 155 | sysout(q); 156 | 157 | and the remove method will remove the head that is the first element 158 | 159 | int a = q.remove(); //return the removed element 160 | sysout("element removed- "+a) 161 | 162 | sysout(q); 163 | 164 | So Queue allows retrieval of element in First In First Out order. and it is different from stack as Stack allows elements to be retrieved in Last In First out order. 165 | 166 | Stack st = new Stack<>(); 167 | st.push(10); 168 | st.push(20); 169 | 170 | To pop, 171 | st.pop(); 172 | 173 | sysout(st); 174 | 175 | So thats the difference between Stack and queue.. Stack is a class and queue is an interface. 176 | 177 | How can we sort Collections? 178 | There are some implementations of set and map which are used to store elements in a sorting order. 179 | -> SortedMap, SortedSet etc. - can be used to get a sorted collection(Map or Set). 180 | 181 | To sort List implementations, the Collections provides method sort(). 182 | 183 | Collections.sort(): sorts list implementation passed to it. 184 | 185 | -> It does not return anything just sorts the collection. 186 | 187 | How to make a collection read only? 188 | We can create a read only collection by using unmodifiableCollection method of Collections class. 189 | 190 | Collections.unmodifiableCollection(Collection c) 191 | 192 | -> if any operation occurs it will throw UnsupportedOperationException. 193 | 194 | How can we make a collection thread-safe? 195 | There is a method in Collections class -> 196 | synchronizedCollection(Collection c) : used to get a synchronized or thread-safe collection. 197 | 198 | What is the difference between Set and List? 199 | Both Set and List are used to store objects and provides convenient way to insert, 200 | remove and retrieve elements and also provides support for iteration. 201 | 202 | Fundamental differences between List and Set: 203 | 1. Allowing Duplicate Elements 204 | 2. Order 205 | 206 | When should we use List and when to use Set?? 207 | 👉🏻 If we need to maintain insertion order and we can have duplicates too then we use List. 208 | 👉🏻 If we want a collection of unique objects then we should use Set. 209 | 210 | How does HashSet is implemented? How does it use Hashing? 211 | 212 | What are Comparable and Comparator interface? When to use what? 213 | 214 | Whats difference between TreeSet and LinkedHashSet and HashSet? 215 | These are the implementations of Set. 216 | 217 | Starting with TreeSet, the main feature of TreeSet is Sorting. 218 | Its the implementation class of sortedSet. 219 | So in TreeSet the insertion of elements is done on some sorting order. 220 | like we want to store all the Employee's object according to their EmployeeIds then we should 221 | go for SortedSet or TreeSet. 222 | Also in treeSet, we cannot put heterogeneous elements in it. 223 | Its about sorting as we cannot sort different type of objects so it is restricted to insert diff data types in treeSet. 224 | 225 | SortedSet t = new TreeSet<>(); 226 | 227 | It will creates an TreeSet object in which elements to be inserted in Default natural sorting order. 228 | Note that, If we are depending on the default natural sorting order, then our elemtns/object should be... 229 | homogeneous and comparable, otherwise we will get classCastException. 230 | 231 | So we can add integer only. 232 | t.add(10); 233 | t.add(5); 234 | sysout(t); 235 | 236 | This will add both elements in ascending order by default. 237 | 238 | And next is LinkedHashSet.. it was introduced in 1.4 version. It is the sub class of Hashset (no insertion order) where insertion order is preserved. 239 | And that's the main difference between HashSet and LinkedHashSet. 240 | 241 | We create linkedHashSet like, 242 | LinkedHashSet lhs = new LinkedHashSet(); 243 | 244 | So all of the three, TreeSet, LinkedHashSet and HashSet doesn't allow to store duplicates. 245 | And none of these are thread-safe.. 246 | But HashSet is the Fastest among them. 247 | LinkedHashSet comes second or can be similar to HashSet but 248 | TreeSet is slower because it performs sorting for each insertion. 249 | 250 | Next difference between these, is ordering. 251 | HashSet doesn't maintain any order while LinkedHashSet maintains insertion order 252 | and treeSet maintains sorting order of elements. 253 | 254 | And talking about internal implementations, 255 | HashSet is backed by HashMap.. 256 | whereas LinkedHashSet is implemented using HashSet and LinkedList. 257 | And TreeSet, it is backed up by navigableMap and it internally uses TreeMap. 258 | 259 | Next difference is about way of comparing things, 260 | like HashSet and LinkedHashSet uses equals() for comparison 261 | and TreeSet uses compareTo() method for maintaining ordering. 262 | This was all about differences between them. 263 | 264 | Can we add a null element to TreeSet and HashSet? 265 | We can add a null element in HashSet but not in treeSet. 266 | 267 | 👉🏻 TreeSet uses compareTo() method to compare objects with each other, if any element will be null 268 | by any chance, it will throw NullPointerException. 269 | 270 | What is difference between poll() and remove() methods of Queue? 271 | Both of these methods are used to remove element and returns the head of the queue. The difference is, 272 | 273 | -> if the queue is empty and we call the remove() method, then it will throw exception, 274 | but if we call poll() method, it will return null. 275 | 276 | What is the difference between remove() method of Collection and remove() method of Iterator? 277 | Collection.remove() is used for removing object from collection, while not iterating. 278 | 279 | -> When we use this remove() method to remove element at the time of iteration then it may throw 280 | ConcurrentModificationException. 281 | 282 | -> Iterator.remove() is advised to use for remove element while iterating. 283 | 284 | How HashMap works in Java? 285 | 286 | Whats the difference between HashMap and HashTable? 287 | 288 | Can we use a Custom object as a key in HashMap? If yes then How? 289 | Yes! we may create custom object key for HashMap. 290 | -> for that we need to override the equals() and hashcode() method to the Class which we want to use 291 | as key. 292 | 293 | Why it is suggetsed to have immutable objects as keys in hashMap? 294 | //why string is popular hasmap key in java? 295 | -> if we want to use custom object as key, we need to ensure that the hashcode() of the key of hashMap 296 | does not change. If it happens then it is impossible to get object value from that key. 297 | 298 | What is the contract of equals() and hashCode() method? 299 | 👉🏻 If two objects are equal, then they must have the same hashcode. 300 | 👉🏻 if two objects have the same hash code, then they may or may not be equal. 301 | 302 | //Equal objects must produce same hashcode 303 | //a.equals(b) -> true then a.hashCode() = b.hashCode() 304 | 305 | //unequal objects need not produce same hashcode 306 | //a.equals(b) -> false then a.hashCode() = b.hashCode() -> true 307 | //a.equals(b) -> false then a.hashCode() = b.hashCode() -> false 308 | 309 | What is the NavigableMap? 310 | 311 | What is the difference between HashMap and HashSet in java? 312 | 👉🏻 HashMap is collection of key-value pairs whereas HashSet is an un-ordered collection of unique 313 | elements! 314 | 315 | What are IdentityHashMap and WeakHashMap? How they are different? 316 | 317 | When to use HashMap and when to use TreeMap? 318 | 👉🏻 HashMap is the best implementation of Map for inserting, deleting, and locating elements. 319 | 320 | 👉🏻 TreeMap is the better alternative if we need to traverse the keys in a sorted order. 321 | 322 | -> HashMap is faster than TreeMap; for sorted key traversal, it is faster way to add elements to a 323 | HashMap, and then convert the map to a TreeMap. 324 | 325 | 326 | //Concurrent Collections 327 | //java.util.concurrent v5 328 | 329 | What is iterator's fail-fast property? 330 | While iterating over any collection, we cannot perform any modification on elements. 331 | Whenever we access the next element in collection, Iterator's fail fast property checks for any 332 | modification in the structure of that collection.' 333 | -> If any modifications found, it throws RuntimeException. 334 | 335 | 👉🏻 Almost all the implementations of the iterator, are fail-fast by design. 336 | ** Except the concurrent collection classes. 337 | 338 | What are Concurrent Collection classes? When does ConcurrentModificationException occur? 339 | The Concurrent Package [java.util.concurrent] which introduced in java 1.5, 340 | contains thread-safe collection classes called Concurrent Collection class: 341 | -> that allows collections to be modified while iterating. 342 | 343 | By design, iterator implementation are fail fast and throw the ConcurrentModificationException 344 | whenever we modify element while iterating. 345 | 346 | -> Iterator implementations in Concurrent Package allows us to do the modifications at runtime too. 347 | 348 | 1. CopyOnWriteArrayList 2. ConcurrentHashMap 3. CopyOnWriteArraySet. 349 | 350 | What is the difference between fail-fast and fail safe? 351 | 352 | What is the difference between Synchronized Collection and concurrent collection? 353 | Synchronized collections classes, like Hashtable and Vector provides thread-safe implementation of Map 354 | and List. 355 | 356 | There are several factors which make them less suitable for use in highly concurrent applications. 357 | 358 | Performance: The synchronized collections are unsuitable because of their 'wide-locking mechanism'. 359 | They acquire lock on complete object whereas concurrent classes locks only a part. 360 | 361 | When do we use ConcurrentHashMap in Java? 362 | 363 | Can we replace HashTable with ConcurrentHashMap? 364 | Yes, we can replace the HashTable with ConcurrentHashMap. 365 | -> As the performance of ConcurrentHashMap is better than HashTable. 366 | 367 | We need to be careful with code which relies on locking behavior of Hashtable. 368 | Since Hashtable locks whole Map instead of a portion of Map, compound operations like 369 | if(Hashtable.get(key) == null) put(key, value) works in Hashtable but not in concurrentHashMap. 370 | 371 | What is CopyOnWriteArrayList? How it is different than ArrayList? 372 | 373 | 374 | What is BlockingQueue? 375 | 376 | -------------------------------------------------------------------------------- /Design-Patterns.java: -------------------------------------------------------------------------------- 1 | 2 | What is a design pattern ? 3 | Design patterns is the basket of pre-designed solutions to common problems in Object Oriented programming 4 | given by various programmers in the world. 5 | They promote reusability which leads to a more robust and maintainable code. 6 | 7 | In how many catogories Design Patterns are classified?⭐️ 8 | The Design patterns can be classified into three main categories: 9 | Creational Patterns 10 | Structural Patterns 11 | Behavioral Patterns 12 | 13 | A Class Instance Can Be Created Using New Operator. Why Should We Use Creational Design Patterns To Create Objects?⭐️ 14 | 15 | In scenarios where the nature of the object can change according to the nature of the program, 16 | that is where we are not sure about which class's object we are going to create each time. 17 | we use creational design patterns which offer flexible approach for creating class instances. 18 | 19 | Which Object Oriented Method Is Used By The Creational Patterns To Instantiate Object? 20 | Creational patterns use inheritance. 21 | 22 | What is Singleton Pattern in Java?⭐️ 23 | Singleton pattern is a creational pattern which allows only one instance of a class to be created 24 | which will be available to the whole application. 25 | The major advantage of Singleton design pattern is that it always saves memory because 26 | the single instance is reused again and again. There is no need to create a new object at each request. 27 | For example, we can use a single database connection shared by multiple objects, 28 | instead of creating a database connection for every request. 29 | 30 | Java.lang.Runtime is a classical example of Singleton design pattern 31 | 32 | How can we create thread-safe singleton in Java? 33 | There are multiple ways to write thread-safe singleton in Java 34 | e.g 35 | by writing singleton using double checked locking, 36 | by using static Singleton instance initialized during class loading. 37 | By using Java enum to create thread-safe singleton is most simple way. 38 | 39 | What are the drawbacks of using singleton design pattern? 40 | The major drawbacks of using singleton design pattern are: 41 | a)Singleton causes code to be tightly coupled. 42 | 43 | b)They hide dependencies instead of exposing them. 44 | 45 | c)Singleton Pattern does not support inheritance. 46 | 47 | d)Singleton principle can be violated by techniques such as cloning. 48 | 49 | How To Prevent Cloning Of A Singleton Object? 50 | Throw exception within the body of clone method. 51 | 52 | Why and When Will You Use A Factory Pattern? 53 | Why: 54 | Factory classes provide flexibility in terms of design. Below are some of the benefits of factory class: 55 | •Factory design pattern results in more decoupled code as it allows us to hide creational logic from dependant code 56 | •It allows us to introduce an Inversion of Control container 57 | •Factory pattern’s main benefit is increased level of encapsulation while creating objects. 58 | If you use Factory to create object you can later replace original implementation of Products or classes 59 | with more advanced and high performance implementation without any change on client layer. 60 | 61 | When: 62 | - a class does not know which objects of class it must create 63 | - factory pattern can be used where we need to create an object of any one of sub-classes depending 64 | on the data provided 65 | 66 | What is the difference between factory and abstract factory design pattern?⭐️ 67 | Both factory and abstract factory are creational design patterns. 68 | 69 | The major difference between these two is, a factory pattern creates an object through inheritance 70 | and produces only one Product. 71 | On the other hand, an abstract factory pattern creates the object through composition 72 | and produce families of products. 73 | 74 | What is observer design pattern in Java? When it is used? 75 | Observer design pattern is one of the behavioral design patterns 76 | which defines one-to-many dependencies between objects & is useful 77 | when we are interested in a state of an object and 78 | we want to get notified when there is any change in state of Object. 79 | In Observer design pattern, when one object changes its state, 80 | all its dependent objects are automatically notified, 81 | the object is called Subject and dependants are called Observers. 82 | Java provides libraries to implement Observer design pattern using java.util.Observable class 83 | & java.util.Observer interface. 84 | 85 | Which design pattern will you use to create a complex object? 86 | Builder design pattern is used to construct a complex object. 87 | It is designed to solve the issues with factory and abstract design pattern. 88 | 89 | Give example of decorator design pattern in Java ? Does it operate on object level or class level ?⭐️ 90 | 91 | The decorator pattern, also known as a structural pattern is used to add additional functionality 92 | to a particular object at runtime. It wraps the original object through decorator object. 93 | For example, when you are buying a burger, you can customize it by adding extra filling and sauces, 94 | now the cost of these items have to be added to the final price. 95 | The customization will differ from customer to customer and offer from a shop. 96 | Creating different classes of burger with different fillings will end up creating a lot of classes. 97 | Decorator solves this problem by extending the functionality of single Burger class at runtime based 98 | on customer request. 99 | 100 | What is the benefit of using prototype design pattern over creating an instance using the new keyword?⭐️ 101 | Sometimes, object creation is heavyweight and requires a lot of resources, 102 | creating a new instance will impact the performance. 103 | In such cases, a prototype design pattern is used which refers to creating duplicate objects. 104 | In prototype design pattern, if a similar object is already present then 105 | cloning is done keeping performance in mind. 106 | 107 | What is MVC design pattern ? Give one example of MVC design pattern ? 108 | MVC stands for Model-View-Controller Pattern. We can use this pattern for better organization of code. 109 | 110 | Model : Model layer is layer which interacts with datdabase. Model is the data layer. 111 | So, The model is responsible for managing the data of the application. 112 | 113 | view : The view means presentation of the model in a particular format. 114 | It is what the user interacts with (the Front-end ). 115 | 116 | Controller : user request first enters the controller . 117 | Controller works between model and view.. 118 | The controller responds to the user input and performs interactions on the data model objects. 119 | The controller receives the input, optionally validates it and then passes the input to the model. 120 | 121 | What is FrontController design pattern in Java ? Give an example of front controller pattern ? 122 | The FrontController Design Pattern provides a centralized request handling mechanism 123 | so that, all the requests are handled by a single handler. 124 | 125 | FrontController is a centralized entry point for handling requests. 126 | 127 | So FrontController pattern is generally used to do the authentication or authorization or tracking of request and 128 | then pass the requests to corresponding handlers using the Dispatcher. 129 | FrontController redirects the request to dispatcher and dispatcher identifies the handler which can handle the request 130 | 131 | What is Chain of Responsibility design pattern ? 132 | the chain of responsibility pattern creates a chain of receiver objects for a request. 133 | It is one of the behavior pattern in which a objects are chained together in a sequence. 134 | and a responsibility or we can say a request is provided in order to be handled by the group 135 | that means it decouples sender and receiver of a request based on type of request. 136 | So, In this pattern, normally each receiver contains reference to another receiver. 137 | If one object cannot handle the request then it passes the same to the next receiver and so on. 138 | 139 | What is Adapter design pattern ? 140 | Adapater is actully used to facilitate the communication between two subjects, 141 | when they are not able to understand each other. 142 | 143 | Adapter design pattern works as a bridge between two incompatible interfaces. 144 | This pattern involves a single class called adaptor between two incompatible interfaces. 145 | 146 | Or 147 | 148 | Adapter allows two classes of a different interface to work together, 149 | without changing any code on either side. 150 | 151 | Difference between strategy and state design pattern in Java?⭐️ 152 | Strategy Design Pattern : 153 | Strategy design pattern used when we have multiple solution or algos to solve a specific task 154 | and at runtime client decides the specific implementation which is to be used. 155 | 156 | The Strategy pattern suggests keeping the implementation of each of the algorithms in a separate class. 157 | Each such algorithm encapsulated in a separate class is referred to as a strategy. 158 | An object that uses a Strategy object is often referred to as a context object. 159 | 160 | 161 | State Design Pattern : 162 | State design pattern used to alter an object's behaviour when its internal state changes. 163 | State Design pattern is useful, 164 | in the case of an object of a class that has some or all of its behaviour completely influenced 165 | by its current state or internal state. 166 | and that class is referred to as a Context class. 167 | A Context object can alter its behaviour when there is a change in its internal state and 168 | is also referred as a Stateful object. 169 | 170 | What is null Object Pattern? 171 | In Null Object pattern, a null object replaces check of NULL object instance. 172 | Instead of using a null reference to convey absence of an object (for instance, a non-existent customer), 173 | one uses an object which implements the expected interface, but whose method body is empty. 174 | The advantage of this approach over a working default implementation is that 175 | a null object is very predictable and has no side effects: it does nothing. 176 | 177 | Can you name few design patterns used in standard JDK library?⭐️ 178 | 179 | Builder 180 | java.lang.StringBuilder#append() 181 | 182 | Factory method 183 | java.util.Calendar#getInstance() 184 | 185 | Prototype 186 | java.lang.Object#clone() (the class has to implement java.lang.Cloneable) 187 | 188 | Singleton 189 | java.lang.Runtime#getRuntime() 190 | java.lang.System#getSecurityManager() 191 | 192 | Decorator 193 | All subclasses of java.io.InputStream, OutputStream, Reader and Writer 194 | have a constructor taking an instance of same type. 195 | 196 | Observer (or Publish/Subscribe) 197 | All implementations of java.util.EventListener (practically all over Swing thus) 198 | 199 | What Are J2ee Patterns? 200 | These design patterns are specifically concerned with the presentation tier. 201 | These patterns are identified by Sun Java Center. 202 | -------------------------------------------------------------------------------- /Design-Principle.java: -------------------------------------------------------------------------------- 1 | 2 | //Design Principles 3 | 4 | What are Software Design Principles? 5 | Software design principles represent a set of guidelines that helps us to avoid having a bad design. 6 | According to Robert Martin there are 3 important characteristics of a bad design that should be avoided: 7 | - Rigidity 8 | - Fragility 9 | - Immobility 10 | 11 | 12 | What are SOLID principles? 13 | S -> Single Responsibility Principle 14 | O -> Open/closed Principle 15 | L -> Liskov substitution principle 16 | I -> Interface Segregation Principle 17 | D -> Dependency Inversion Principle. 18 | -------------------------------------------------------------------------------- /ExceptionHandling.java: -------------------------------------------------------------------------------- 1 | 2 | What is Exception in Java?⭐️ 3 | Exception is an error event that can happen during the execution of a program 4 | and disrupts it’s normal flow. 5 | 6 | What is the difference between Exception and Error? 7 | An Error "indicates serious problems that a reasonable application should not try to catch." 8 | An Exception "indicates conditions that a reasonable application might want to catch." 9 | 10 | What are Compile Time Errors, Compile Time Exception, Runtime errors and Runtime Exceptions ?⭐️⭐️ 11 | So on this question let me be very specific..because a lot of people get confused when they listen these terms . 12 | If you see the exception heirarchy 13 | all the classes are child of Throwable and see..we have Exception and error. 14 | 15 | What is difference between Checked and Unchecked Exception in Java ? Explain Exception heirarchy. 16 | Main difference between Checked and Unchecked Exception lies in their handling. 17 | Checked Exception requires to be handled at compile time using try, catch and finally keywords 18 | or else compiler will flag error. 19 | This is not a requirement for Unchecked Exceptions. 20 | Also all exceptions derived from java.lang.Exception classes are checked exception, 21 | exception those which extends RuntimeException, these are known as unchecked exception in Java. 22 | You can also check next article for more differences between Checked and Unchecked Exception. 23 | 24 | All Exceptions are Java Objects and falls under Throwable class. 25 | Other than the exception class there is another subclass called Error which 26 | is derived from the Throwable class. 27 | Errors are abnormal conditions that happen in case of severe failures, these 28 | are not handled by the Java programs. 29 | For example the Exception class has these subclasses: 30 | IOExceptionclass, AWTException class, SQLException class, 31 | InterruptedExceptionclass and RuntimeException Class. 32 | 33 | Again Note that : Errors are also unchecked Exceptions because we can't handle them.⭐️ 34 | 35 | What is similarity between NullPointerException and ArrayIndexOutOfBoundException in Java? 36 | Both of them are example of unchecked exception and derived form RuntimeException. 37 | 38 | Which of the following combinations are correct or incorrect? 39 | 40 | What is difference between throw and throws keyword in Java? 41 | throw keyword is used to throw exception explicitly from any method or static block 42 | while throws keyword is used in method declaration, it denotes which exception can possiblly be thrown by this method. 43 | throw is followed by an instance while throws is followed by exception class name. 44 | 45 | How exception is propagated? What is default exception handling?⭐️ 46 | An exception is first thrown from the top of the stack, if it is not caught, 47 | it drops down the call stack to the previous method and so on until they are caught or until they reach the very bottom of the call stack that means up to main method. 48 | This is called exception propagation. 49 | 50 | What is Exception chaining in Java? 51 | Exception chaining is a popular exception handling concept in Java, 52 | where another exception is thrown in response of an exception and creating a chain of Exceptions. 53 | This technique mostly used to wrap a checked exception into an unchecked or RuntimeException. 54 | 55 | How to write custom Exception in Java?why we use custom or user defined exceptions?⭐️ 56 | Customized exceptions or user defined exceptions are the exceptions which are created by Programmer to achieve programming requirements. 57 | In java we can create our own exceptions, by creating class under Exception hirearchy, and throw them on a particular condition. 58 | We can define exceptions checked or unchecked, by extending Exception or RuntimeException. 59 | Making custom exception checked, will bound us to handle those exceptions. 60 | And if Custom exception are unchecked, we can simply throw them, hence these exceptions should be defined as unchecked. 61 | 62 | Does code form finally executes if method returns before finally block or JVM exits ? 63 | finally block in Java executes even when return keyword is used in try block. 64 | but when you call System.exit(0) from try block, it will not execute. 65 | 66 | What is difference in final, finalize and finally keyword in Java?⭐️ 67 | Final class can't be inherited, 68 | final method can't be overridden and 69 | final variable value can't be changed. 70 | 71 | Finally is used to place important code, 72 | it will be executed whether exception is handled or not. 73 | 74 | Finalize is used to perform clean up processing just before object is garbage collected. 75 | 76 | What is the purpose of using multiple catch Blocks? can we catch Exception before FileNotFoundException? 77 | We can catch different exceptions by using multiple catch blocks in a proper hierarchy. 78 | For example you have to handle more than one Exception 79 | that may be thrown from the code written inside the try block, 80 | then that can be handled by two diff catch blocks, 81 | 82 | we can not catch exception first because its higher in heirarchy than FlieNotFoundException. 83 | So we catch the most specific first. 84 | In case, there is not parent-child relation or if Exceptions we are catching are at same level in heirarchy 85 | then order does not matter. 86 | 87 | What is Java 7's multi-catch block? 88 | if we catch a lot of exception in a single try block, the catch block code looks very ugly, 89 | That is why, to reduce length of code, 90 | we can use a single catch with multiple exception seperated by single pipelines if handling for all of 91 | those exceptions is going to be same. 92 | This is taken as an improvent or enhancement in java 1.7. 93 | Hence, Single catch block can be written to handle different type of exceptions 94 | and it is called multi-catch block. 95 | 96 | What is Java 7's automatic resource management Feature?⭐️ 97 | Basically try with resources is a try statement that declares one or more resources. 98 | It ensures that each resource that we used in our program is closed at the end of try block. 99 | so it is like an alternate of finally block, which we use for the same purpose. 100 | In ARM We are not responsible to close the resource. 101 | 102 | What best practices you follow while doing Exception handling in Java ?⭐️ 103 | 1. is To clean up the resources gracefully after using them. 104 | 2. Always correctly wrap the exceptions in custom exceptions so that stack trace is not lost 105 | 3. Exception handling should be used wisely -no overuse 106 | 4. we can Either log the exception or throw it but never do the both. 107 | 5. Logging Exception 108 | 6. define exception handling strategy at the design time 109 | 7. Know when to Throw checked and when to throw unchecked exception 110 | 8. Throw exception as early as possible 111 | 9. Catch late / catch as early as we know how to handle the issue properly 112 | 113 | DeliverGifts 114 | packGifts 115 | giftSelector 116 | GiftManufecturer 117 | 118 | What is wrong with following code in Java: 119 | 120 | public class SuperClass { 121 | public void start() throws IOException{ 122 | throw new IOException("can't operate on file"); 123 | } 124 | } 125 | 126 | public class SubClass extends SuperClass{ 127 | public void start() throws Exception{ 128 | throw new Exception("Not able to start"); 129 | } 130 | } 131 | 132 | In this code compiler will complain on sub class where start() method gets overridden. 133 | As per rules of method overriding in Java, an overridden method can not throw Checked Exception 134 | which is higher in hierarchy than original method. 135 | Since here start() is throwing IOException in super class, start() in sub class can only 136 | throw either IOException or any sub class of IOException but not super class of IOException e.g. Exception. 137 | 138 | What is wrong with following Java Exception code: 139 | 140 | public static void start(){ 141 | System.out.println("Executing start!"); 142 | } 143 | 144 | public static void main(String args[]) { 145 | try{ 146 | start(); 147 | }catch(Exception e){ 148 | e.printStackTrace(); 149 | } 150 | } 151 | 152 | IOException is a checked Exception 153 | and start() method doesn't throw IOException, 154 | so compiler will flag error as "exception java.io.IOException is never thrown in body of corresponding try statement", 155 | but if you change IOException to Exception compiler error will disappear 156 | because Exception can be used to catch all RuntimeException which doesn't require declaration in throws clause 157 | because compiler can not check for RuntimeExceptions. 158 | -------------------------------------------------------------------------------- /Generics.java: -------------------------------------------------------------------------------- 1 | 2 | What is Generics in Java ? why we should use Generics?⭐️ 3 | //benefits of using Generics? 4 | Simply stating generics is a mechanism for type checking at compile time 5 | Code that uses generics has many benefits over non-generic code: 6 | 7 | 1) Stronger type checks at compile time: 8 | A Java compiler applies strong type checking to generic code 9 | and issues errors if the code violates type safety. 10 | Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find. 11 | 12 | 2) Code Reusability 13 | 14 | 3) Elimination of casts: 15 | prior to Java 5 , to get the element back from collection we had to cast it back to correct Type before using it. 16 | But now If you use generics, then explicit type casting is not required anywhere. 17 | 18 | 4) Enabling programmers to implement generic algorithms: 19 | By using generics, programmers can implement generic algorithms that work on collections 20 | of different types, can be customized, and are type safe and easier to read. 21 | 22 | Which exception we get if we cast an element to wrong type? 23 | ClassCastException 24 | 25 | Can we generify a static method? Can we have a static varible of generic type? 26 | NO. 27 | 28 | What are generic types? 29 | A generic type is a generic class or interface that is parameterized over types. 30 | 31 | Can a generic type extend or implement a non-generic type? 32 | Yes. 33 | 34 | public class GenericClass extends NonGenericClass{ 35 | 36 | } 37 | 38 | public class GenericClass implements NonGenericInterface{ 39 | 40 | } 41 | 42 | public class GenericClass extends RawTypeClass{ 43 | 44 | } 45 | 46 | public class GenericClass implements RawTypeInterface{ 47 | 48 | } 49 | 50 | Can a non-generic type extend or implement a generic type? 51 | Only if we parametrize the with a specific type. 52 | 53 | public class NonGenericClass extends GenericClass{ ❌ 54 | 55 | } 56 | 57 | public class NonGenericClass extends GenericClass{ 💯 58 | 59 | } 60 | 61 | 62 | public class NonGenericClass implements GenericInterface{ ❌ 63 | 64 | } 65 | 66 | public class NonGenericClass implements GenericInterface{ 💯 67 | 68 | } 69 | 70 | What is a Raw-Type?⭐️ 71 | Raw-Type is a generic-type without any type argument. 72 | ArrayList l = new ArrayList(); 73 | 74 | Difference between List and raw type List.⭐️ 75 | List listOfRawTypes = new ArrayList(); 76 | listOfRawTypes.add("abc"); 77 | listOfRawTypes.add(123); //compiler will allow this - exception at runtime 78 | String item = (String) listOfRawTypes.get(0); //explicit cast is required 79 | item = (String) listOfRawTypes.get(1); //ClassCastException because Integer can not be cast in String 80 | 81 | List listOfString = new ArrayList<>(); 82 | listOfString.add("abcd"); 83 | listOfString.add(1234); //compiler error, better than runtime Exception 84 | item = listOfString.get(0); //no explicit casting is required - compiler auto cast 85 | 86 | Can a generic Type have more than 1 type parameters?⭐️ 87 | yes, We can create classes having mutiple type parameters. 88 | a generic type can have multiple type parameters. 89 | Example: Hashmap 90 | 91 | Can we add elements of subtype to an object of super type?⭐️ 92 | //Type compatibility //Substitution Principle 93 | Yes , if the types are compatible, you can add the elemets or objects. 94 | Example: 95 | List l = new ArrayList<>(); 96 | you can add integer to it. Because Integer is sub-type of Number. 97 | 98 | Is sub-typing possible in java?⭐️⭐️ 99 | //sub-typing 100 | As long as you do not vary the type argument, the subtyping relationship is preserved between the types 101 | else there is no such thing as sub-typing. 102 | 103 | ArrayList is a sub Type of List. 104 | 105 | List list = ArrayList(); 106 | So, 107 | ArrayList is also a SubType of List 108 | because types are same. 109 | But, 110 | 111 | List list = ArrayList(); ❌ 112 | ArrayList is not a sub type of List. 113 | 114 | Also, 115 | ArrayList al = Arraylist(); ❌ 116 | As we know this is also Not possible, Both Type Arguments should be same. 117 | 118 | How to write a generic method? When should we use generic method?⭐️ 119 | 120 | public void GenericMethod(List l){ 121 | 122 | } 123 | When the class does not have multiple area to use the type parameter, 124 | i.e., when we are not needed to generify the whole class then we can generify the perticular method only. 125 | 126 | Can we generify constructor? 127 | As constructors are also special kind of methods, we can generify them. 128 | 129 | Can we use Generics with Array? 130 | No. 131 | 132 | What are bounded types? How to Bound a Type parameter?⭐️ 133 | There may be times when you'll want to restrict the kinds of types 134 | that are allowed to be passed to a type parameter. 135 | For example, a method that operates on numbers might only want to accept instances 136 | of Number or its subclasses. This is what bounded type parameters are for. 137 | 138 | To declare a bounded type parameter, 139 | While creating a generic type or a generic method, 140 | list the type parameter's name, followed by the extends keyword, followed by its upper bound. 141 | 142 | 143 | 144 | 145 | Class: 146 | 147 | class MyClass{} 148 | 149 | Interface: 150 | 151 | interface MyInterface{} 152 | 153 | Method: 154 | 155 | public void method(List li){ 156 | 157 | } 158 | 159 | What is type inference?⭐️ 160 | Type inference is a Java compiler's ability to look at each method invocation and corresponding 161 | declaration to determine the type argument (or arguments) that make the invocation applicable. 162 | The inference algorithm determines the types of the arguments and, if available, the type that 163 | the result is being assigned, or returned. Finally, the inference algorithm tries to find the 164 | most specific type that works with all of the arguments. 165 | 166 | What are Wild Cards in generics?⭐️ 167 | In generic code, the question mark (?), called the wildcard, 168 | It represents an unknown type. 169 | The wildcard can be used in a variety of situations: 170 | as the type of a parameter, field, or local variable; sometimes as a return type 171 | (though it is better programming practice to be more specific). 172 | 173 | What is Bounded and Unbounded wildcards in Generics ? 174 | represent unbounded type where there is no bound. 175 | 176 | Bounded Wildcards are those which impose bound on Type. 177 | there are two kinds of Bounded wildcards 178 | which impose an upper bound by ensuring that type must be sub class of UpperBound class and 179 | where its imposing lower bound by ensuring Type must be super class of LowerBound class. 180 | 181 | Can we have more than one Bound? 182 | With type parameters we can have more than one bound but with wildCards we can not. 183 | 184 | What are the restrictions on wildcards? 185 | 186 | can we use Type parameters and wildcards as return type? 187 | yes. But wildcard can not be used as the direct return type. 188 | 189 | How Generics works in Java? What is type erasure?⭐️ 190 | 191 | Can you pass List to a method which accepts List 192 | No, 193 | 194 | List objectList; 195 | List stringList; 196 | 197 | objectList = stringList; //compilation error incompatible types 198 | 199 | Difference between List and raw-type List in Java? 200 | Main difference between raw type and parametrized type List is that, 201 | compiler will not check type-safety of raw type at compile time but it will do that 202 | for parametrized type and by using Object as Type it inform compiler that 203 | it can hold any Type of Object e.g. String or Integer. 204 | 205 | Difference between List and List in Java? 206 | List is List of unknown type while List is essentially List of any Type. 207 | You can assign List, List to List but you can not assign List to List. 208 | 209 | List listOfAnyType; 210 | List listOfObject = new ArrayList(); 211 | List listOfString = new ArrayList(); 212 | List listOfInteger = new ArrayList(); 213 | 214 | listOfAnyType = listOfString; //legal 215 | listOfAnyType = listOfInteger; //legal 216 | listOfObjectType = (List) listOfString; //compiler error - in-convertible types 217 | -------------------------------------------------------------------------------- /Inner-classes.java: -------------------------------------------------------------------------------- 1 | 2 | What is Inner class? 3 | Any Class which is not a top level Class or any Class which is declared inside another Class 4 | is Inner class. 5 | 6 | class OuterClass{ 7 | class InnerClass{ 8 | public void display(){ 9 | System.out.println("Inner class."); 10 | } 11 | } 12 | } 13 | 14 | What are the types of Inner classes?⭐️ 15 | There are following types of such classes: 16 | 1. Member Inner class | Regular Inner class 17 | 2. Local Inner class 18 | 3. Anonymous Inner Class 19 | 4. Static Nested Class 20 | 21 | What is Member Inner Class?⭐️ 22 | Member Inner Class is just regular inner Class which is not static member of the outer class. 23 | It acts as other instance member of that class. 24 | 25 | class OuterClass{ 26 | class InnerClass{ 27 | public void display(){ 28 | System.out.println("Inner class."); 29 | } 30 | } 31 | } 32 | 33 | -> Class Inner behaves as instance member of this Class Outer. 34 | -> To access this class, we must create the object of Outer Class. 35 | 36 | The Member inner classes can be private protected public final abstract etc. 37 | 38 | What is the difference between Static nested Class and Member Inner class?⭐️ 39 | 40 | Static Nested Class is the Class which is declared inside another Class with static modifier. 41 | 42 | class Demo{ 43 | static class Nested{ 44 | public void method(){ 45 | System.out.println("Static Nested class."); 46 | } 47 | } 48 | } 49 | 50 | 👉🏻 To create the instance of Member Inner class, an instance of Outer Class is required. 51 | Whereas static nested Class does not require any outer Class instances. It can be Accessed just 52 | like other static members of that class. 53 | 54 | Demo.Nested obj = new Demo.Nested(); 55 | Obj.method(); 56 | 57 | 👉🏻 In Member Inner class/ Non-static Nested class, we can access all the static and instance variables of the outer class. 58 | Whereas, inside static nested class, we can only access the static variables of outer class. 59 | 60 | 👉🏻 We can not declare static methods inside Regular inner classes whereas in static nested classes, 61 | we can do so. 62 | So we can declare main method in static nested class, whereas in regular inner classes we cannot. 63 | 64 | 👉🏻 We can Import Nested Static Class with static import, whereas we normally Import the non 65 | static nested classes. 66 | 67 | What are Local Inner Classes?⭐️ 68 | Local inner classes are those classes which are declared inside a code block or a method. 69 | 70 | class Main{ 71 | private String info = "Outer Class Member"; 72 | 73 | public void method1(){ 74 | class Printer{ 75 | public void printInfo(){ 76 | System.out.println(info); 77 | } 78 | } 79 | } 80 | } 81 | 82 | -> Local inner classes can be used to define specific required functionality for that particular method. 83 | 84 | 👉🏻 Local Inner Class is a member of the method, so their scope is limited to that particular 85 | method only; Local inner classes are the most rarely used inner classes. 86 | 87 | Can we access local variable of the wrapping method inside local inner class? 88 | Yes, we can access final or non-final local variables in local inner class, But We can not modify them. 89 | If we Try to modify them, compiler will raise error. 90 | 91 | What access modifiers can be used with Local inner classes? 92 | Local inner is the local member of method, so it can not be declared as public private protected. 93 | 👉🏻 Local inner classes can only be final or abstract. 94 | 95 | What is Anonymous Inner class?⭐️⭐️ 96 | Anonymous Inner Class is a Class which does not have name to reference and initialised at the same 97 | place where it gets created. 98 | 👉🏻 For anonymous inner classes, only a single object is created. 99 | 100 | Note: An Anonymous Inner Class always extend a Class or implement an interface. 101 | 102 | When should we use Anonymous inner classes? 103 | -> An Anonymous Inner Class can be used while making an instance of an object with certain additional 104 | functionalities such as overloading methods of a class, or interface, without having actually any 105 | subclass. 106 | 107 | For example, Anonymous inner classes are common to extend Thread Class in order to override run method. 108 | 109 | Similarly we can also create anonymous inner class, by implementing runnable interface. 110 | 111 | -> Also Anonymous inner classes can be frequently used in GUI based applications for event handling. 112 | We can write implementation classes for listener interfaces in graphics programming using them.. 113 | 114 | Can we create constructor in anonymous inner class? 115 | We know the constructor has the same name as of the class. We can create constructor explicitly in 116 | all other types of inner classes and static nested class. 117 | 118 | But in the case of Anonymous inner class, we do not have the name of the class. 119 | 👉🏻 We cannot write any constructor explicitly in anonymous inner class. 120 | 121 | What are differences between an Anonymous Inner Class and a normal class? 122 | Both are different in many ways: 123 | 124 | 1. A normal Class can extend one Class and implement many interfaces at the same time, whereas 125 | the Anonymous Inner Class can either extend one Class or implement one Interface at a time. 126 | 127 | 2. We write constructors in normal class, which are invoked at the time of instance creation. 128 | But we cannot write any constructor in anonymous inner class. 129 | 👉🏻 These classes are initialised at the time of creation itself with the default constructor. 130 | 131 | 3. We write normal classes for our standard requirements whereas we write anonymous inner classes 132 | when we do not need any separate Class for some temporary requirements, 133 | or when we need to provide implementations to methods for a single object. 134 | 135 | Can we have static members inside anonymous inner classes? 136 | No, we cannot declare static data members or static member function inside anonymous inner class. 137 | -> In-fact we can not define any static member inside any inner class. we can do so only in 138 | Static nested classes. 139 | 140 | What are the ways of creating Anonymous inner classes?⭐️ 141 | Ways to Create anonymous inner classes, 142 | 1. By extending a class: 143 | 144 | Thread t = new Thread(){ 145 | public void run(){ 146 | System.out.println("Anonymous inner Thread"); 147 | } 148 | }; 149 | t.start(); 150 | 151 | 2. By implementing an interface: 152 | 153 | Runnable r = new Runnable() { 154 | @Override 155 | public void run() { 156 | System.out.println("Runnable"); 157 | } 158 | } ; 159 | Thread th = new Thread(r); 160 | th.start(); 161 | 162 | 3. Defining inside any method or constructor argument: 163 | 164 | Thread t = new Thread(new Runnable(){ 165 | public void run(){ 166 | System.out.println("Child Thread"); 167 | } 168 | }}).start(); 169 | 170 | What are the advantages of inner classes? 171 | We use nested Class when it is useful to only one class. So keeping them together helps in the 172 | packaging of the classes. 173 | 174 | By using Inner classes we develop more readable and maintainable code, because it logically 175 | groups the classes in one place. 176 | 177 | With inner classes we can access outer Class private members and at the same time we can hide 178 | inner Class from the outer world. Inner classes implements encapsulation. 179 | 180 | We also optimize the code by writing inner classes as it requires less code to write. 181 | 182 | Can we write Nested Interface inside an Interface? 183 | Answer is Yes. 184 | When an Interface is required for one Interface only then we may write Interface inside Interface. 185 | 186 | for example, 187 | In Map Interface we have the Interface Entry, which is used for Map only. 188 | Entry represents a key-value pair inside map. 189 | 190 | 👉🏻 The inner interfaces which are declared inside Interface are always public and static, 191 | even if we do not make them public or static explicitly. 192 | 193 | 👉🏻 Inner interfaces can be implemented independently. 194 | 195 | Is it possible to define Interface inside Class or Class inside interface? 196 | Answer is Yes. Both cases are possible. 197 | 198 | If we define Interface inside class, it is always static. 199 | We can declare it as private public or protected according to our requirement. 200 | 201 | class Demo{ 202 | public interface Inner{ 203 | } 204 | } 205 | 206 | And if any Class is closely associated with any Interface then it may be defined inside the interface. 207 | 208 | For example, class EmailDetails is required for the interface EmailService. 209 | So we can define it inside this interface. 210 | 211 | interface EmailService{ 212 | public void sendMail(EmailDetails e); 213 | class EmailDetails{ 214 | .. 215 | .. 216 | } 217 | } 218 | 219 | Note: If we implement the Interface with its own inner Class then it is called as its default implementation. 220 | -------------------------------------------------------------------------------- /JVM Architecture.java: -------------------------------------------------------------------------------- 1 | -----JVM---- 2 | 3 | L1-00:40 What do you mean by Virtual Machine? 4 | A software program that simulates behaviour of a physical machine, which can perform operations 5 | like any other physical machine. For example, 6 | -> VMWare is the system based virtual machine 7 | -> JVM is the Application based virtual machine 8 | 9 | L1-01:17 What is JVM? 10 | "Java Virtual Machine" 11 | Basically JVM provides runtime environment in which Java programs are executed. 12 | First the java programs get compiled and converted into byte code. 13 | JVM is responsible for loading Class files and executing that byte code. 14 | 15 | -> What makes Java platform independent? Or what you mean by 'write once, run anywhere'?⭐️ 16 | JVM converts the byte code to the machine specific code i.e, 17 | one java program can be executed on any type operating system because of JVM. 18 | That is why we need different kinds of JVM for different Operating systems. 19 | 20 | L1-02:36 Is JVM, a compiler or interpreter ?⭐️ 21 | JVM is an interpreter. 22 | 23 | L1-02:45 What are JRE, JDK? how these are different from JVM?⭐️ 24 | JRE: JRE stands for Java runtime environment and JVM is actually an implementation of JRE. 25 | It consists of set of libraries like jar files and other files that JVM uses at runtime. 26 | so it is different from JVM as it only contains the environment to execute java program. 27 | 28 | JDK: The Java development kit consists more than JRE, as it provides all the tools which 29 | are used to develop java applications along with tools and executable required to compile, 30 | debug and execute java program. 31 | 32 | L1-04:25 How JVM works?⭐️ 33 | We know, JVM is a runtime engine to run the java applications.. when we write a java file.. 34 | the compiler creates the Class file having the byte code.. This .class file goes into various steps. 35 | 36 | L2-00:17 What is Classloader?⭐️ 37 | Class loader is a set of components which loads the classes during runtime into JVM. 38 | These classes are not loaded all at once, when the application requires that particular class or we can say 39 | when we try to use a Class, Java ClassLoader loads that class into memory. 40 | 41 | L2-00:43 What activities are performed by the classloader subsystem? 42 | Class loader subsystem is responsible to perform these three activities: 43 | 1.Loading 44 | 2.Linking 45 | 3.Initialization 46 | 47 | Loading: The classloader reads the class and generates the binary data. 48 | This binary data get stored inside method area. 49 | Method area - class related data gets stored. 50 | With all the class info, JVM creates an object of Type : java.lang.Class for that loaded class in 51 | heap area. 52 | This 'java.lang.Class' class object provides complete information for that class. 53 | 54 | 02:30 -> If we call a class more than once, will there be more than one java.lang.Class object for that 55 | class? 56 | NO. Even though we call the class multiple times but in the heap area there will be only one 57 | Class class object, because one Class class object for that particular class is enough to 58 | provide information for that class. For any new object the class information will remain same. 59 | 60 | Linking: It consists of three activities.. 61 | Verify 62 | Prepare 63 | Resolve 64 | 65 | Verification: Bytecode verifier ensures that code passed to java interpreter is in a fit state 66 | to be executed. 67 | This is also a reason why JAVA is secure.. 68 | 69 | Preparation: JVM allocates memory to class level variables and assign default values to them. 70 | 71 | Resolution: JVM replaces symbolic names with original memory references from method area. 72 | class Demo{ 73 | public static void public static void main(String[] args) { 74 | String s = ... 75 | Student s1 = new Student(); 76 | } 77 | } 78 | 79 | Constant Pool of Demo : Demo, String, Student 80 | In resolution, these names will get replaced with memory level references from method area. 81 | 82 | Initialization: -> Original value get assigned to the static variables. 83 | -> Static blocks get executed from parent to child and top to bottom in this phase. 84 | 85 | Note: While loading linking initialisation any error occurs, 86 | then we will get runtime exception saying java.lang.linkage error. 87 | 88 | L2-07:14 What are the different class loaders used by JVM? 89 | There are three diff class loaders, each of them has a predefined location from where they loads class. 90 | 91 | Bootstrap Class Loader | Primordial Class loader: 92 | 93 | It is responsible to load the classes which are present in bootstrap path (jdk->jre->lib->rt.jar) 94 | like, rt.jar.. 95 | rt.jar -> core java apis. 96 | so this Class loader loads the core java api classes. 97 | 98 | This Class loader is parent of all other class loaders in java. It is not implemented in java. 99 | 100 | Extension Class Loader: 101 | 102 | This Class loader is responsible to load classes from the extension path. (jre/lib/ext/'*'.jar) 103 | Extension Class loader is the implementation of Bootstrap Class loader. 104 | It is implemented by sun.misc.Launcher$ExtClassLoader 105 | 106 | Application Class loader | System Class loader: 107 | 108 | It is responsible for loading the classes from the CLASSPATH environment variable. 109 | This is the child class of Extension Class loader. 110 | It is implemented by sun.misc.Launcher$AppClassLoader. 111 | 112 | Note: Except the bootstrap classloader which is only implemented in native languages not in java, 113 | all the classloader are implemented using java.lang.ClassLoader. 114 | 115 | L2-09:28 How does JVM load the classes?⭐️ 116 | The classloader subsystem works on the delegation principle. One classloader delegates the 117 | responsibility for loading the class to their parent and if it doesn't work, then they loads the class 118 | by themselves 119 | 120 | What is the difference between static and dynamic class loading?⭐️ 121 | 122 | L2-12:30 What is difference between Class.forName() and ClassLoader.loadClass()?⭐️ 123 | Both methods try to load classes dynamically. 124 | 125 | The most common method is Class.forName(). By default the classes get initialised using this method. 126 | 127 | loadClass() is an instance method and requires a particular ClassLoader to load the class. 128 | 129 | By default the classes does not get initialised in this. 130 | 131 | //Memory Areas 132 | L3-00:12 What are the various memory areas present in JVM?⭐️ 133 | JVM has 5 different memory areas .. 134 | 1. Method area 135 | 2. Stack area 136 | 3. Heap area 137 | 4. PC Registers 138 | 5. Native method area 139 | 140 | L3-00:30 Which memory area is used to store Static variables? 141 | JVM stores the Class level information in the Method area. 142 | Class level information consists Class name, parent Class name, Method info, Variables info, 143 | Constructors, Modifiers info, Constant pool info etc. 144 | 145 | Whenever we start JVM, a method area gets created, 146 | 👉🏻 and that will be shared among all JVM threads. 147 | 148 | L3-01:14 When are the static variables loaded in memory? 149 | Static variables get loaded at the time of Class loading and gets stored in the method area. 150 | 151 | L3-01:31 What is Heap space in Java?⭐️ 152 | Heap memory in JVM is used to store objects and corresponding instance variables. 153 | 👉🏻 Whenever we create objects, it is always created in Heap space. 154 | 155 | Heap area gets created when we start JVM 156 | 👉🏻 Heap area is shared among all the threads. 157 | 158 | Method and heap area need not be continuous. 159 | 160 | L3-02:10 What is String pool?⭐️ 161 | String pool or string intern pool is a special storage area in Heap space. 162 | When we create a string, it gets stored to the string pool, so that if any other string will get 163 | created which exists in the pool then instead of creating new object, 164 | the reference of existing string will be returned. 165 | 166 | L3-03:04 What is Stack? What it stores?⭐️ 167 | Stack is a part of memory that stores each method call performed by that thread including primitives 168 | and local variables. 169 | 170 | 👉🏻 For every thread, a new runtime stack gets created.. 171 | 172 | L3-05:42 What is stack frame? What does it consist? 173 | Each entry in stack is called stack frame. 174 | 1. Local Variable Array 175 | -> Which store local variables and corresponding values related to any method. 176 | 2. Operand Stack 177 | -> It is a runtime workspace for JVM, to perform any intermediate operations. 178 | 3. Frame data 179 | -> All symbols corresponding to any method are stored here. 180 | 181 | 👉🏻 For every method call one stack frame is created. 182 | 183 | How stack and heap are interrelated?⭐️ 184 | We know Local variables are stored on the stack, and all the objects in java are stored on the 185 | Heap area. 186 | 👉🏻 For every object on the heap, there is a pointer which is the reference to that object. 187 | This reference variable is also stored on the stack. This is how Stack and heap are interrelated.. 188 | 189 | How to get information about heap memory? 190 | We know the java application can communicate directly with JVM via runtime class. 191 | Runtime Class provides various methods from which we can get information about memory. 192 | 193 | We create Runtime instance via method getInstance(), because this Class is Singleton class. 194 | 195 | Runtime r = Runtime.getInstance(); 196 | r.maxMemory(); 197 | //this method returns the maximum amount of memory that the Java virtual machine will attempt to use. 198 | 199 | r.totalMemory() //this returns the total amount of memory in the Java virtual machine. 200 | 201 | r.freeMemory(); //this returns the amount of free memory in the Java Virtual Machine. 202 | 203 | What happens when there is not enough Heap Space for storing new objects?⭐️ 204 | JVM tries to free up space but if it fails then JVM throws java.lang.OutOfMemoryError. 205 | 206 | How to set minimum and maximum heap size?? 207 | By using -Xmx we can specify the maximum heap size for any program.. 208 | And -Xms to set the minimum heap size.. 209 | 210 | $ java -Xms512m -Xmx1024m 211 | 212 | Why do member variables have default values whereas local variables do not have any default value ? 213 | In java, ClassLoader is responsible to load the Class and while loading the Class they initialize 214 | the static variable and blocks. 215 | 216 | JVM does not have any idea about local variables at the time of Class loading, therefore 217 | local variables do not have any default values. 218 | 219 | What PC registers are for? 220 | 👉🏻 Every thread has separate PC register. 221 | PC registers is used to hold the address of current executing instruction. when the instruction gets 222 | executed the PC register will be updated with the next one. 223 | 224 | What is Native Method Stack? 225 | It is another memory space of JVM which stores the native method information. 226 | 👉🏻 for every thread, there will be a separated native method stack. 227 | 228 | //Execution Engine 229 | 230 | What is Execution engine? What it does? 231 | Execution engine is the component in JVM which is responsible to execute the byte code which is 232 | assigned to the runtime data area. 233 | 234 | It has following sub-components: 235 | 1. Interpreter 236 | 2. JIT compiler 237 | 3. Garbage collector 238 | 239 | What is Interpreter? 240 | Interpreter is a program that reads byte code in the sequential manner (line by line). 241 | it runs the application by accepting file name argument from the command line, 242 | 243 | java 244 | 245 | What are the limitations interpreter has? 246 | Interpreter interprets fast but executes slow! 247 | The limitation is, when a code of block or one method is called multiple times, 248 | every time a new interpretation is required. 249 | 250 | What is JIT compiler?⭐️ 251 | It stands for Just-in-time compiler. 252 | It compiles those byte code parts which are having similar functionality at the same time. 253 | 254 | Sub components of JIT compiler: 255 | 1. Intermediate code generator: it produces intermediate code. 256 | 2. Code Optimizer: Responsible for optimizing that intermediate code. 257 | 3. Target code generator: Responsible for generating native code! 258 | 4. Profiler: Responsible for finding the hot code! It finds which method is called multiple times. 259 | 260 | What is Garbage collector? 261 | It is the component of Execution engine which frees up the memory by collecting and removing 262 | the unreferenced objects. 263 | 264 | // 265 | 266 | What is garbage collection? 267 | Garbage is unused and unreferenced objects, and Garbage collection is the process inside JVM which 268 | identifies and discards those objects which are no longer required in the application. 269 | 270 | ->It is a mechanism of JVM to reclaim heap space from objects which are eligible for garbage collection. 271 | 272 | Which objects are eligible for garbage collection? 273 | Any object on the heap which unreachable through a reference from the stack is eligible for garbage 274 | collection. 275 | 276 | Is programmer responsible to destroy objects?⭐️ 277 | No! In java programmer need not to worry for this. Garbage collector destroys the objects which are no 278 | longer in use. 279 | Before calling garbage collector, it is recommended to make the unused object available for garbage 280 | collection. 281 | 282 | How to make an object available for garbage collection?⭐️ 283 | There are 4 ways to do so, 284 | 285 | 1. Nullifying the reference variable: by doing so the object in heap will be unreachable from the stack. 286 | 287 | 2. Reassigning the reference variable: the variable gets assigned with new object and the older one gets 288 | unreferenced from stack.. 289 | 290 | 3. Object inside method: we know for every method call the stack has a stack frame, which consists of 291 | all of its members. When a method is executed the stack frame is popped out from 292 | stack and thus all of its members get unreferenced from the stack. 293 | 294 | 4. Creating anonymous object: we know an anonymous object is not referenced, so it is eligible for 295 | garbage collection. 296 | 297 | How to call garbage collector? 298 | The most common way to invoke garbage collector is by invoking gc method of system class. 299 | System.gc(); 300 | 301 | Other way is to invoke gc method with Runtime class. 302 | Runtime.getRuntime().gc(); 303 | 304 | This method suggests the JVM to recycle the unused objects in order to make the memory available for 305 | future allocation. 306 | 307 | Can you guarantee that invoking gc will definitely call garbage collector?⭐️ 308 | By invoking gc, we just request or suggest JVM to call garbage collector. But there is no guarantee 309 | that the Java virtual machine will do that. So answer is no! 310 | 311 | If an object reference is set to null, will the Garbage Collector immediately free the memory held by 312 | that object ? 313 | No, the object will be available for garbage collection in the next cycle of the garbage collector. 314 | 315 | When should we call garbage collector to run? 316 | When we are executing multiple blocks of code and after executing one block 317 | -> if we want to free the memory so that the next block of code may execute more efficiently 318 | -> if you are trying to get more accurate evaluation and want to start those code block with the same 319 | state as we started the very first block.. 320 | .. then we may call the gc. 321 | 322 | Why is it bad idea to run gc? 323 | As we know we can not guarantee that the garbage collector will process when we call gc, so we should 324 | just do not bother to do it. 325 | Because when we call gc, Garbage collection temporarily stops all threads in our application for running. 326 | When garbage collection takes place our application is temporarily suspended.. and it would not resume 327 | until the gc process complete. 328 | This 'stops the world!' That is, running garbage collection can cause an unacceptable freeze in 329 | execution. 330 | 331 | When is the finalize() method gets called? What is the purpose of calling it? 332 | Finalise method is a special method present in object class. That means every class can override this 333 | method. 334 | when we call the gc, it calls the finalise method before performing the clean up activity. This allows 335 | programmer to perform other clean up activities too 336 | -> like releasing any system resource, closing connections.. 337 | 338 | So when it is called? It is called before performing garbage collection. 339 | 340 | However we can not be assured that the finalise method will be called when we call the gc.. 341 | We don't have any idea that the method is going to be called or not or when this method will going to 342 | be called. 343 | 344 | Why we should not use finalize() method?⭐️ 345 | 346 | There is no assurance that finalize method will get called. Therefore it gets useless sometimes to put 347 | any clean up code in the finalise method. 348 | 349 | So there is no use of finalize method? 350 | We can use this method to check that are the rosaries are closed or not? 351 | So you may not use finalize method to correct the problem but at least send out a warning that 352 | something could be wrong. 353 | 354 | What are memory leaks? What are soft references? 355 | memory leak is a scenario that occurs when objects are no longer being used by the application, 356 | but the Garbage Collector is unable to remove them from working memory – because they’re still being referenced. 357 | As a result, the application consumes more and more resources – which eventually leads to OutOfMemoryError. 358 | 359 | Soft leaks: it may be possible that any objects are not being used for years but any third party API or 360 | any other thing is there for keeping it live.. these kind of objects should be garbaged but they are 361 | not because they are somehow referenced from stack.⭐️ 362 | -------------------------------------------------------------------------------- /Java8.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1. Have you used Java 8 and Later? What the most important features added in Java 8. 4 | 5 | Java 8 is a Major release from Oracle that changes the way of programming and some of the very powerful features added in Java 8 are - 6 | 7 | Lambda Expressions & Functional Interface. 8 | Java Stream API 9 | forEach() method in Iterable interface 10 | default and static methods in Interfaces 11 | Java Date and Time API 12 | 13 | 2. So, What is Lambda Expression ? 14 | 15 | And you may answer this Question By Explaining - 16 | 17 | In Java Lambda Expressions is the anonymous functions that can be Passed into another method as argument. A function that can be created without belonging to any class. Lambda Expression facilitate passing Behavior or Functions 18 | as parameter to another Functions. This also enables the programming language to be as functional programming language. 19 | 20 | 3. Now the Next and a bit important Questions That can come in two Ways - 21 | 22 | A) So how do you call / Invoke this Function without name called Lambda? 23 | B) What is Functional Interface 24 | 25 | The Answer is that, Every Lambda function in Java is Backed up by a Functional Interface. Java Implemented functional programming or 26 | Lambda Expressions using Interfaces to keep the language's backwards compatibility intact. 27 | Let me now take you through a full background in The following lecture so that you can understand and answer the Questions around Lambda and 28 | Functional Interfaces. 29 | 30 | 31 | 4. Can you Convert few Functions into Lambda - and the interviewer may put a function for you to convert that into Lambda. 32 | 33 | You may Convert the lambda of functions like this - 34 | 35 | 36 | Zero parameter: 37 | 38 | () -> System.out.println("My without Parameter Lambda"); 39 | 40 | One parameter:� 41 | 42 | (x) -> System.out.println("One parameter: " + x); 43 | 44 | Multiple parameters : 45 | 46 | (a,b) -> System.out.println("Multiple parameters: " + a + ", " + b); 47 | 48 | 49 | 50 | 5. What are Functional interfaces 51 | 52 | Functional interfaces, are interfaces having only one abstract method and generally used to invoke Lambda Expression. 53 | 54 | 55 | 56 | 6. so what is the difference between anonymous classes and Lambda Expression? 57 | 58 | So the main difference between anonymous inner classes and Lambda is 59 | 60 | The compiler generates a class file for each anonymous inner class. 61 | For example � AnonymousInnerClass$1.class 62 | Like all classes, it needs to be loaded and verified at startup. 63 | 64 | For Lambda compiler uses invoke Dynamic to call the Lambda so no extra class files are generated 65 | 66 | 67 | 7. Can you Name a few Functional Interfaces that are already there in Java 8 to use. 68 | 69 | The answer of this question is there are 40+ predefined functional interfaces in Java, Some on the very important functional interfaces to remember are 70 | 71 | Consumer (This consumes the input) having a abstract Method Accept(Object obj) 72 | Predicate (This Functional Interface is used to test some condition) having abstract method test(Object obj) 73 | Supplier only Supplies does not accept, or return anything back having Method get() 74 | Function Functional interface is used to apply some operation and return the object back, having method Object apply(Object obj) 75 | 76 | 77 | 8. What is :: (Double Colun Operator) or Method reference. 78 | 79 | :: Operator of method reference can be used if we want to use an existing method available as Lambda. 80 | 81 | Like in String we want to use toUppercase - Let's see how we can use that 82 | 83 | import java.util.function.Function; 84 | 85 | public class Parctice01 { 86 | 87 | public static void main(String[] args) { 88 | 89 | String s="BasicsStrong"; 90 | // There is a method in String toUpperCase and we can refer this using 91 | // Functional Interface 92 | 93 | Function fun = String::toUpperCase; 94 | 95 | String newString=fun.apply("basicsStrong"); 96 | System.out.println(newString); 97 | } 98 | 99 | } 100 | 101 | 102 | 9. Another most important Question the interview may ask is, What is Functional Programming. 103 | 104 | In Functional programming Functions are the first class Citizens, Can be passed to another functions and can be returned from another 105 | functions. 106 | 107 | Functional Programming mainly supports 108 | 109 | Methods Composition (one function returns another) 110 | Passing the Method or behavior Dynamically 111 | Pure Functions 112 | Higher Order Functions 113 | 114 | 10. What is pure Function? 115 | 116 | Pure Functions have below Characteristics. 117 | 118 | ___________________ 119 | | | 120 | Input-----> | f(x) | -----> OutPut 121 | | | 122 | |___________________| 123 | 124 | The return value of the pure func�tions solely depends on its arguments Hence, if you call the pure func�tions with the same set of argu�ments, you will always get the same return values. 125 | 126 | They do not have any side effects like net�work or data�base calls 127 | 128 | They do not mod�ify the argu�ments which are passed to them 129 | 130 | With this pure functions comes with a Great Benefit and can be used fearlessly in Multithreaded programs as they will never Modify the 131 | shared State or variables. 132 | 133 | Example : 134 | 135 | public static int sum(int a, int b) { 136 | return a + b; 137 | } 138 | 139 | This function, satisfies all the requirements of being pure. 140 | 141 | 142 | 143 | At the same time ... 144 | 145 | public static int sum(int a, int b) { 146 | return new Math.Random().nextInt() + a + b; 147 | } // This is Impure becasue it Voilates the first Rule. 148 | 149 | 150 | public static int sum(int a, int b) { 151 | writeSomethingToFile(); 152 | return a + b; 153 | } // This is also impure because it voilates the second rule. 154 | 155 | 156 | 11. What are Higher Order Functions? or Functional Composition? 157 | 158 | The Functions that return another Function is called Higher Order Functions, and applying these functions one by one like Fluid Operations are called Functional Composition 159 | 160 | Let's understand this with an Example - 161 | 162 | Look at this code closely this is returning a Function, so this can be called as Higher Order Function. 163 | 164 | public static Comparator reverse(Comparator comp) { 165 | return (x, y) -> comp.compare(y, x); 166 | } 167 | 168 | 169 | 12. What is Stream in Java. 170 | 171 | A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Stream connects to 172 | the data source and convert that into a flow of Objects, that can be processed using methods one by one. 173 | Let's take an Example - 174 | 175 | public class Parctice02 { 176 | 177 | public static void main(String[] args) { 178 | 179 | List list=Arrays.asList(1,2,2,3,4,5,6,7,8,9); 180 | 181 | List is converted into Stream Here where the Elements will flow one by on and processed as per the operations applied. 182 | List evenList=list.stream() 183 | .filter(e -> e%2==0) 184 | .collect(Collectors.toList()); 185 | 186 | System.out.println(evenList); 187 | 188 | // In this Example list of Integers has been converted into Stream 189 | // then Filter Method is applied and lambda is passed to filter only even items 190 | // then finally collect operation is called to collect the Items to another list 191 | } 192 | 193 | 194 | } 195 | 196 | 13. What do you mean by Pipeline of Operations? 197 | 198 | To perform a sequence of operations over the elements of the data source and process and get the results, 199 | 200 | There are three things Required 201 | 202 | Data source 203 | Intermediate operation(s) 204 | Terminal operation. 205 | 206 | Data Source is the Dataset or collection to which the Stream will be created. 207 | 208 | There are various operations in Stream that is Intermediate - 209 | 210 | filter() 211 | map() 212 | flatMap() 213 | distinct() 214 | sorted() 215 | peek() 216 | limit() 217 | skip() 218 | 219 | Intermediate operations are lazy and will not be called until the Terminal operation is called. To identify if the operation is Intermediate 220 | or not we can check 221 | 222 | If the operation is returning another stream it is called intermediate operation. 223 | 224 | The terminal operation is the final operations that will be called after triggering the Intermediate operations. 225 | 226 | Some of the Example of Terminal operations are. 227 | 228 | toArray() 229 | collect() 230 | count() 231 | reduce() 232 | forEach() 233 | forEachOrdered() 234 | min() 235 | max() 236 | anyMatch() 237 | allMatch() 238 | noneMatch() 239 | findAny() 240 | findFirst() 241 | 242 | In the Example above - filter is a intermediate operation and collect is the terminal operation 243 | 244 | List list=Arrays.asList(1,2,2,3,4,5,6,7,8,9); 245 | 246 | List is converted into Stream Here where the Elements will flow one by on and processed as per the operations applied. 247 | List evenList=list.stream() 248 | .filter(e -> e%2==0) 249 | .collect(Collectors.toList()); 250 | 251 | System.out.println(evenList); 252 | 253 | 14. What do you mean by Lazy evaluation? 254 | 255 | 256 | Lazy evaluation is that Intermediate operations are not executed, until required, and JVM intelligently calls intermediate operations. 257 | 258 | Let's prove this using an Example 259 | 260 | package com.basicsstrong.apidesign; 261 | 262 | import java.util.ArrayList; 263 | import java.util.Arrays; 264 | import java.util.Comparator; 265 | import java.util.List; 266 | import java.util.function.Function; 267 | import java.util.stream.Collectors; 268 | import java.util.stream.Stream; 269 | 270 | public class Parctice02 { 271 | 272 | public static void main(String[] args) { 273 | 274 | 275 | List persons = new ArrayList<>(); 276 | persons.add(new Person("John",36)); 277 | persons.add(new Person("Erick",39)); 278 | persons.add(new Person("Mickel",56)); 279 | persons.add(new Person("Bob",33)); 280 | 281 | // This is just a Intermediate Operation Let see if the get Method gets executed by 282 | // Putting a Debug code there 283 | 284 | Stream stream = persons.stream() 285 | .filter(e -> e.getAge() <= 36); 286 | 287 | // Nothing Happenes. 288 | 289 | // Let's now add one terminal operation 290 | 291 | 292 | List newlist = persons.stream() 293 | .filter(e -> e.getAge() <= 36) 294 | .collect(Collectors.toList()); 295 | // See the getMethod call takes place and Stream is filtered 296 | 297 | System.out.println(newlist); 298 | } 299 | 300 | } 301 | 302 | class Person{ 303 | 304 | String name; 305 | int age; 306 | 307 | public Person(String name, int age) { 308 | super(); 309 | this.name = name; 310 | this.age = age; 311 | } 312 | 313 | public String getName() { 314 | return name; 315 | } 316 | public void setName(String name) { 317 | this.name = name; 318 | } 319 | public int getAge() { 320 | 321 | System.out.println("I am in getAge Mthod of Persons"); 322 | 323 | return age; 324 | } 325 | public void setAge(int age) { 326 | this.age = age; 327 | } 328 | 329 | @Override 330 | public String toString() { 331 | return "Person [name=" + name + ", age=" + age + "]"; 332 | } 333 | 334 | 335 | } 336 | 337 | 15. What are parallel Streams : 338 | 339 | Parallel Streams can take advantage of MultiCore processors, and get executed in parallel. But you should take care while using parallel streams 340 | 341 | 342 | 343 | 16. Why default methods got introduced in Java 8 344 | 345 | For Making, Functional interfaces more Functional to support Composition and Higher Order functions. Functional interfaces needed to have Methods inside. 346 | But Java Could not do that because of backward compatibility. If they could have add a method in existing interface all the application using 347 | those interfaces had to implement That. 348 | 349 | That's why Java introduced Default Methods. Others can override if they need their implementation else, default implementation would remain there. 350 | -------------------------------------------------------------------------------- /Language-Fundamentals.java: -------------------------------------------------------------------------------- 1 | //Identifiers 2 | 3 | L1-00:35 What are identifiers in java? 4 | Name used to identify the class or a variable or A label or a method or a package.. such things 5 | is called an identifier 6 | 7 | package com.basicsstrong.fundamentals; 8 | class Demo{ 9 | int a; 10 | public void display(){} 11 | 12 | } 13 | 14 | Here 15 | Package name 'com.basicsstrong.fundamentals', 16 | Class name 'Demo', 17 | Variable name 'a', 18 | Method name 'display()' are identifiers. 19 | 20 | -> Identifiers are case-sensitive, and we can define identifiers of any length. (preferred 4-15) 21 | 22 | L1-01:44 In below example, how many identifiers are there? 23 | public class Demo{ 24 | public static void main(String[] args){ 25 | int a = 20; 26 | } 27 | } 28 | There are 5 identifiers. 29 | 1. ClassName 'Demo', 30 | 2. MethodName 'main', 31 | 3. Predefined ClassName 'String', 32 | 4. Variable name 'args', 33 | 5. Variable name 'a'. 34 | 35 | L1-02:53 which characters are allowed for identifiers? 36 | Identifiers can have all the- 37 | -> alphanumeric characters [A-Z],[a-z],[0-9], 38 | -> '$' dollar sign and the underscore '_' 39 | 40 | L1-03:22 Can we have an identifier starting with a digit? 41 | Answer is No, any identifier starting with digit is not a valid java identifier. 42 | -> We cannot have '1stVariable' as identifier. 43 | 44 | L1-03:49 Can we use reserved word as identifier? ⭐️ 45 | No, we can not use reserved words as identifiers. for example, 46 | String final = "final string"; //invalid statement 47 | 48 | //Reserved Words 49 | 50 | L2-00:07 What are reserved words? ⭐️ 51 | Any programming language reserves some words to represent some functionalities defined by that 52 | particular language, such words are called reserved words. 53 | It consists of Keywords and literals. 54 | 55 | L2-00:35 How many keywords are there in java? 56 | For defining some functionalities, There are around 50 keywords in java, 57 | which includes data types, modifiers, keywords related to flow control, and many more. 58 | 59 | L2-03:34 What are unused keywords? ⭐️ 60 | Goto and const are the keywords which are reserved by java but have not used until now. 61 | 62 | L2-04:21 Can we use predefined Class name as identifier? 63 | Answer is Yes, we can use predefined Class name as identifier. 64 | String String = "Basics"; 65 | 66 | But it is not recommended to, because it reduces the readability and creates complexity in code. 67 | 68 | L2-04:56 Explain var keyword in java? 69 | 'var' is a keyword which is added in java 10, which allows us to declare a variable without defining 70 | their type. 71 | 72 | String str = "my string"; -> var str = "my String"; var i = 10; 73 | 74 | L2-05:41 Is null a keyword? 75 | No, null is not a keyword. It is a literal. 76 | 77 | L2-05:50 What are literals? ⭐️ 78 | Literals are the constant values which can be assigned to the variable. 79 | For example, 80 | 81 | String s = "BasicsStrong"; 82 | -> BasicsStrong is a literal. 83 | 84 | And java provides 3 literals, which are null, true, false. 85 | 86 | 1. Integral Literals for byte, short, int, long. 87 | 2. Floating-Point Literals for float and double. 88 | 3. Char Literals for char. 89 | 4. String Literals for strings. 90 | 5. Boolean Literals which are true and false. 91 | 92 | //Data types 93 | 94 | L3-00:05 What are various primitive data type in java?⭐️ 95 | There are 8 primitive data types: 96 | 1. byte 97 | The byte data type is an 8-bit signed Two-s complement integer. 98 | Size : 8 bit 99 | Value : -128 to 127. 100 | 101 | 2. short 102 | The short data type is 16-bit signed two-s complement integer. 103 | Size : 16 bit 104 | Value : -32768 to 32767. 105 | 106 | 👉🏻 Both byte and short are useful for saving memory in large arrays. 107 | 108 | 3. int [int i = 100;] 109 | It is a 32-bit signed two-s compliment integer. 110 | Size : 32 bit 111 | Value : -2^31 to (2^31)-1 112 | 113 | 👉🏻 int data type is generally used for numeric values. 114 | 115 | 👉🏻 In java SE8 and later, we can also use int data type as unsigned 32-bit integer which has value 116 | in range [0,2^31 - 1]. and for that we use Integer class. 117 | 118 | 4. long 119 | Long data type is 64-bit two-s compliment integer. 120 | Size : 64 bit. 121 | Value : -2^63 to 2^63 -1. 122 | 123 | 👉🏻 The Long Class can be used to represent an unsigned 64-bit long. 124 | 125 | 5. float 126 | Float data type is a 32-bit floating point. And to define a float data type 127 | we use f or F suffix. 128 | like this, 129 | float f = 10.7f; 130 | 131 | 6. double 132 | double is a 64-bit floating point. It is the default data type for decimal values. 133 | double d = 7.34456 134 | 135 | 👉🏻 Float and double are used for scientific calculations. 136 | 137 | 7. boolean 138 | boolean data type represents only one bit of information, it can be either true or false. 139 | 140 | 8. char 141 | The char data type is a single 16-bit Unicode character. Note that it is a single character. 142 | char c = 'B'; 143 | 144 | L3-03:14 What is difference between double and float variables? 145 | -> Float takes 4 bytes in memory whereas double takes 8 bytes in memory. 146 | So float is single precision floating point and double is double precision decimal number.. 147 | 148 | -> If we want to save memory in large arrays of floating point numbers, then we should use a 149 | float instead of double. 150 | 151 | L3-03:49 What is implicit conversion in java?⭐️ 152 | Type conversion in java is converting a type into another type. 153 | Two type of type casting in java, 154 | -> Implicit 155 | -> Explicit 156 | 157 | Implicit type conversion wides the range of any type. 158 | In this, one primitive is converted into another one. 159 | It is automatic type conversion which happens only when both type are compatible and target 160 | type is larger than source type. for example, 161 | 162 | int a = 50; 163 | long b = a; 164 | 165 | Here int a will be converted into long type without any explicit casting. 166 | 167 | L3-07:14 How to make any variable constant so that it cannot get changed through out the program? 168 | We can declare any variable final, with final keyword. 169 | -> a final value can never be changed. 170 | 171 | final double a = 2.4; 172 | 173 | L3-08:06 What are the default values for all primitive types? 174 | For boolean -> false 175 | For byte -> 0 176 | short -> 0 177 | int -> 0 178 | long -> 0l 179 | char -> /u0000 180 | float -> 0.0f 181 | double -> 0.0d 182 | And when it comes to any object, the default value is -> null 183 | 184 | L3-08:37 What are the Wrapper classes available for primitive types? 185 | Wrapper classes are the wrappers to primitive data types. 186 | 👉🏻 By using wrapper classes we are allowed to access primitives as objects. 187 | For every primitive type there is a Wrapper Class present in java: 188 | boolean - java.lang.Boolean 189 | byte - java.lang.Byte 190 | char - java.lang.Character 191 | double - java.lang.Double 192 | float - java.lang.Float 193 | int - java.lang.Integer 194 | long - java.lang.Long 195 | short - java.lang.Short 196 | void - java.lang.Void 197 | 198 | L3-09:26 How primitive variable passed to methods? By value or by reference?⭐️ 199 | In java, primitives are passed to methods by value. 200 | So that, when the passed value changes in the method, it does not change the original value. 201 | 202 | L3-00:00 Is it correct to say that Classes and interfaces are data types or data structure? 203 | We can consider a Class as Data type but interfaces can not be seen as data types because they 204 | do not hold anything. 205 | 206 | //Main method 207 | 208 | L4-00:13 What is main method? 209 | main method is a method which is entry point of execution of any java program. 210 | 211 | public class Exercise{ 212 | public static void main(String[] args){ 213 | int a = 10; 214 | byte b = 2; 215 | char c = 'A'; 216 | double d = 2.4; 217 | //lets add these values, 218 | System.out.println(a+b+c+d); 219 | 220 | } 221 | } 222 | 223 | So main method is an standard method which is used by JVM to start executing the program. 224 | 225 | L4-00:58 What is String args[] in main method? 226 | Main method has an argument, 'args array' of type string. 227 | However we can name it anything in place of args but mostly programmers prefer to name it args. 228 | 229 | -> When we run the program from command prompt we can pass some input to our java program. 230 | That input will get stored in String args array. 231 | 232 | -> We can also specify String argument for main method using run configuration in eclipse. 233 | 234 | L4-02:51 Why the main method is public static? 235 | -> Any method of any Class can be accessed only by creating its instance unless it is static method. 236 | 237 | 👉🏻 Java uses the main() method as the entry point of execution, so if main() method is 238 | declared non-static then JVM would not be able to call it without creating the instance of that Class. 239 | 240 | JVM cannot create instance of the main Class as there is no standard constructor defined in 241 | main class. 242 | 243 | 👉🏻 Main method is public so that it is visible to every class. If its not public, 244 | then JVM classes might not be able to access it. 245 | 246 | These are the reasons why main method is public and static. 247 | And as it does not return anything so it is void.⭐️ 248 | 249 | L4-04:33 Can we run any java program without main method? 250 | We can not. Before JDK7 we had static initialisers as an alternative approach for main method but 251 | from JDK 7 we cannot do so. 252 | 253 | //static initialiser: 254 | public class Demo{ 255 | static{ 256 | sysout(); 257 | System.exit(0); 258 | } 259 | } 260 | 261 | It is mandatory to write main method because it is the entry point of java application in case of 262 | core Java. 263 | In case of other container managed environment like Servlet, EJB etc, java programs have their 264 | own life-cycles. so we do not need to write main method in such environments. 265 | 266 | L4-05:36 Can we change signature of main method?⭐️ 267 | No, we can not change anything while defining the standard main method in java. 268 | We cannot define it non-static, private - protected, or we can not change its return type which is 269 | void. 270 | 271 | If we change anything then JVM will consider that method as any other ordinary method, and will 272 | continue to search for the standard main method. 273 | If it does not find that, the runtime error will occur. 274 | 275 | L5-07:10 Can we make main method final in java?⭐️ 276 | Answer is yes, we can declare main method as final. 277 | This makes its implementation final; any other Class would not be able to change it. 278 | -------------------------------------------------------------------------------- /MultiThreading.java: -------------------------------------------------------------------------------- 1 | 2 | L1-00:19 What is MultiThreading and its Purpose? 3 | Its a way to achieve multi-tasking in java. 4 | 5 | Multi-tasking is acheived in 2 ways: 6 | 1. Process Based 7 | 2. Thread Based is Multi-MultiThreading 8 | 9 | What is Thread? ⭐️ 10 | Thread is separate path of execution in program. 11 | Threads are, Light weight,They share the same address space. creating thread is simple 12 | when compared to process because creating thread requires less resources when compared to 13 | process. 14 | 15 | How to create a Thread? How to acheive Multi-Threading programmatically using Threads? 16 | 1. By extending Thread Class 17 | 2. By implementing Runnable Interface 18 | 19 | Which approach is better? ⭐️ 20 | implementing Runnable is a better approach. 21 | 22 | What is Main Thread? 23 | Thread responsible to execute the main method. 24 | 25 | why we call start method? can't we directly call run method? ⭐️ 26 | If we directly call run method.. 27 | then we are calling a normal method without creating a new thread. 28 | that is run method will behave as normal method and now child thread will not get started 29 | and there will only be main thread that will execute this run method. 30 | 31 | Start Method: 32 | Registering the thread with Thread Scheduler 33 | Perform all the mandatory activities 34 | invoke run 35 | 36 | Can we overload the run method? 37 | yes ,but that start method written in Thread class invokes the no argument run method. 38 | so if you overload the run method, 39 | the run method that will get invoked by the start method will 40 | only be the one with no arguments. 41 | 42 | Can we override the start method? 43 | It will not execute the necessary steps that thread class start method is having. 44 | Thats why you should not override the start method. 45 | still if you want to override the start method, 46 | you can first call the super of Thread class using super.start() and then can give additional implementation. 47 | 48 | What is Thread Scheduler? 49 | It is a part of JVM. 50 | It is responsible for the order in which the threads get executed 51 | and there is no assurity of the algorithm used by the scheduler to order 52 | the threads. It varies from JVM to JVM 53 | 54 | Explain the life-cycle of a Thread? 55 | A thread can be in any of the five states : 56 | New : When the instance of thread is created it will be in New state. 57 | Ex : Thread t= new Thread(); 58 | In the above example t is in new state. 59 | The thread is created but not in active state to make it active, 60 | we need to call start() method on it. 61 | 62 | 63 | Runnable state : A thread can be in the runnable state in either of the following 64 | two ways : 65 | When the start method is invoked or 66 | A thread can also be in runnable state after coming back from blocked or sleeping 67 | or waiting state. 68 | 69 | Running state : If thread scheduler allocates cpu time, then the thread will be 70 | in running state. 71 | 72 | Blocking/ Waiting / sleeping states : In this state the thread can be made temprorily 73 | inactive for a short period of time 74 | the above state in any of the following ways: 75 | 1) The thread waits to acquire lock of an object. 76 | 2) The thread waits for another thread to complete. 77 | 3) The thread waits for notification of other thread. 78 | 79 | Dead State : A thread is in dead state when thread’s run method execution 80 | is complete. It dies automatically when thread’'s run method execution is completed 81 | and the thread object will be garbage collected. 82 | 83 | //sleep(), yield(), join(), Thread name, Thread Groups, Thread Priorities.... 84 | 85 | What are thread priorities and importance of thread priorities in java? 86 | Thread priorities determine which thread to run. Every thread has a priority. 87 | A thread inherits priority of its parent thread. 88 | By default thread has normal priority of 5. 89 | Thread scheduler uses thread priorities to decide when each thread is allowed to run. 90 | Thread scheduler runs higher priority threads first. 91 | 92 | Explain different types of thread priorities ? 93 | Every thread in java has priority in between 1 to 10. 94 | By default priority is 5 (Thread.NORM_PRIORITY). 95 | The maximum priority would be 10 and minimum is 1. 96 | Thread class defines the following constants(static final variables) to define properties. 97 | Thread. MIN_PRIORITY = 1; 98 | Thread.NORM_PRIORITY=5; 99 | Thread. MAX_PRIORITY=10; 100 | 101 | How to change the priority of thread or how to set priority of thread? 102 | Thread class has a set method to set the priority of thread 103 | Signature : final void setPriority(int value); 104 | The setPriority() method is a request to JVM to set the priority. JVM may or may not oblige the request. 105 | We can get the priority of current thread by using getPriority() method of Thread class. 106 | final int getPriority() { 107 | } 108 | 109 | If two threads have same priority which thread will be executed first ? 110 | We are not guaranteed which thread will be executed first when there are threads with equal priorities. 111 | It depends on thread scheduler that which thread to execute. 112 | 113 | What all methods are used to prevent thread execution ? 114 | There are three methods in Thread class which prevents execution of thread. 115 | 1) yield() 116 | 2) join() 117 | 3) sleep() 118 | 119 | Explain yield() method in thread class ? 120 | Yield() method makes the current running thread to move in to runnable state from running state 121 | giving chance to remaining threads of equal priority which are in waiting state. 122 | yield() makes current thread to sleep for a specified amount of time.T 123 | here is no guarantee that moving a current running thread from runnable to running state. 124 | It all depends on thread scheduler it doesn’t guarantee anything. 125 | 126 | Explain how join method works? 127 | A thread can invoke the join() method on other thread to wait for other thread to complete its 128 | execution. Assume we have two threads, t1 and t2 threads . 129 | A running thread t1 invokes join() on thread t2 then t1 thread will wait in to waiting state until t2 completes. 130 | Once t2 completes the execution, t1 will continue. 131 | join() method throws Interrupted Exception so when ever we use join() method 132 | we should handle Interrrupted Exception by throws or by using try catch block. 133 | 134 | Explain purpose of sleep() method in java? 135 | sleep() method causes current running thread to sleep for specified amount of time . 136 | Now lets see the syntaX: 137 | first one: public static native void sleep(long ms). //its a native one not written in java 138 | second one: public static void sleep(long ms,int ns). 139 | 140 | there is no sleep method with no argument..with sleep there must be the interval for which we want to 141 | make the thread sleep. 142 | 143 | Explain about interrupt() method of thread class ? 144 | If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), 145 | calling the interrupt() method on the thread, breaks out the sleeping or waiting state 146 | throwing InterruptedException. This is reason we need to handle interrupted exception with throws 147 | or try/ catch block. 148 | 149 | What is Race Condition and when it occur?⭐️ 150 | when more than one thread operate on same object without proper synchronization 151 | then the thread operations interleaves on each other. 152 | that is, one thread is modifying the object data and in some intermediate state where 153 | the updation is not yet completed some other thread performs modification on 154 | the intermediate data resulting to data inconsistency. 155 | and this condition is called race condition. 156 | this happens when the operations that the threads are performing 157 | are non-atomic and this is why thread operation interleaves on each other. 158 | 159 | What are atomic and non atomic operations? Can volatile make a non-atomic operation to atomic? 160 | Atomic operations take place in one step. 161 | where as non-atomic operations takes place in multiple steps internally. 162 | java provides volatile keyword to make assignment or read or write operations atomic. 163 | we can use volatile before long and double and boolean to avoid data inconsistency. 164 | but you can't do anything compound such as incrementing it safely, because that's a read/modify/ 165 | write cycle. 166 | 167 | What is Synchronization? 168 | we can guard the critical section to avoid data inconsistency so that only one thread have access or execute 169 | this section of the code at a time. 170 | that is only one thread enters this section at at a time 171 | and when it exits other thread can enter this section. 172 | 173 | what is critical section? 174 | A critical section in java multithreading is a piece of code that access shared resources. 175 | that is why there are chances of data inconsistency or race condition if multiple threads operate simultaneously. 176 | 177 | What are the ways to acheive synchronization? 178 | Two ways: 179 | 1.Synchronized methods 180 | 2.Synchronized blocks 181 | 182 | When a thread is executing synchronized methods , 183 | then is it possible to execute other synchronized methods simultaneously by other threads on the same object? 184 | No it is not possible to execute synchronized methods by other threads on the same object 185 | when a thread is inside a synchronized method. 186 | 187 | example: 188 | 189 | Student s = new Student(); 190 | 191 | class Student{ 192 | synchronized public void method1(){ //can only be executed on s by the thread having the lock of s 193 | 194 | } 195 | 196 | synchronized public void method2(){ //can only be executed on s by the thread having the lock of s 197 | 198 | } 199 | 200 | public void method3(){ //any thread can execute this method on s. 201 | 202 | } 203 | } 204 | 205 | When a thread is executing synchronized methods , 206 | then is it possible to execute other synchronized methods simultaneously by other threads on different objects? 207 | yes, its is possible. Other threads are only restricted to execute the synchronized methods on the 208 | object whose lock is already aquired by the thread. 209 | 210 | Can we synchronize static methods in java? 211 | Every class in java has a unique lock associated with it. 212 | If a thread wants to execute static synchronize method it need to acquire class level lock. 213 | When a thread was executing static synchronized method no other thread can execute 214 | static synchronized method of class since lock is acquired on class. 215 | But it can execute the following methods simultaneously : 216 | 1) Normal static methods 217 | 2) Normal instance methods 218 | 3) Synchronized instance methods 219 | 220 | class Student{ 221 | 222 | synchronized public static void staticMethod1(){ //can only be executed by the thread having the lock of class Student 223 | 224 | } 225 | 226 | public static void staticMethod2(){ //can be executed by any thread 227 | 228 | } 229 | 230 | 231 | synchronized public void method1(){ //can only be executed by any thread 232 | 233 | } 234 | 235 | synchronized public void method2(){ //can only be executed by any thread 236 | 237 | } 238 | 239 | public void method3(){ //can only be executed by any thread 240 | 241 | } 242 | } 243 | 244 | Can we use synchronized block for primitives? 245 | 246 | Student s = new Student(); 247 | 248 | synchronized (s){ 249 | 250 | } 251 | 252 | class Student{ 253 | 254 | public static void staticMethod1(){ 255 | //can only be executed by the thread having the lock of class Student 256 | 257 | synchronized(Student.class){ 258 | 259 | } 260 | 261 | } 262 | 263 | public static void staticMethod2(){ //can be executed by any thread 264 | 265 | } 266 | 267 | 268 | public void method1(){ 269 | //can only be executed by any thread 270 | 271 | synchronized (this){ 272 | 273 | } 274 | 275 | } 276 | 277 | synchronized public void method2(){ //can only be executed by any thread 278 | 279 | } 280 | 281 | public void method3(){ //can only be executed by any thread 282 | 283 | } 284 | } 285 | 286 | Synchronized blocks are applicable only for objects. If we try to use 287 | synchronized blocks for primitives we get compile time error. 288 | 289 | Why we use explicit lock? 290 | It provides additional features 291 | 292 | //Inter-Thread communication 293 | 294 | Explain about inter-thread communication and how it takes place in java? 295 | Usually threads are created to perform different unrelated tasks but 296 | there may be situations where they may perform related tasks or they need to communicate to other threads. 297 | one of the example of this is Producer Consumer problem. Inter-thread communication 298 | in java is done with the help of following three methods : 299 | 1) wait() 300 | 2) notify() 301 | 3) notifyAll() 302 | 303 | Explain wait(), notify() and notifyAll() methods of object class ? 304 | wait() : wait() method releases the lock on object until some other thread acquires the lock and calls notify(). 305 | notify() :notify() method wakes up the thread that called wait on the same object. 306 | notfiyAll() :notifyAll() method wakes up all the threads that called wait() on the same object. 307 | The highest priority threads will run first. 308 | All the above three methods are in object class and are called only in synchronized context. 309 | All the above three methods must handle InterruptedException by using throws clause or by using try 310 | catch clause. 311 | 312 | Write code to solve the Produce consumer problem in Java? ⭐️ 313 | 314 | when wait(), notify(), notifyAll() methods are called does it releases the lock or holds the acquired lock? 315 | when the thread enter in synchronized context thread acquires the lock on current object. When 316 | wait(), notify(), notifyAll() methods are called lock is released on that object. 317 | 318 | Explain why wait(), notify() and notifyAll() methods are in Object class rather than in thread class? 319 | wait() , notify(), notifyAll() methods are object level methods they are called on same object. 320 | these methods are called on an shared object so they are kept in object class rather than thread 321 | class. 322 | 323 | Explain IllegalMonitorStateException and when it will be thrown? 324 | IllegalMonitorStateException is thrown when wait(), notify() and notifyAll() are called in non 325 | synchronized context. Wait(), notify(),notifyAll() must always be called in synchronized context 326 | other wise we get this run time exception. 327 | whenever we call these methods lock is acquired or released on that object so they must be called 328 | from within synchronized area. 329 | 330 | //other 331 | 332 | Explain which of the following methods releases the lock when invoked? 333 | yield() No 334 | join() No 335 | sleep() No 336 | wait() Yes 337 | notify() Yes 338 | notifyAll() Yes 339 | 340 | 341 | Can we restart a dead thread in java? 342 | If we try to restart a dead thread by using start method, we will get run time exception since the 343 | thread is not alive. 344 | 345 | Can one thread block the other thread? 346 | No, one thread cannot block the other thread in java. It can block the current thread that is running. 347 | for example if we yield a thread..it blocks itself to give chance to other thread..but we can't 348 | block other thread. 349 | 350 | Can we restart a thread already started in java? 351 | We start a thread using start() method in java. 352 | If we call start method second time once it is started it will cause RunTimeException(IllegalThreadStateException). 353 | A runnable thread cannot be restarted. 354 | 355 | 356 | //liveness problems, Daemon Threads, Immutable Objects (Thread Safety) 357 | 358 | What is liveness? What are liveness problems? 359 | A concurrent application's ability to execute in a timely manner is known as its liveness. 360 | Liveness problems include: 361 | Deadlock, 362 | Starvation, 363 | Livelock 364 | 365 | What is deadlock? ⭐️ 366 | When two or more threads are waiting for each other to release the resource or lock 367 | and get stuck for infinite time, the situation is called deadlock. 368 | 369 | Write a program which will result in a deadlock? How will you fix deadlock in Java?⭐️ 370 | 371 | How many types of threads are there in Java? 372 | Java offers two types of threads: 373 | 1.user threads 374 | 2.daemon threads. 375 | 376 | What are daemon threads in java?⭐️ 377 | Daemon threads are threads which run in background. 378 | Daemon thread is mostly created by JVM. 379 | For example: Garbage collector 380 | These are service threads and works for the benefit of other threads. 381 | If parent thread is daemon, child thread also inherits daemon nature of thread. 382 | JVM will force daemon thread to terminate if all user threads have finished their execution 383 | but The user thread is closed by itself. 384 | 385 | How to make a non daemon thread as daemon? 386 | By default all threads are non daemon. 387 | We can make non daemon thread daemon using setDaemon() method. 388 | we call setDaemon() only before start() method. 389 | If we call setDaemon() after start() method an IllegalThreadStateException will be thrown. 390 | 391 | Can we make main() thread as daemon? 392 | Main thread is always non daemon. 393 | We cannot make it daemon. 394 | 395 | How immutability simplify the concurrency? 396 | Immutable objects are by default thread-safe because there state can not be modified once created. 397 | So we do not have to take care of data inconsistency in case of immutable objects. 398 | For example: All the Wrapper classes (Integer, Long, Byte, Double, Float, Short),String class 399 | 400 | //Advanced Multithreading 401 | 402 | What is Thread Group? Why it’s advised not to use it? 403 | Thread group is a collection of threads or sub thread groups 404 | that are responsible for doing something similar and Java provides a convenient way to group multiple 405 | threads in a single object .The advantage of using thread group is that we can perform common operation on the whole 406 | group so in other words programmer can group the threads in thread group based on their functions to 407 | be performed. 408 | But ThreadGroup API is weak and it doesn’t have any functionality that is not provided by Thread. 409 | Two of the major feature it had are to get the list of active threads in a thread group 410 | and to set the uncaught exception handler for the thread. 411 | So ThreadGroup is obsolete and hence not advised to use anymore. 412 | 413 | What is Thread Pool? How can we create Thread Pool in Java? 414 | A thread pool manages the pool of threads, it contains a queue that keeps tasks waiting to get executed. 415 | java.util.concurrent.Executors provide implementation of java.util.concurrent. 416 | Executor interface to create the thread pool in java. 417 | 418 | What is Callable?⭐️ 419 | Callable is an interface with single abstract method call(). 420 | Java 5 introduced java.util.concurrent.Callable interface in concurrency package 421 | that is similar to Runnable interface but it can return any Object and is able to throw Exception. 422 | Callable interface use Generic to define the return type of Object. 423 | 424 | What is ExecutorService?⭐️ 425 | The Java ExecutorService is a construct that allows you to pass a task to be executed by a thread asynchronously. 426 | The executor service creates and maintains a reusable pool of threads for executing submitted tasks. 427 | 428 | How to create executor service? 429 | ExecutorService executorService = 430 | new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, 431 | new LinkedBlockingQueue()); 432 | 433 | ExecutorService executor = Executors.newFixedThreadPool(10); 434 | 435 | ExecutorService executor = Executors.newSingleThreadExecutor(); 436 | 437 | ExecutorService executor = Executors.newCachedThreadPool(); 438 | 439 | ExecutorService executor = Executors.newScheduledThreadPool(5); 440 | 441 | ExecutorService executor = Executors.newSingleThreadScheduledExecutor(); 442 | 443 | ExecutorService executor = Executors.newWorkStealingPool(); 444 | 445 | How do you execute a callable from executorservice? 446 | We pass the callable task inside the submit method 447 | and invoke the submit on the created ExecutorService. 448 | 449 | How do you execute runnable task from executorservice? 450 | We pass the runnable in the execute method and invoke it on the ExecutorService. 451 | 452 | What is Future?⭐️ 453 | Executors class provide useful methods to execute Callable in a thread pool. 454 | Since callable tasks run in parallel, we have to wait for the returned Object. 455 | Callable tasks return java.util.concurrent.Future object. 456 | Using Future we can find out the status of the Callable task and get the returned Object. 457 | It provides get() method that can wait for the Callable to finish and then return the result. 458 | So, Future is basically a placeholder for the object which is going to be 459 | returned by the callable task at any time in future. 460 | 461 | What is ThreadLocal? 462 | Java ThreadLocal is used to create thread-local variables. i.e., variables local to each thread. 463 | We know that all threads on an Object share it’s variables, so if the variable is not thread safe, 464 | we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables. 465 | If the same code runs in different threads, these executions will not share the value, instead of that, each 466 | thread has its own variable that is local to the thread and they can use it’s get() and set() methods 467 | to get the default value or change it’s value local to Thread. 468 | ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread. 469 | 470 | What is Java Thread Dump, How can we get Java Thread dump of a Program? 471 | Thread dump is list of all the threads active in the JVM, 472 | thread dumps are very helpful in analyzing bottlenecks in the application 473 | and analyzing deadlock situations. 474 | There are many ways using which we can generate Thread dump – 475 | Using Profiler, Kill -3 command, jstack tool etc. 476 | 477 | How to schedule a task to run after specific interval? 478 | java.util.TimerTask is an abstract class that implements Runnable interface 479 | and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class and 480 | java.util.Timer class can be used to schedule a task to 481 | be run one-time or to be run at regular intervals at certain time in future. 482 | 483 | What is context switching in multithreading ? 484 | Context Switching is the process of storing and restoring of CPU state 485 | so that Thread execution can be resumed from the same point at a later point of time. 486 | Context Switching is the essential feature for multitasking operating system and 487 | support for multi-threaded environment. 488 | 489 | What is fork join pool?⭐️ 490 | fork join 491 | 492 | What is completable future? 493 | completable Future 494 | 495 | What is FutureTask Class? 496 | FutureTask is the base implementation class of Future interface 497 | and we can use it with Executors for asynchronous processing. 498 | Most of the time we don’t need to use FutureTask class but it comes real handy 499 | if we want to override some of the methods of Future interface and want to keep most of the base implementation. 500 | We can just extend this class and override the methods according to our requirements. 501 | 502 | 503 | //Concurrent Collection And Concurrent Utilities 504 | 505 | What are Concurrent Collection Classes? 506 | Java Collection classes are fail-fast which means that if the Collection is changed while 507 | some thread is traversing over it using iterator, the iterator.next() will throw ConcurrentModificationException. 508 | Concurrent Collection classes support full concurrency of retrievals and 509 | adjustable expected concurrency for updates. 510 | Major classes are ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteArraySet, LinkedBlockingQueue etc. 511 | 512 | Briefly explain concurrentHashMap. How is it better than HashMap and HashTable in terms of concurrency? 513 | 514 | Briefly explain CopyOnwriteArraylist. Can we perform remove operation on CopyOnwriteArraylist while iterating? 515 | 516 | explain CopyOnwriteArraySet. 517 | 518 | What is CountDownLatch? When we use CountDownLatch? 519 | 520 | What is CyclicBarrier? What is the difference between CountDownLatch and CyclicBarrier? 521 | 522 | What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue? 523 | 524 | What is Exchanger? How do exchanger work? 525 | 526 | Briefly explain Semaphore. 527 | 528 | List the implementations of BlockingQueue. 529 | ArrayBlockingQueue, 530 | DelayQueue, 531 | LinkedBlockingQueue, 532 | PriorityBlockingQueue, 533 | and SynchronousQueue. 534 | -------------------------------------------------------------------------------- /OOPS in java.java: -------------------------------------------------------------------------------- 1 | 2 | //Object Oriented Programming [OOP] 3 | 4 | //Classes and Objects - Building Blocks of OOP 5 | 6 | L1-00:45 What are classes and objects? 7 | A Class is a user-defined-blueprint from which objects are created, which has attributes and behavior. 8 | 9 | L1-04:30 How can we create class? 10 | We can define a Class in java, using keyword "class". 11 | 12 | class 13 | { 14 | //Variables 15 | //Methods... 16 | } 17 | 18 | For example: 19 | 20 | class Fan{ 21 | private boolean isOn; 22 | 23 | public void turnOn(){ 24 | isOn = true; 25 | } 26 | 27 | public void turnOff(){ 28 | isOn = false; 29 | } 30 | } 31 | 32 | Class members: isOn [Data member], turnOn() turnOff() [Member functions] 33 | 34 | L1-09:07 How to create objects? 35 | We create objects with the keyword 'new'. 36 | 37 | ref = new (); 38 | 39 | L1-13:41 How many classes we can create in a java file? 40 | We can create any number of classes in a java file. 41 | 👉🏻 We can have only one Public Class in a java file. 42 | 43 | 44 | //modifiers 45 | 46 | L2-00:22 There are two types of modifiers present in java 47 | 1. Access modifiers 48 | 2. Non-Access Modifiers. 49 | 50 | L2-00:29 What are the Access modifiers in java? 51 | Access Modifiers are the keywords in object oriented language, which set the accessibility of classes 52 | or methods or any members. 53 | 54 | -> Using public modifier we specify that the Class can be accessed everywhere. 55 | 56 | L2-01:13 How many access modifiers are there in java? 57 | 1. public 58 | 2. private 59 | 3. protected 60 | 4. 61 | 62 | public: 63 | public members can be accessed anywhere, in any class, present in any Package. 64 | 65 | default: 66 | When there is no modifier used, then the component has default accessibilities. 67 | -> Classes with no modifier said to be default classes. The scope for the default classes 68 | and default Class members is within their Package. 69 | 70 | private: 71 | Private members cannot be accessed anywhere except in the Class itself where they are declared. 72 | 73 | protected: 74 | Protected members can be accessed within the same Package and in its subclass, 75 | but it cannot be accessed in the other packages excepts its child classes. 76 | 77 | So their scope is limited to its Package and its subclasses. 78 | 79 | L3-00:02 What is a Package? 80 | A Package is a mechanism to keep all classes, interfaces and sub-packages; 81 | which has similar functionalities, at the same place. 82 | 83 | Packages provides a folder structure to organize our classes-interfaces, so that one can easily 84 | search and use them. 85 | 86 | L3-01:12 How can we access a Class outside its Package? 87 | To use a Class outside its Package we must Import it, using the 'import' keyword. 88 | For example, 89 | 90 | import com.basicsstrong.oops.; 91 | 92 | L3-01:55 Can we declare a Top level Class private? 93 | Answer is no, A Class can be public or default. 94 | 95 | Inner class: Class defined in a class. 96 | 97 | Inner classes can be declared as private or protected as they are the members of the class. 98 | -> Top level Class can not be private or protected. 99 | 100 | L3-03:10 Which access modifier is the least restrictive and which is the most restrictive? 101 | Least Restrictive Modifier: Public access modifier 102 | -> It is also known as Universal Access Modifier. 103 | 104 | Most Restrictive access modifier : private. 105 | 106 | L4-00:04 What are non-access modifiers in java? 107 | 1. Static : 108 | static keyword is used to specify whether the member is a Class member or an instance member. 109 | If a member is defined static, then it is said to be Class member. 110 | 111 | 2. Final : 112 | final specifier is used to restrict further modifications on any class, any method or any 113 | variable. 114 | -> if any primitive variable is final, we cannot change its value in whole program. 115 | 116 | 3. Abstract : 117 | abstract specifier is used to mark the method or Class to be incomplete and to must be 118 | modified further by other classes. 119 | 120 | 4. Synchronized : 121 | This is used to achieve thread safety in multithreaded environment which is about executing 122 | tasks simultaneously with different threads. 123 | 124 | L4-06:35 Can a Class or a method be abstract and final at the same time? 125 | A Class or a method cannot be abstract or final at the same time. 126 | -> Final restricts the component to be modified further. 127 | -> abstract make component available to be modified further. 128 | 129 | L4-06:56 What do you mean by abstract classes? 130 | A Class with abstract specifier is a abstract class. 131 | 132 | If a Class is abstract it is not fully implemented and if a method is abstract, it does not have 133 | any implementation. 134 | 135 | 👉🏻 abstract methods can only be defined in abstract class. 136 | 137 | L4-07:32 what is abstract method? 138 | A method without any implementation or definition is an Abstract method. 139 | Abstract method are declared with the keyword abstract. 140 | 141 | L4-09:33 Can we define an abstract method in a non-abstract class? 142 | We can not declare any abstract method in a non-abstract class. 143 | 144 | L4-09:50 Can an abstract method be declared as private? 145 | No, abstract method cannot be declared as private, as they are meant to be used in other classes, 146 | so they must be public, or default or protected. 147 | 148 | L4-10:48 Can we instantiate abstract classes? 149 | Answer is No, since abstract classes are not fully implemented that is why we cannot create objects 150 | of them. 151 | 152 | L4-11:29 Can we define top level Class as static? 153 | Answer is No. static keyword is applicable only for Class members. 154 | 155 | L4-12:09 Why do we define members as static? 156 | Static keyword is used to define the members independent from any instance. 157 | Static members exist independently of any instances created for the class. 158 | 159 | -> Defining a method static will make it independent of any instance. 160 | We can call static members without creating objects, by just invoking them with the classname.. 161 | 162 | 163 | //variables, Methods, Constructors 164 | 165 | L6-00:11 What is a variable? What are the types of variable in java? 166 | Variable is a name which is given to a memory shell. It is a container that used to store data values. 167 | Variable can store primitives or objects. 168 | 169 | Class can have these variables: 170 | 171 | Instance Variable [defined inside class, outside the method] 172 | Local Variable [defined inside a method or block or constructor] 173 | Class Variables [defined in Class and outside any method but with static keyword] 174 | 175 | //What is the difference between Instance variables , Local variables and Static variables? 176 | 177 | L6-04:33 When are static variables loaded in memory? 178 | Static variables are loaded in memory at the time of Class loading. i.e, 179 | When we load the class, the static members are the first to load. 180 | 181 | L6-04:53 Are there any global variables in java? 182 | Global variables are generally those variable which can be accessed by other part of program or 183 | outside the class. 184 | 185 | Java does not allow to have global variables. As it does not fit good with the oops. 186 | 187 | L6-05:32 Can we declare final variable without initialization? 188 | Yes, we can declare final variable without initialisation. 189 | -> Such variables are called as Blank Final Variable. 190 | Blank final variable can be static or non-static.. 191 | 192 | This is how we declare blank final variables: 193 | 194 | private static final int blank_final; 195 | 196 | We have to initialize blank final varables before any usage. 197 | 198 | static blank final variables can be initialised in static block.. 199 | 200 | L6-08:45 Can we make the local variable final? 201 | Yes, we can define a local variable as final. 202 | 👉🏻 It is the only modifier which is acceptable to a local variable. 203 | 204 | L6-09:08 What is Constructor? 205 | Constructor is a special kind of method which is used to initialise objects. 206 | The name of constructor is same as of its class. 207 | 208 | class Fan{ 209 | Fan(){ 210 | //this is constructor. 211 | } 212 | } 213 | 214 | L6-09:38 What are the various types of constructors? 215 | There are three types of constructors.. 216 | 1. default Constructor: if we do not write constructor in program, then this constructor is called automatically. 217 | 2. Non-Parameterised Constructor : the constructor with no-arguments 218 | 3. Parameterised Constructor : the constructor with arguments is called as parameterised. 219 | 220 | L6:10:56 When constructors are called? 221 | Constructor are called at the time we create objects using 'new' keyword. 222 | 223 | 👉🏻 If we have not written any constructor in program then it takes default constructor automatically 224 | and initialise the data members with their default values. 225 | 226 | L6-16:06 Can a constructor be final or static or abstract? 227 | No, Constructor cannot have any Non-access modifiers. 228 | 229 | -> The constructor can not be final because once we create anything final, then that method cannot 230 | be modified by other class, and as the Constructor already can not be overridden or modified by any 231 | class, there is no need of final keyword. 232 | 233 | -> abstract method does not have body. They have only declaration. 234 | But constructor cannot lack a body, thats why constructor can not be abstract. 235 | 236 | -> static members always belong to class, not to any objects. Therefore constructor cannot be static 237 | as, they are invoked every time we create objects. 238 | 239 | L6-16:57 Can we have return type or any return statement with constructor? 240 | No, we cannot have these. 241 | 242 | L6-17:06 What is the use of private constructor in Java? 243 | private members can only be accessed inside the class, where they are defined. So if we define 244 | constructors private, then we can create objects of the Class only in inside that Class internally. 245 | No other classes can create object for that. 246 | 247 | -> So using private constructor we can restrict the caller from creating objects. 248 | 249 | L6-19:19 Can a Constructor return any value ? 250 | As we know constructors do not have any return type, So a constructor cannot return any explicit value. 251 | However constructor returns the instance of the Class implicitly. 252 | 253 | L6-19:47 Can an Abstract Class have a constructor? 254 | Yes, an abstract Class can have a constructor. 255 | 256 | L6-20:01 How we define a method in java? 257 | Method is block of code which can be invoked by its name whenever required. In java we write method as, 258 | 259 | (datatype args){ 260 | //method body 261 | } 262 | 263 | L6-20:30 What is Method signature? 264 | The method name and the data type of parameters it have is called as method signature. Like: 265 | Method signature for method is, 266 | findSum(int a ,int b). 267 | 268 | L6-21:06 Does return type of the method is a part of method signature? 269 | No, method signature only contain method name and type of arguments. 270 | 271 | L6-22:02 What are Static methods? 272 | We use static keyword to define static methods. Static methods are used to access static members. 273 | 274 | Public static int get(){ 275 | } 276 | 277 | -> To call static method: 278 | Addition.get(); 279 | 280 | L6-22:22 Can we access instance variables inside Static methods? 281 | Answer is No, we cannot access instance variable inside static blocks, static methods. 282 | Static methods and static blocks can only access static members. 283 | 284 | L6-23:24 What are method declarations? 285 | When we do not define the body of method, and end it with a semi-colon then that is called method 286 | declaration. 287 | 288 | -> Method declarations are only used in abstract classes and interfaces. 289 | 290 | L6-24:15 What are interfaces? 291 | An Interface is actually blueprint of a class, which specifies what a Class must do. (not how) 292 | i.e, Interfaces does not have implementations of methods, There are only method declarations 293 | and all the methods are abstract and public by default. 294 | 295 | interface InterfaceDemo{ 296 | void method1(); 297 | void method2(); //this is method declaration. 298 | } 299 | 300 | L6-25:57 What is a native method? 301 | A native method is a method which is implemented in a non-java language, and is targeted for a 302 | single machine type. 303 | 304 | L6-26:35 Can we define any method as final? 305 | Yes. Methods can be made as final. 306 | -> You can define any method final if you want to restrict others to modify the implementation of the 307 | method. 308 | 309 | L6-26:53 Can we create object for final class? 310 | Yes, we can definitely create an object for final class. 311 | Example is class:String. It is a final class. 312 | 313 | //OOPS 314 | 315 | L7-00:13 What is OOPS? 316 | OOPS stands for Object Orieted programming System. 317 | Object oriented programming is a Programming paradigm to write programs based on real world 318 | objects, in that world, the states and behaviour of an object are the variable and methods. 319 | 320 | L7-01:15 What are the advantages of OOPS? 321 | These are the major advantages of OOPS: 322 | 1. Simplicity: 323 | Since OOPS consists real world objects, so the program structure remains clear to everyone without 324 | any complexity. 325 | 2. Modularity: 326 | In object oriented paradigm, each object forms a separate entity. For each object, their state, 327 | behaviour and other internal workings are decoupled from other parts of system. 328 | 3. Modifiability: 329 | With OOPs programming it is easy to change the data representation and methods. Changes inside 330 | any particular Class do not affect any other part of the program. 331 | 4. Extensibility: 332 | This is about adding New features by modifying some existing modules. OOPs allows to do that. 333 | 5. Maintainability: 334 | The objects can be maintained by fixing problems easier. 335 | 6. Reusability: 336 | Objects can be reused in different programs. 337 | 338 | L7-02:37 What are the core concepts of oops? 339 | 340 | 1. Data Hiding : hiding the internal data, Securing the internal data 341 | 2. Abstraction : way to segregate implementations from other entities (Hiding internal implementation) 342 | 3. Encapsulation : Grouping of data member and member functions together 343 | 4. Inheritance : Inheritance is the process of creating a new Class from the existing class(Inheriting properties from a class) 344 | 5. Association 345 | 6. Composition 346 | 7. Aggregation 347 | 8. Polymorphism : a particular method that behaves different in different contexts 348 | 349 | L8-00:02 What is the difference between Abstraction and Encapsulation? 350 | 351 | Abstraction is implemented using interfaces and abstract classes and Encapsulation is about wrapping 352 | data members and member functions. This is implemented using private, protected keywords. 353 | 354 | Encapsulation is a concept that is a mix of data hiding and Abstraction. We hide Data from 355 | unauthenticated access, and implementations from outside world. 356 | Abstraction is about not showing the internal implementations directly to any other class. 357 | 358 | L8-01:04 What is difference between Abstract Class and Interface? 359 | 360 | 1. In abstract class, we can have both abstract and concrete methods where as in Interface, 361 | we can only have abstract methods, they cannot have concrete methods. 362 | However we can have static, default and private methods in interface. 363 | 364 | 2. We can extend only one Abstract Class at a time where as in case of interfaces, we can implement 365 | any number of interfaces at a time. 366 | 367 | 3. In abstract class ‘abstract’ keyword is used to declare a method as abstract, where as in Interface 368 | all the methods are abstract by default, so no keyword is required to declare methods. 369 | 370 | 4. Abstract Class can have static, final or static final variables with any access specifier 371 | where as in Interface, we can have only static final variable by default. 372 | 373 | So we can use interfaces, when we want to create a service requirement specification for any class. 374 | and we can use abstract classes to provide a base for subclasses to extend and implement the abstract 375 | methods and use the implemented methods which are defined in abstract class. 376 | 377 | L8-04:09 How can we write static, private and default methods in interface? 378 | 379 | L9-00:02 Can we have an abstract class without any abstract method? 380 | yes. 381 | 382 | L9-00:21 Can we have a non-abstract class with abstract methods? 383 | No. 384 | 385 | L9-00:39 Can we create constructor in abstract class? 386 | Yes. We can create constructor in abstract class. It does not give any compilation error, 387 | but as we cannot instantiate an Abstract Class so there is no use of creating it. 388 | 389 | L9-00:58 What are the various types of inheritance? 390 | These are the types of inheritance: 391 | 392 | 1. Single Inheritance: a single Class extends another class. 393 | 394 | class A{} 395 | class B extends A{} 396 | 397 | 2. Multilevel Inheritance: in this there are multiple level of inheritance. 398 | 399 | class A{} 400 | class B extends A{} 401 | class C extends B{} 402 | 403 | 3. Multiple Inheritance: A single Class extends more than 1 class. 404 | 405 | 👉🏻 Java does not support this type of inheritance, because if a class extends more than one class. then there is chance 406 | of ambiguity problem if there is any method present with the same name. 407 | 408 | However we may implement more than one interfaces, so multiple inheritance is possible with 409 | interfaces. 410 | 411 | 4. Hierarchical Inheritance: This is about having single base class, and multiple implementation 412 | classes. i.e, single parent multiple Child classes. 413 | 414 | class A{} 415 | class B extends A{} 416 | class C extends A{} 417 | 418 | Java allows this type of inheritance. We can extend a Class in more than one classes. 419 | 420 | 5. Hybrid Inheritance: This is the combination of more than one type of inheritance. It is about having 421 | multiple base and multiple implementation classes. 422 | 423 | 👉🏻 It is not supported in java, as we know multiple classes can extend a single Class but a 424 | single Class can not extend multiple classes. 425 | 426 | 6. Cyclic inheritance: A Class extends itself. it is not available in java and not actually required. 427 | class A extends B{} 428 | class B extends A{} 429 | 430 | -> all the methods or attributes will be available for use to each other. 431 | Instead of doing this, one may merge these two classes. So Cyclic inheritance is not required. 432 | 433 | L9-04:02 What is Diamond Problem in inheritance? 434 | In case of multiple inheritance, if a Class extends two classes, then there is chance of ambiguity 435 | problem. This ambiguity problem is called as Diamond Access problem. 436 | 437 | L9-04:32 Why do not we have ambiguity problem with interfaces in case of multiple inheritance? 438 | We can implement more than one interface. So multiple inheritance is possible as interfaces 439 | only have declaration of methods, not implementation. If two interfaces have methods with same name, 440 | then these are only multiple declarations of that method. The implementation will be only one. 441 | So there is no chance of ambiguity problem. 442 | 443 | L9-05:12 What happens when we have default methods of same signatures while implementing multiple interfaces? 444 | To resolve default method calls, 445 | We can explicitly specify which default method is to be used, in implementing class. 446 | 447 | L9-07:21 What is the difference between Late Binding and Early Binding? 448 | Binding is the association of a method call with the method definition. 449 | i.e, when a method is called in java, the program control binds to the memory address where that 450 | method is defined. 451 | 452 | There are two types of binding in java, 453 | -> Early Binding | Static Binding 454 | -> Late Binding | Dynamic Binding 455 | 456 | 👉🏻 The Early Binding happens at Compile time, and late binding at Runtime. 457 | 458 | 👉🏻 In early binding the method definition and the method call are linked during compile time. 459 | And that can only happen when all information needed to call a method is available at the compile 460 | time only. 461 | -> private, static, and final methods - at compile time. 462 | 463 | 👉🏻 In early binding, the Reference Type information is used to resolve method calls, whereas in 464 | Late binding object information is used. 465 | 466 | 👉🏻 As method calls are resolved before run time, Static Binding results in faster execution of a 467 | program while Dynamic binding results in somewhat slower execution of code. 468 | 469 | However the major advantage of Dynamic binding or method overriding is its flexibility, as a single 470 | method can handle different type of objects at run time. 471 | This reduces the size of base code and makes code more readable. 472 | 473 | L10-00:02 Can we overload and override static methods? 474 | Yes we can overload static methods. But we cannot override them. We can define same method with same 475 | method signature in other Class but that will not be Method overriding. 476 | Because static method calls are resolved statically, i.e, at compile time. 477 | And in method overriding, method calls are resolved dynamically. 478 | 479 | L10-00:29 What is constructor overloading? 480 | Constructor overloading allows to have more than one constructor inside the class. 481 | So in Constructor overloading we have multiple constructors with different signatures, i.e, 482 | with different arguments. 483 | 484 | L10-01:45 What is this keyword in java? ⭐️ 485 | 'this' Keyword in java is a reference variable that refers to the current object. 486 | It holds the current state and behaviour for an object. 487 | 488 | L10-05:47 What is super keyword? 489 | Super keyword is used to refer to Parent Class objects. 490 | -> When a Derived Class and Base Class has same data members then we may use super keyword to access 491 | the parent classMembers. same with the methods, we use super keyword with method calls to specify 492 | that parent Class method will be invoked. 493 | 494 | L10-06:24 What is Constructor Chaining in java? ⭐️ 495 | In java, we can call one constructor from another. This is called Constructor Chaining. 496 | We have this and super keywords for that. 497 | -> this() is used to call another constructor from a constructor. 498 | -> super() is used to call the constructor of the super class from the constructor of base class. 499 | 500 | L11-00:01 Can we overload main method? 501 | Apart from the fact that JVM always looks for the main method to launch the program, main method is 502 | just like other methods. 503 | We can overload main method too, But JVM never gonna call that overloaded method. 504 | -> To execute that method we need to call that from the main method only. 505 | 506 | public static void main(){ 507 | //any implementation 508 | } 509 | 510 | public static void main(String[] args){ 511 | obj.main(); 512 | } 513 | 514 | L11-01:26 Can a final method be overloaded in java? 515 | Yes, final method can be overloaded but cannot be overridden. 516 | 517 | L11-01:36 What is IS-A and HAS-A relationship? 518 | IS-A relationship implies inheritance. i.e, if class 'A' extends class 'B', then A is-a B. 519 | For example, 520 | 521 | -> There is a 'Teacher' Class which extends a 'Person'. So here a person is a teacher. and it is 522 | transitive, like if another class 'MathTeacher' extends 'Teacher' class, then also 523 | MathTeacher is-a Person. 524 | 525 | -> when a class 'A' has-a member reference variable of type 'B' then A has-a B. for Example, 526 | College has-a Teacher. This is also known as Aggregation. 527 | 528 | L11-02:54 What is Stronger association: Composition or Aggregation? 529 | Composition is the stronger association than aggregation. Because in composition, the entities are 530 | highly dependent on each other. 531 | 532 | L11-03:09 How OOPs is different than Procedural programming? 533 | -> Procedural language is based on functions but object oriented language is based on objects. 534 | 535 | -> Procedural language exposes the data for that program, whereas Object oriented language 536 | encapsulates the data. 537 | 538 | -> Procedural language follows top down programming paradigm, but OOp language follows bottom up 539 | programming paradigm. 540 | 541 | -> Procedural language is complex in nature, so it is difficult to modify, extend and maintain. 542 | but OOP language is less complex in nature so it is easier to modify, extend and maintain. 543 | 544 | -> Procedural language provides less scope of code reuse but object oriented language provides more 545 | scope of code reuse. 546 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # java_interview_questions 2 | 3 | Find the complete Java Interview Questions Boot-Camp [Here](https://www.udemy.com/course/java-interview-questions-bootcamp-master-class-1000-java-questions/?utm_source=git) 4 | -------------------------------------------------------------------------------- /Serialization.java: -------------------------------------------------------------------------------- 1 | 2 | What is serialization?⭐️ 3 | Serialization is a mechanism of converting the state of an object into a byte stream. 4 | 5 | what is Deserialization?⭐️ 6 | Deserialization is reverse of serialization. 7 | The reverse process of creating object from sequence of bytes is called deserialization. 8 | 9 | How to make a Java class Serializable? 10 | By implementing Serializable interface. 11 | 12 | How many methods Serializable has? If no method then what is the purpose of Serializable interface? 13 | It is a marker interface.The main purpose of using marker interface is to tell 14 | the compiler that treat differently the object of the class which implemented marker interface. 15 | they are used to indicate something to compiler or JVM. 16 | 17 | Which methods are used during Serialization and DeSerialization process in Java? 18 | we call ObjectOutputStream.writeObject(saveThisobject) and 19 | to deserialize that object we call ObjectInputStream.readObject() method. 20 | Call to writeObject() method trigger serialization process in java. 21 | one important thing to note about readObject() method is that it is used to read bytes 22 | from the persistence and to create object from those bytes and its return an Object 23 | which needs to be type cast to correct type. 24 | 25 | What if we want to serialize or deserialize primitives? 26 | For every primitive corresponding method is there like writeInt(), readInt(), writeFloat() etc. 27 | 28 | Write a program to serialize and deserialize an object.⭐️ 29 | 30 | Can we serialize more than one object and write on same File? 31 | Yes 32 | 33 | What does transient mean? why we use transient keyword? 34 | //While serializing you want some of the members not to serialize? How do you achieve it? 35 | Transient mean not to serialize. 36 | 37 | What if we make static variable transient? 38 | Static variables are not part of object state. 39 | serialization is for objects.So static variables are not serialized.Thus no use of using transient. 40 | 41 | Which kind of variables is not serialized during Java Serialization?⭐️ 42 | transient and static variables. 43 | 44 | What if we make final variable transient?⭐️ 45 | It is useless to make a final variable transient. 46 | final variables participate in serialization directly by the value 47 | hence declaring a final variable as transient has no meaning.They will anyhow participate. 48 | 49 | What do you have to take care if file to read is having more than one object? 50 | The order in which they were serialized. 51 | It should be same while deserializing. Otherwise we will get ClassCastException. 52 | 53 | What if a member of class doesn't implement Serializable interface? 54 | //what is object graph?⭐️ 55 | If you try to serialize an object of a class which implements Serializable, 56 | but the object includes a reference to a non- Serializable class then a ‘NotSerializableException’ will be thrown 57 | at runtime 58 | whenever we are serializing an object, set of all objects which are reachable 59 | from that object will be serialized automatically. 60 | this gp of objects is called object graph 61 | In object graph every object should be serializable. 62 | otherwise we will get ‘NotSerializableException’. 63 | 64 | //Customized serialization 65 | 66 | Can we customize Serialization process in Java?⭐️ 67 | yes. We can customize behavior of object in serialization and deserialization 68 | by implementing two methods in serializable class: 69 | 70 | private void writeObject(ObjectOutputStream os) throws Exception 71 | private void readObject(ObjectInputStream is) throws Exception 72 | 73 | we can do any kind of pre or post processing task inside these methods. 74 | These methods are callback methods, we can not call these methods as you can see 75 | they are private to avoid being inherited, overridden or overloaded, these are automatically called by jvm. 76 | 77 | What is the need of customized serialization? 78 | To do any kind of pre or post processing task like encryption and decryption of fields which should be secured. 79 | or we can say to recover loss of information because of transient fields. 80 | 81 | what if the child of serializable does not implement serializable and we try to serialize or deserialize object 82 | of that class? 83 | All the child of serializable are by default serializable. Its inherited in child. 84 | 85 | If a class is Serializable but its super class is not, what will be the state of the instance variables inherited 86 | from super class after deserialization? 87 | If any variable is inherited from parent then jvm ignores the value and write the default value on file. 88 | Deserialization: 89 | jvm checks is the parent is serializable or not, if not then 90 | Jvm executes instance control flow and for that jvm always calls the no argument constructor. 91 | (can be default generated by compiler or provided by us) 92 | 93 | What if the parent is not serializable and is not having no arg constructor? 94 | If no arg constructor is not there we will get InvalidClassException. 95 | 96 | Suppose super class of a new class implement Serializable interface, how can we avoid new class to being serialized? 97 | To avoid Java serialization you can implement writeObject() and readObject() method in our serializable Class 98 | and throw NotSerializableException from those method. 99 | 100 | //externalization 101 | 102 | What is Externalizable? the difference between Serializable and Externalizable interface in Java?⭐️ 103 | Externalizable is an interface.(Not Marker) 104 | in serialization everything a taken care by jvm and programmer does not have any control.. 105 | With serialization its not possible to save a part of file which can create performance problems 106 | so we have externalization. 107 | with externalization programmer have control instead of jvm, 108 | based on our requirement we can save a part or the full object. 109 | 110 | In externalization interface there are 2 methods: 111 | 112 | 1.public void writeExternal(ObjectOutput oo) throws IOException //ObjectOutput : Parent of ObjectOutputStream 113 | 2.public void ReadExternal(ObjectInput io) throws IOException 114 | 115 | at the time of deserialization jvm again needs to create the object since the file only has a part of object 116 | it does not have the object and for that it needs no arg constructor 117 | thus externalizable class should contain public no arg constructor 118 | 119 | Can we use transient keyword with externalization? 120 | Yes, but it has no affect. 121 | Its not required. 122 | 123 | What is serialVersionUID and use of serialVersionUID?⭐️ 124 | jvm saves a unique identifier with every object based on the class file of the object while serializing. 125 | On receiver's machine while deserializing the jvm again generates the unique identifier for the same local class. 126 | If both does not match we will get InvaliClassException.else object will be deserialized. 127 | This unique identifier is serialVersion UID. 128 | 129 | What are the drawbacks of using default serialVersion UID generated by jvm? 130 | The both machines which are serializing and deserializing the object have to use same machine that is same operating 131 | system, same java version, same vendor as to generate same serialVersion UID. 132 | Both sender and receiver have to use same version of class file, after serialization any change in 133 | that file at receiver side will lead to creation of different ID.Thus deserialization will not be performed. 134 | Jvm uses complex process to generate serialVersionUID , which may affect performance. 135 | 136 | so we can have our own serialVersionUID: 137 | private static final long serialVersionUID = 1L; 138 | 139 | 140 | -------------------------------------------------------------------------------- /enum.java: -------------------------------------------------------------------------------- 1 | 2 | L1-01:00 What is enum? 3 | Enum is a special type in java that is used to define collection of constants. 4 | Enum of colours: 5 | 6 | enum Color{ 7 | Red,Green,Blue,White,Black; 8 | } 9 | 10 | This is how we declare enum. 11 | -> Semicolon is not mandatory if we are having only constants in enum. 12 | -> By using enum, we can create our own data type. 13 | 👉🏻 Data type of Red is 'Color'. 14 | 15 | L1-01:40 Where can we declare 'enum' type? 16 | Enum can be declared outside the class, and also inside the class. 17 | Note: Inside method we cannot create enum. 18 | 19 | L1-01:55 How to access Enum constants? 20 | Every 'enum' constant is static, so We access 'enum' constants using the Enum name. 21 | 22 | System.out.println(Color.Red); 23 | 24 | L1-02:14 How to get all constants of enum? 25 | For that we have values() method, that can be invoked with the enum name or enum instance. 26 | 27 | Color[] colors = Color.values(); 28 | for(Color c : colors){ 29 | System.out.println(c); 30 | } 31 | 32 | 👉🏻 Enum provides values() method implicitly. It is not present in Enum Class or Object class. 33 | 34 | L1-02:41 Whats difference between the enum, Enum, and Enumeration? 35 | 1. enum: It is a keyword to declare group of constants. 36 | 37 | 2. Enum: It is base Class for all enums. 38 | 👉🏻 Every 'enum' is direct child Class of Enum class. 39 | 40 | 3. Enumeration: It is an Interface present in java.util Package. 41 | It is a cursor that is used to get objects one by one from collection. 42 | 43 | L1-05:33 Can an 'enum' be declared as final? 44 | No. enum is implicitly final. They can not be declared final explicitly. 45 | 46 | L1-05:47 What modifiers are allowed to be used with enum? 47 | 'enum' can be public, , strictfp. 48 | If it is declared inside the class, then it can also be private, protected and static. 49 | 50 | 👉🏻 'enum' can not be abstract as they are implicitly final. 51 | 52 | L1-06:08 Can an 'enum' extend any class? 53 | No. Every 'enum' is direct subClass of java.lang.Enum class. 54 | -> Since java does not provide support for multiple inheritance hence, 55 | 👉🏻 It is not possible to extend Class with enum. 56 | 57 | L1-06:26 Can 'enum' have implementation classes? 58 | No. enum cannot have subclasses because they are final implicitly. 59 | 60 | 06:44 Can 'enum' implement interfaces? 61 | Yes. enum is a type just like Class and interfaces. 62 | 👉🏻 'enum' can implement interfaces. 63 | 64 | L1-07:03 Can we have Constructor in enum? 65 | Answer is yes! We can have Constructors as well as methods and variables inside the enum. 66 | 67 | Consider an enum Week, it can have constructor, other data members and methods: 68 | 69 | enum Week{ 70 | Sun,Mon,Tue,Wed,Thu,Fri,Sat; 71 | int a; 72 | Week(){ 73 | 74 | } 75 | public void m1(){} 76 | } 77 | 78 | L1-07:38 How constructors are invoked in enum? 79 | Answer is, every time we load the enum, the constructor is invoked. 80 | 81 | Every 'enum' constant is considered as 'enum' object. 82 | Whenever 'enum' gets loaded, for every 'enum' Constant, constructor will be invoked. 83 | 84 | L2-00:00 Can we create 'enum' object explicitly? 85 | No. We can not create 'enum' object with new keyword. 86 | Because if we want to create any new object w of type Week enum, then we can declare w as enum constant! So there is no need of creating enum object explicitly .. 87 | -> Week w: 88 | enum Week{ 89 | Sun,Mon,Tue,Wed,Thu,Fri,Sat,w; 90 | } 91 | 92 | Week w = new Week(); ❌ 93 | 94 | L2-00:32 Can we create parameterised constructors in enum? If yes then how to pass value to constructor? 95 | Yes, we can create parameterised constructors in enum. 96 | Sun("Holiday") 97 | 98 | L2-04:18 Can 'enum' have abstract methods? 99 | No. Because Enum are final. 100 | 101 | L2-04:37 Can we override toString() method for enum? 102 | Yes. We can override toString in Enum like any other class. 103 | -> But there is no need to overriding it, because Enum Class has already overridden the toString 104 | for every enum. 105 | 106 | Week w2 = Week.Wed; 107 | w2.toString(); 108 | 109 | 👉🏻 There is no need to call toString explicitly, because if we print any 'enum' constant, 110 | then by default it takes .toString() internally. 111 | 112 | L2-05:43 Can we create 'enum' constant outside of enum? 113 | Answer is no, we can only create 'enum' constant inside its enum. 114 | 115 | L2-06:08 Can constructors be public in enums? 116 | No constructors can not be public or protected either. 117 | 118 | L2-06:18 What does ordinal() method do? 119 | Ordinal method returns order of the 'enum' constant. 120 | 121 | L2-07:09 Can we use Enum with TreeSet or TreeMap in Java? 122 | Yes. We know we can use comparable types with treeSet or treeMap. 123 | 👉🏻 Since Enum by default impalements Comparable interface, they can be used inside TreeSet or TreeMap. 124 | 125 | L2-07:33 Can we use Enum in switch case in Java? 126 | Yes. Enum instances are constants so we can use them inside switch case. 127 | 128 | switch(Week){ 129 | case Sun: 130 | System.out.println("Peaceful day"); 131 | break; 132 | case Mon: 133 | System.out.println("Back to work."); 134 | break; 135 | case Sat : 136 | System.out.println("Party Time!"); 137 | break; 138 | default: 139 | System.out.println("Work Work Work."); 140 | } 141 | 142 | L2-08:07 Is Enum serializable in java? 143 | Yes, Java enums are automatically serializable as Enum Class implements Serializable interface. 144 | 145 | L2-08:32 How to convert a String to Enum in Java? 146 | The String can be converted to 'enum' by using valueOf() method. 147 | The 'enum' type provides valueOf() method which takes a String as an argument and returns 148 | corresponding 'enum' object. 149 | 150 | L2-10:03 What are benefits of using 'enum' in java? 151 | 👉🏻 'enum' are type safe, We cannot assign anything else other than those predefined constants of enum. 152 | 153 | 👉🏻 'enum' has its own namespace. 154 | 155 | 👉🏻 We can use 'enum' with switch case.. 156 | -------------------------------------------------------------------------------- /file IO.java: -------------------------------------------------------------------------------- 1 | //File IO 2 | 3 | L1-00:55 What is IO stream? What are the types of IO streams? 4 | Java I/O Stream is an abstraction that either produces or consumes data. 5 | Streams are flows of data, that we can either read from or write to! 6 | 7 | There are two types of I/O Streams: 8 | -> Character Streams 9 | -> Byte Streams 10 | 11 | L1-01:57 What are the classes available for the different streams in java? 12 | For Character streams there are two abstract classes present in java IO .. 13 | 1. java.io.Reader 14 | 2. java.io.Writer 15 | 16 | Similarly for Byte Streams: 17 | 1. java.io.InputStream 18 | 2. java.io.OutputStream 19 | 20 | L1-02:29 How these streams differ from each other? 21 | The InputStream classes receive data from various resources like 22 | a file, a pipe, a string, an array of bytes, and many other resources. 23 | 24 | OutputStream defines stream byte output. The destination may be 25 | an array of bytes, a file or any channel. 26 | 27 | Character streams have Reader and Writer: 28 | Which actually responsible for the flow of unicode characters. These takes information from a file 29 | and sends back to file! 30 | 31 | L1-03:13 What happens if any error occurs in case? 32 | All of the stream classes throw IOException in case of any errors. 33 | 34 | L1-03:26 How we can create any file? 35 | By creating an object of file class, we create a java file object to represent any resource. 36 | File f = new File("file.txt"); 37 | To create a file in the current working directory: 38 | f.createNewFile(); 39 | To create a new directory: 40 | f.mkdir(); 41 | 42 | L1-06:31 What if we use single slash while specifying file path? 43 | In windows, compiler takes single slash as escape. So single slash cannot be used to specify path.. 44 | instead of that we can use '//' 45 | 46 | File f = new File("D://Documents//file.txt"); 47 | 48 | L1-07:14 How to select all text files under any directory? 49 | File.listFiles() method returns an array of File objects contained in the particular directory. 50 | 51 | L2-00:01 What are different writers available for Character streams? 52 | There are three writers available for char streams: 53 | 1.FileWriter 54 | 2.BufferedWriter 55 | 3.PrintWriter 56 | 57 | L2-00:17 What is difference between fileWriter and BufferedWriter? 58 | With FileWriter we write character data or text data to any file. 59 | 60 | FileWriter fw = new FileWriter("File.txt"); 61 | Fw.write("any string"); 62 | fw.flush(); 63 | fw.close(); 64 | 65 | for appending the text that will be written with this object.. 66 | 67 | FileWriter fw = new FileWriter("File.txt",true); 68 | 69 | BufferedWriter: 70 | BufferedWriter uses internal buffer to write data into file, other than this, 71 | It is similar to FileWriter. 72 | -> BufferedWriter can not communicate with file directly. We have to use other writer with it. 73 | 74 | BufferedWriter bw = new BufferedWriter(fw); 75 | bw.write("Writing with BufferedWriter"); 76 | bw.flush(); 77 | bw.close(); 78 | 79 | In file writer we have to provide additional line separator (\n) to write in new line. 80 | But in BufferedWriter we have a method newLine() to provide line separator. 81 | 82 | L2-03:55 When we had these two writers, What is the need of PrintWriter then? 83 | PrintWriter is the most enhanced writer. It overcomes the little limitations that we had with 84 | filewriter and bufferedWriter. 85 | For example, 86 | We were allowed to write char, string types only with those writers. 87 | -> What if we want to write data of different data types? 88 | PrintWriter allows us to do so. 89 | 90 | -> PrintWriter can communicate directly to file and also can communicate via any other writer.. 91 | 92 | PrintWriter pw = new PrintWriter("File.txt"); 93 | PrintWriter pw = new PrintWriter(new FileWriter("File.txt")); 94 | 95 | PrintWriter pw = new PrintWriter("abc.txt"); 96 | pw.write(100); //this will write d to file 97 | Pw.println(100); //this will write int 100 and will separate line. 98 | pw.println(true); //this will write boolean true and separate line.. 99 | pw.flush(); 100 | pw.close(); 101 | 102 | L2-05:05 Why we use flush() and close()? 103 | Flush() method is used to clear all the data characters stored in the buffer and clear the buffer. 104 | It flushes the stream so that we get assured that the data has properly written to file. 105 | 106 | Close() method is used to close the character stream and it releases system resources associated 107 | with the stream. 108 | 109 | Note that, flush method is applicable for all the Writers and close() is for all readers and writers.. 110 | 111 | L3-00:01 How to read any file? 112 | There are two readers to read the file: 113 | FileReader 114 | BufferedReader 115 | 116 | L3-00:13 Difference between FileReader BufferedReader? 117 | FileReader reads the data from a file in the forms of characters.. 118 | 119 | FileReader fr = new FR("abc.txt"); 120 | char[] ch = new char[(int)f.length()]; 121 | fr.read(ch); //this will copy data from file into char array 122 | 123 | for(char ch1: ch){ 124 | Sysout ch1; 125 | } 126 | 127 | With file reader we read data character by character, not line by line. 128 | For that, we have BufferedReader. 129 | 130 | BufferedReader allows us to read file by char and by line too. 131 | 132 | BufferedReader br = new BufferedReader(new FR("abc.txt")); 133 | String line = br.readLine(); 134 | while(line!=null){ 135 | System.out.println(line); 136 | line = br.readLine(); 137 | } 138 | br.close(); 139 | 140 | BufferedReader is most efficient reader for reading the file because it buffers the input from the 141 | specified file. 142 | 143 | -> Compared to FileReader, BufferedReader reads large chunks of data from file at once and 144 | keep this data in a buffer. 145 | When we ask for the next character or line of data, it gets retrieved from that buffer.. 146 | This makes bufferedReader most efficient.. 147 | 148 | L5-00:06 Explain Hierarchy of Reader-Writer. 149 | 150 | When to use ByteStreams? 151 | Byte oriented streams process data byte by byte, so byte stream is suitable for processing raw data 152 | like binary files. 153 | And when we have text files, then the character streams are useful. 154 | 155 | When to use what: FileInputStream and FileReader. 156 | Both InputStream and Reader are used to read data from the source (either file or socket). 157 | 158 | InputStream is used to read binary data, while Reader is used to read text data, that is, 159 | Unicode characters. 160 | 161 | We should prefer Readers instead of InputStreams in case of text files. 162 | Buffered reader is suggested to use to read text files and FileInputStream is used to read raw 163 | streams of bytes from any source, which can be file or socket in java. 164 | 165 | When to use what: FileOutputStream and FileWriter 166 | To write something to a file, we use FileOutputStream, FileWriter etc. 167 | With FileOutputStream class, we can write byte oriented as well as character oriented data. 168 | But Note that it is always preferred to use FileWriter/PrintWriter to write character data to file. 169 | 170 | What are the FilterOutputStream and FilterInputStream? 171 | FilterOutputStream is another implementation of OutputStream. 172 | It further has different implementation classes: BufferedOutputStream 173 | DataOutputStream 174 | It is used less individually.! 175 | 176 | Similarly, FilterInputStream have subclasses: BufferedInputStream 177 | DataInputStream 178 | 179 | Which superstructure Class allows reading data from an input byte stream in the format of primitive data 180 | types? 181 | 'DataInputStream' Class is used to read primitive data. 182 | Methods: readInt(), readByte(), readChar(), readDouble(), readBoolean() 183 | 184 | DataInputStream Class can not communicate directly to files.. we can use this as, 185 | 186 | DataInputStream dInput = new DataInputStream(new FileInputStream("File.txt")); 187 | 188 | and similarly, DataOutputStream is used to write Primitives to file. 189 | 190 | How BufferedOutputStream is different from BufferedWriter? 191 | They are almost similar but BufferedOutputStream is used to write raw bytes whereas 192 | BufferedWriter writes characters. 193 | BufferedWriter: Provides buffering for Writer Instances which makes performance fast. 194 | BufferedOutputStream: Used for buffering output streams. Internally it uses buffer to store data. 195 | 196 | Methods to write data, 197 | write(int b): for writing specified byte to stream 198 | write(byte[] b, int off, int len): to write bytes from specified byte array starting with given offset 199 | 200 | What is difference between InputStreamReader and BufferedReader? 201 | -> InputStreamReader creates a new stream object that can be used to read data from the specified source. 202 | It reads bytes and decodes them into characters. 203 | BufferedReader is an "abstraction" that reads text from a character-input stream. 204 | It 'buffers' characters so as to provide efficient reading of characters and lines. 205 | 206 | -> BufferedReader reads a couple of characters from the specified stream and stores it in a buffer. 207 | This makes input faster. 208 | InputStreamReader reads only one character from specified stream and remaining characters still remain 209 | in the stream. 210 | 211 | What do you know about add-on classes? 212 | Add-on classes provides additional properties to the existing threads. 213 | Examples of classes: BufferedOutputStream , BufferedInputStream , 214 | BufferedWriter – buffers the stream and improves performance. 215 | 216 | What class-add-on allows you to speed up reading / writing by using a buffer? 217 | java.io.BufferedInputStream (InputStream in) || BufferedInputStream (InputStream in, int size), 218 | 219 | java.io.BufferedOutputStream (OutputStream out) || BufferedOutputStream (OutputStream out, int size), 220 | 221 | java.io.BufferedReader (Reader r) || BufferedReader (Reader in, int sz), 222 | 223 | java.io.BufferedWriter (Writer out) || BufferedWriter (Writer out, int sz) 224 | 225 | What classes allow you to convert byte streams to character and back? 226 | OutputStreamWriter 227 | InputStreamReader 228 | 229 | Will this code compile? 230 | ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt"))); 231 | Yes 232 | 233 | Explain hierarchy of InputStream and OutputStream. 234 | -------------------------------------------------------------------------------- /file-NIO.java: -------------------------------------------------------------------------------- 1 | What is NIO?⭐️ 2 | Non-Blocking I/O: Java provides a different way to work with I/O than the standard I/O Apis. 3 | -> NIO supports buffer-oriented and channel based approach for I/O operations. 4 | -> NIO introduced in java 1.4 and with JDK 7, NIO system is expanded. 5 | -> NIO is widely used in the File handling. 6 | 7 | What are fundamental components of NIO? 8 | Java NIO has these fundamental components: 9 | 1. Channels 10 | 2. Buffers 11 | 3. Selectors 12 | 4. Non-blocking I/O 13 | 14 | Channel and Buffers: Data is written from a buffer to a channel and read from a channel to a buffer. 15 | 16 | Selectors: Selectors are used to monitor the multiple channels for the events like 17 | when data is arrived, connection is opened. 18 | 19 | Non-Blocking I/O: In NIO, Threads are allowed to go on and do something else in mean time of 20 | performing any task. 21 | 22 | In which Package the NIO classes are present? 23 | java.nio.* 24 | -> also there are sub-packages inside this Package. 25 | java.nio.charset 26 | java.nio.channels 27 | java.nio.file 28 | ..and many more 29 | 30 | What is Channel? How many channels are there in java?⭐️ 31 | In NIO, channel is the medium to transport data efficiently. 32 | Channel in an Interface which provides access to low-level I/O services in a controlled way. 33 | Methods: 34 | 1. isOpen() : this Tells whether or not this channel is open. 35 | 2. close() : closes the channel. 36 | 37 | Channels: 38 | DatagramChannel 39 | SocketChannel 40 | FileChannel 41 | ServerSocketChannel 42 | 43 | Which channel is used for reading data from files? 44 | FileChannel. It is used for reading data from files. 45 | -> We cannot create its object directly as it is an abstract class. 46 | for object creation - getChannel() method is used. 47 | 48 | What other channels are used for? 49 | DatagramChannel is used to read and write data over the network via User Datagram protocol (UDP). 50 | SocketChannel can read write data over network via Transmission Control protocol (TCP). 51 | ServerSocketChannel allows user to listen the incoming TCP connections, same as a web server. 52 | 53 | Note that, for every incoming connection a socket channel is created. 54 | 55 | What are NIO Buffers?⭐️ 56 | NIO buffers are used to make interaction with NIO channels. 57 | Block of memory into which we can write data, from which we can read data. 58 | 👉🏻 In NIO system this memory block is wrapped with an NIO buffer object. 59 | 60 | How many Buffers we have in java? 61 | There is a buffer type for every primitive type. 62 | 1. CharBuffer 63 | 2. DoubleBuffer 64 | 3. IntBuffer 65 | 4. LongBuffer 66 | 5. ShortBuffer 67 | 6. FloatBuffer 68 | 69 | There is ByteBuffer which is Mostly used buffer type. 70 | 7. ByteBuffer 71 | 72 | How to create ByteBuffer? 73 | To create ByteBuffer, we have to allocate a buffer. For that we invoke allocate() method, 74 | 75 | ByteBuffer b = ByteBuffer.allocate(capacity); 76 | 77 | to write data, we use put() method. 78 | 79 | How to transfer data between channels and buffers? 80 | 81 | public class Demo { 82 | public static void main(String[] args) throws IOException { 83 | FileInputStream input = new FileInputStream("File1.txt"); 84 | ReadableByteChannel src = input.getChannel(); 85 | 86 | FileOutputStream output = new FileOutputStream("File2.txt"); 87 | WritableByteChannel dest = output.getChannel(); 88 | 89 | copy(src,dest); 90 | input.close(); 91 | output.close(); 92 | } 93 | 94 | private static void copy(ReadableByteChannel src, WritableByteChannel dest) throws IOException { 95 | ByteBuffer b = ByteBuffer.allocate(1024*20); 96 | while (src.read(b) != -1) 97 | { 98 | // The buffer is used to drained 99 | b.flip(); 100 | // keep sure that buffer was fully drained 101 | while (b.hasRemaining()) 102 | { 103 | dest.write(b); 104 | } 105 | b.clear(); // Now the buffer is empty, ready for the filling 106 | } 107 | } 108 | } 109 | This will write file1 data to file2. 110 | 111 | Can we transfer data between channels?⭐️ 112 | Yes. In Java NIO we can directly transfer the data from one channel to another. 113 | 114 | Methods present in FileChannel: 115 | 1. FileChannel.transferTo() method 116 | 2. FileChannel.transferFrom() method 117 | 118 | The transferTo(position, count, target) method allows the data transfer from a FileChannel 119 | into some other channel. 120 | 121 | The transferFrom(src, position, count) method allows the data transfer from a source channel 122 | into the FileChannel. 123 | 124 | What do you understand by Scattering reads and Gathering writes?⭐️ 125 | 'Scattering read' is reading the data from a single channel into multiple buffers. 126 | 'Gathering write' is writing the data from a multiple buffers into a single channel. 127 | 128 | We have ScatteringByteChannel, and GatheringByteChannel channels for this. 129 | 130 | What Selectors are for? 131 | Selectors are used for handling multiple channels using a single thread. 132 | 133 | Selectors are created as, 134 | Selector selector = Selector.open(); 135 | 136 | -> invoke the register() method on various channels objects to register our interest in various 137 | I/O events. 138 | 139 | What is difference between IO and NIO?⭐️ 140 | -> The important distinction between IO and NIO is that, 141 | Original IO deals with data in streams, whereas NIO deals with data in blocks. 142 | IO is stream oriented and NIO is buffer oriented. 143 | 144 | -> IO streams are blocking whereas NIO can be blocking or non-blocking. 145 | 146 | What do threads do in the mean time? 147 | Threads spend their time performing IO on other channels. 148 | -> In NIO a single thread can manage multiple channels of input and output. 149 | 150 | NIO have Selectors for selecting or registering in different channels. 151 | 152 | -> you may also get asked some queries like, 153 | 154 | If you have three sockets, then how many threads you will need to handle that? 155 | So answer to this is, using NIO we can operate on multiple channels using the same thread. 156 | 157 | What is the byte order of ByteBuffer? 158 | Byte order is the order in which a multi-byte quantity is stored into the memory. 159 | There are two types of Byte order, 160 | 1. Big-Endian 161 | 2. Little-Endian 162 | 163 | 👉🏻 Byte Buffer has big-endian as its default byte order.. 164 | 165 | What is the difference between Direct and Non-Direct buffer in java?⭐️ 166 | A byteBuffer is either direct or non-direct. 167 | If it is Direct byte buffer, then JVM will perform native I/O operations directly upon it. 168 | 169 | Direct byte buffer can be created: 170 | -> by invoking the allocateDirect() factory method of this class. 171 | -> by mapping a region of a file directly into memory. 172 | 173 | 👉🏻 Non direct buffer is just a wrapper around byte array and it resides in Java heap memory, 174 | whereas Direct buffer resides outside of JVM and memory is not allocated from heap! 175 | 176 | What is the memory mapped buffer in Java? 177 | MappedByteBuffer is a subclass of ByteBuffer, which is actually a Direct Byte Buffer whose content 178 | is a memory mapped region of a file. 179 | 180 | It is created by FileChannel.map() method. 181 | 182 | What is the difference between ByteBuffer and CharBuffer in Java? 183 | A ByteBuffer is a buffer that holds (8-bit) byte values and CharBuffer holds (16 bit) char values.. 184 | -------------------------------------------------------------------------------- /flow control.java: -------------------------------------------------------------------------------- 1 | -- Flow Control -- 2 | 3 | L1-00:24 What are Control flow statements? 4 | These are the statements which are used for - 5 | Decision making 6 | Looping 7 | Changing the control flow of a program on a particular case. 8 | 9 | L1-00:58 Explain the if-else statement. | Explain how if-else changes the control flow of program? 10 | if-then: 11 | if(boolean arg){ 12 | //code to be executed if condition returns true. 13 | } 14 | 15 | for example, 16 | public class Exercise{ 17 | public static void main(String[] args){ 18 | int val= 25; 19 | if(val<=30){ 20 | //execution will go inside the if block only if the condition returns true. 21 | } 22 | } 23 | } 24 | 25 | else: else clause is optional. 26 | public class Exercise{ 27 | public static void main(String[] args){ 28 | int val= 100; 29 | if(val<=30){ 30 | //... 31 | }else{ 32 | //...this block will be executed 33 | } 34 | } 35 | } 36 | 37 | L1-05:32 What if we have more than one or two conditions in program? Do we need to write if clause again and again? 38 | For this, we have else-if construct. 39 | 40 | public class Exercise{ 41 | public static void main(String[] args){ 42 | int val= 50; 43 | if(val<=30){ 44 | //... 45 | }else if(val>30 && val<= 50){ 46 | //....this will be executed. 47 | }else if(val>50 && val<=70){ 48 | //... 49 | }else{ 50 | //... 51 | } 52 | } 53 | } 54 | 55 | Note that, In java, if-else statement can only have boolean expressions as conditions. 56 | 57 | L1-08:47 There is a boolean value a = true, and b = false. Can we put a=b condition in if block? 58 | boolean a = true; 59 | boolean b = false; 60 | if (a=b) {System.out.println("");} 61 | 62 | Yes we can put such conditions. 63 | 64 | ----------------------------------------------------------------------------------------------------------- 65 | 66 | L1-10:29 Explain switch case. How it works and what object types can be used in the switch clause? 67 | The Switch clause provides several execution paths with case and default clause. 68 | -> Types it takes as switch values : byte, short, char, int and their wrapped versions. 69 | including enums and strings. 70 | 71 | for example, 72 | int yearsOfWorkingExperience = 8; 73 | switch(yearsOfWorkingExperience){ 74 | case 0: 75 | System.out.println("Fresher"); 76 | break; 77 | case 1: 78 | System.out.println("Junior Developer"); 79 | break; 80 | case 2: 81 | System.out.println("Developer"); //this will get executed 82 | break; 83 | case 3: 84 | System.out.println("Senior Developer"); 85 | break; 86 | default: 87 | System.out.println("Team Lead"); 88 | } 89 | 90 | There are 4 possible cases and one default case. 91 | 92 | L1-11:43 How it works? 93 | switch statement evaluates each case expression for matching the value of variable that it is having. 94 | Then executes all the statements that are written inside that case if that case is matched. 95 | 96 | After executing the case we write break, so that the execution will break there and exits the switch 97 | statement. 98 | And if the none of the written cases are matched then the default block will get executed.. 99 | 100 | L1-12:43 What if we do not write the default block in switch statement? 101 | When none of the case will be matched, then nothing will get executed since default block is not there. 102 | 103 | L1-13:17 What will happen when we forget to put break statement in case clause? 104 | In such case, it will continue executing all the cases which are written after that, 105 | until the break statement not found or until the end of switch statement. 106 | 107 | switch(yearsOfWorkingExperience){ 108 | case 0: 109 | System.out.println("Fresher"); 110 | break; 111 | case 1: 112 | System.out.println("Junior Developer"); 113 | case 2: 114 | System.out.println("Developer"); 115 | case 3: 116 | System.out.println("Senior Developer"); 117 | break; 118 | } 119 | 120 | L1-14:24 What if we put the default block in between the case labels? 121 | We can put the default block anywhere, compiler will not raise any error. But the best practice is 122 | we should always write the default block at the end. 123 | 124 | L1-15:32 What is more preferable to use, switch over if-else or if-else over switch? 125 | The if-else statement is used 126 | -> when we need to check ranges of values or multiple conditions.. 127 | 128 | public class Exercise{ 129 | public static void main(String[] args){ 130 | int val= 10; 131 | if((val%2)==0){ 132 | System.out.println("Number is even"); 133 | }else{ 134 | System.out.println("Number is odd"); 135 | } 136 | } 137 | 138 | The switch is used 139 | -> when we need to test a single variable against many single values. 140 | when several values executes the same code. 141 | 142 | int yearsOfWorkingExperience = 1; 143 | 144 | switch(yearsOfWorkingExperience){ 145 | case 0: 146 | System.out.println("Fresher"); 147 | break; 148 | case 1: 149 | case 2: 150 | System.out.println("Developer"); 151 | break; 152 | case 3: 153 | System.out.println("Senior Developer"); 154 | break; 155 | default: 156 | System.out.println("Team Lead"); 157 | } 158 | 159 | 160 | L2-00:16 What types of loops present in java? 161 | for, while, and do-while 162 | 163 | 1. For loop: It provides a way to iterate over a range of values. 164 | We use for loop when we know in advance that how many times a task is going to be repeated. 165 | 166 | for(initialization; condition; incrementation/decrementation){ 167 | //statements or code to be executed 168 | } 169 | 170 | for(int i=0;i<10;i++){ 171 | System.out.println(i); 172 | } 173 | 174 | L2-02:14 -> What if we do not put the condition in for loop? 175 | If we do not put the condition, then loop will execute for infinite times since we did not provide 176 | the condition and by default it will take true for that. 177 | 178 | L2-03:27 -> What if we do not put the incrementation argument in for loop? 179 | If we do not increment the value then the 'i' will remain 0 always and will get printed for 180 | infinite times. 181 | 182 | L2-03:36 -> What if we put break statement inside the for loop? 183 | In such case, the loop will get terminated. 184 | 185 | 2. While loop: This loop is used to iterate a part of the program several times. 186 | We use while loop when the number of iteration is not fixed. 187 | 188 | We put only condition as argument with while. 189 | 190 | int i=10; 191 | while(i>1){ //condition 192 | System.out.println(i); //statements 193 | i--; //incrementing i 194 | } 195 | 196 | 3. do-while loop: This loop is a variation of the while loop where the condition is evaluated at 197 | the bottom of the loop. 198 | do-while guarantees that the code will execute at least once! 199 | 200 | do{ 201 | //statements to get executed 202 | } while(condition) 203 | 204 | L2-07:38 What is enhanced for loop? 205 | The enhanced for loop is designed to iterate through all the elements of any collection,enum, array etc. 206 | 207 | for(DataType var : Collection){ 208 | //statements to be executed 209 | } 210 | 211 | L2-09:28 Except the arrays, which type of object we can iterate over using the foreach loop? 212 | We can iterate any object with this loop, which implements the Iterable interface. 213 | for example, lists, Set, and all the other collections. 214 | 215 | L2-11:57 What are the difference between classic for loop and foreach loop? 216 | foreach is used to loop over a container which must implement the Iterable interface And 217 | there is no such requirement for the traditional for loop. 218 | 219 | for loop is present from the start in java, whereas the foreach loop was added in java in 1.5 version 220 | 221 | Enhanced for loop always executes in sequence.the counter is increased by one. 222 | whereas in for loop we can change the incremental step as per our requirement. 223 | 224 | foreach loop can iterate only in incremental order. 225 | But in traditional for loop we can also iterate in decremental order. 226 | By writing i-- in step counter to go backward 227 | 228 | we don't have the access to array index in foreach loop while iterating. 229 | so, we cannot replace the element at the given index.. whereas using for loop 230 | we are allowed to replace any element in the array by its index. 231 | 232 | L2-14:23 How the foreach loop is different from foreach() method? 233 | Enhanced for loop or foreach loop iterates over the collection objects or the objects which implements 234 | Iterable interface. This is just the enhanced version of for loop.. 235 | 236 | Foreach method is introduced in java 8, in the interface iterator as default method. 237 | We can iterate over any collection by passing the Lambda expression as argument. 238 | 239 | L2-18:08 What are the various transfer statements used in java? 240 | There are six language constructs for transferring control in java: 241 | 1. break: This statement is used to terminate the current loop or flow. 242 | 243 | 2. continue: This is used to stop the execution in loop for the current iteration only. 244 | 245 | 3. return: This statement stops the execution of a method and transfers the control to the caller. 246 | 247 | 4. try-catch-finally 248 | 249 | 5. throw 250 | 251 | 6. assert 252 | -------------------------------------------------------------------------------- /java-lang.java: -------------------------------------------------------------------------------- 1 | //java.lang Package 2 | 3 | Why do not we need to Import java.lang Package in class?⭐️ 4 | We do not need to Import java.lang Package. Because all the classes in this Package are imported 5 | by default. 6 | 7 | Like the printing statement-> System.out.println(); 8 | -> System is java.lang.System class, while using it we do not need to write its fully qualified name 9 | because all the public types present inside this Package are already imported in every class. 10 | 11 | Name few classes of Package java.lang? 12 | Object, String, All wrapper classes, Math, System, StringBuffer, StringBuilder, Thread, Throwable etc. 13 | 14 | What is the base Class for every class?⭐️ 15 | java.lang.Object Class is the base Class for every class. 16 | 17 | Why java.lang.Object is the base class? 18 | Object Class contains the most common methods that are useful for any java object. 19 | equals(), hashCode() etc. 20 | -> To make those available for every object, Java made every Class to be child Class of object 21 | directly or indirectly. 22 | 23 | What are the common methods provided by object class? 24 | 25 | equals() : used to compare two objects, returns true if any object is equals to this object. 26 | 👉🏻 equals() method compares the references of object. 27 | 28 | toString(): The most useful method, returns a string representation of an object. 29 | 30 | hashCode(): this method returns the hash code value for the object. 31 | 32 | clone(): creates and returns a copy of the object. 33 | 34 | getClass(): this return the runtime Class of the object. 35 | 36 | wait(), notify(), notifyAll(): These methods do play a part in synchronizing the activities of 37 | independently running threads in any program. 38 | 39 | finalize(): This method is called by garbage collector on any object. This is deprecated since java 9. 40 | 41 | What is a hashcode?⭐️ 42 | For every Object, JVM generates a unique number which is actually the Hash code. 43 | This hash value can be used to search object in a collection. 44 | 45 | 👉🏻 it is not the address of the object its a distinct number thats generated for every object. 46 | 47 | Whats the difference between an object and an object reference? 48 | An object is an instance of a class, and an object reference is a pointer to the object. 49 | There may be many references to a single object. 50 | 51 | Is String a datatype? 52 | String in java is not a primitive data type like int, long, char. It is a Class or can be 53 | considered as user defined type. 54 | 55 | 👉🏻 String Class is defined inside java.lang Package. 56 | 57 | Is String a Wrapper class? 58 | No, It is not. 59 | 60 | How String is different from a char array? 61 | 1. Both of them contains the sequence of characters, but String is represented as a single data type, 62 | whereas char array is a collection of data type. 63 | 64 | 2. Strings are immutable and characters are mutable. 65 | That means, once we created the string, we cannot modify it by any way. If we modify the string, 66 | it will always result in creating a new string. 67 | 68 | String str = "John"; 69 | str = "Rohn"; //this will create a new string in memory. 70 | 71 | 3. Various built in functions like sustring(): used to get a part of string, 72 | charAt(): used to get particular character. 73 | These functions can be used with string, but with charArrays, we cannot use them. 74 | 75 | 4. String can be stored in memory in any way, while elements of character array are stored contiguously 76 | in increasing memory locations. 77 | 78 | 5. String are stored in string pool whereas, Character array are stored in heap memory in java. 79 | 80 | What is the String pool?⭐️ 81 | The String constant pool is an area in java heap memory where Strings are stored. 82 | 👉🏻 In String pool, there will be no String objects having the same content. 83 | 84 | String s1 = "John"; 85 | String s2 = "John"; //will point to same object 86 | 87 | How these Statements are different?⭐️ 88 | 1. String str = "Basic"; 2. String strr = new String("Basics"); 89 | 90 | String newStr = "Basic"; 91 | 92 | These are the two ways to create string object: 93 | 1. using string literal //Inside String Pool 94 | 2. using 'new' keyword. //Inside Heap Area 95 | 96 | char[] arr = {'a','b'}; 97 | String object = new String(arr); 98 | 99 | String s = "Hello"; 100 | String newS = s.concat(" programmer!"); 101 | 102 | //intern() 103 | 104 | String reUseThis = newS.intern(); 105 | 106 | What is String Interning?⭐️⭐️ 107 | 108 | what intern() method is used for?⭐️ 109 | 110 | How many objects will be created? 111 | String s1 = "BasicsStrong"; 112 | String s2 = new String("BasicsStrong"); 113 | String s3 = "BasicsStrong"; 114 | String s4 = new String("Basics"); 115 | ///String s5 = s4.concat(" here"); 116 | 117 | Answer is 4, two object inside String constant pool. 118 | and two objects will be created inside heap Area. 119 | //SCP does not allow duplicate objects 120 | 121 | Why String is Immutable and Final in java? 122 | There are many benefits of String because of its immutability: 123 | 124 | The concept of String constant pool is possible because String is immutable. 125 | This increases security because no one can change the string content. 126 | 127 | String are safe to use in multithreaded environment (where we work with multiple threads at a time), 128 | because we do not need any synchronization on Immutable objects. 129 | 130 | //All the Wrapper classes are immutable 131 | 132 | Can we create an immutable class?⭐️ 133 | Yes! We can create immutable class, for that We just need to define the Class as final. 134 | we can define all the fields as final. 135 | -> By not providing any method to change the state of the object, we can create an immutable class. 136 | 137 | Is String a keyword in java? 138 | Answer is no, String is not a keyword. 139 | 140 | Which of them is better to store password? String or Char array? 141 | String is not recommended to use as data type for passwords, because of their immutability. 142 | string are stored in String pool, so once its created it always stays in the pool until Garbage 143 | collector erase it. 144 | So even though we are done with password kind stuff, it will be available in memory for the very long 145 | duration. It is a security risk, because anyone who is having access to memory can find password easily. 146 | 147 | While, char array can be modified and we can set elements of char array to blank or null once we are 148 | done with it. This controls the duration of it of being available in memory. 149 | 150 | Difference between String, StringBuffer, StringBuilder.⭐️ 151 | StringBuilder and StringBuffer are another classes which are used to store strings. 152 | 153 | Strings are immutable and Final. 154 | Whenever we do String manipulation, it generates a new String and discards the older String for garbage 155 | collection. 156 | -> These generates a lot of garbage in heap, so java has provided String buffer and string builder 157 | classes that are mutable and can be used for string manipulation. 158 | 159 | StringBuffer vs StringBuilder: 160 | StringBuilder was introduced in java 1.5. 161 | StringBuffer operations are thread-safe and synchronized, whereas StringBuilder operations are not 162 | thread safe. That makes its performance faster than StringBuffer. 163 | 164 | Both StringBuffer and StringBuilder has not overriden the equals method 165 | so equals of object class gets executed which compares references. 166 | 167 | How to check if two strings are equal?⭐️ 168 | There are two ways: 169 | Using == and using equals() method. 170 | 171 | == checks for the reference of the string. 172 | equals() checks for Value of strings. 173 | 174 | 👉🏻 equals() method of object Class checks for references, but String has different 175 | implementation of equals() method. It checks for the values of the string. 176 | 177 | What will be the output of this code snippet? 178 | 179 | String s1 = "Basics"; 180 | StringBuffer s2 = new StringBuffer("Basics"); 181 | System.out.println(s1.equals(s2)); 182 | 183 | Both s1 and s2 have the same value, but this statement will print false. 184 | Because the s2 is not of string type. 185 | 186 | How to convert String to charArray and byteArray? 187 | To get char array from string, we use toCharArray() method, 188 | getBytes() is used to get bytes from a string. 189 | 190 | What does substring() method do? 191 | substring() creates and returns a new string object by taking a portion of original string. 192 | 193 | Which one of them is final class. String, StringBuffer or StringBuilder. 194 | All of them are final classes. 195 | 196 | What is the use of Math class? 197 | Math Class provides the mathematical functions. like, 198 | sqrt(), exp(), log(), abs(). 199 | 200 | Can we instantiate the Math class? 201 | No its cannot be instantiated, because it is final and constructor is private. 202 | 203 | Without creating instance how can we use Math Class functions?⭐️ 204 | All the methods of this Class are static. We can directly invoke them with classname. 205 | 206 | What's Autoboxing and unboxing in java?⭐️⭐️ 207 | Autoboxing and Unboxing : Introduced in Java 1.5 to automatically convert the primitive type into 208 | boxed primitive that is Object of Wrapper class. 209 | 210 | For example, when java automatically converts a primitive type like int, into respective wrapper 211 | Class Object, i.e, integer, then it is called Autoboxing. 212 | 213 | Unboxing is just the opposite case of it. Here, Integer object is converted into primitive int. 214 | 215 | When do Autoboxing and Unboxing occur?⭐️⭐️ 216 | Autoboxing and unboxing can occur wherever an object is expected and primitive is available. 217 | For example, 218 | A method expect an object argument but we pass primitive. In that case java automatically converts 219 | primitive into equal value object. 220 | 221 | -> The classic use of Autoboxing is in Collection. A collection is a group of objects. 222 | So auto boxing is used with collections to add primitive types.. 223 | --------------------------------------------------------------------------------