interview questions

  • Exception

    • unchecked exception: error(out of memory) and runtime exception(outof boundary)
    • IO exception(socket, file not found)
  • Most important feature

    • platform independent language: we can write and compile the java code in one platform and can execure the class in any other supported platform
    • all java classes have same .class files, different platforms have different jvms to exectue.
  • difference between a JDK and JVM

    • jdk contains tools needed to develop the java programs, and jre to run the programs
    • jre( java runtime environment) = jvm (java virtual machine)+ java packages classes (util, math, lang)
    • jvm provides a platform- independent way of executing code, which means compile once in any machine and run it any where
  • what is a pointer and does java support pointers?

    • pointer is a variable to store the address. Imporper handling of pointers leads to memory leaks and reliability issues hence java doesn’t support the usage of pointers
  • what is the base class of all classes?
    -java.lang.object

  • does java support multiple inheritance?

    • java doesn’t support multiple inheritance
  • is java a pure object oriented language?
    -No, java uses primitive data types and hence is not a pure object oriented language

  • are arrays primitive data types?
    -no, arrays are objects
  • what is difference between path and classpath?
    • path and classpath are operating system level environment variables. Path is used define where system can find the executables(.exe) files and classpath is used to specify the location .class file
  • what are local variable
    • local variables are those which are declared within a block of code like methods. local variables should be initialized before accessing them.
  • what are instance variable?
    • instance variables are those which are defined at the class level. Instance variables need not be initialized before using them as they are automatically initialized to their default values
  • how to define a constant variable in java?
    • static and final
  • should a main() method be compulsorily declared in all java classes?
    • not required. main() method should be defined only if the soure class is a java application
  • what is the return type of main() method?
    • void
  • why is the main() method declared static?
    • main() method is called by the jvm even before the instantiation of the class hence it is declared as static
  • can a main() method be overloaded?
    • yes, you can have any number of main() methods with different method signature and implementation in the class.
  • can a main() method be declared final?
    • yes, any inherting class will not be able to have it’s own default main() method
  • can a soure file contain more than one class declaration?
    • yes, a single source file can contain any number of class declarations but only one of the class can be declared as public
  • what is a package?
    -package is collection of related classes and interfaces. package declaration should be first statement in a java class.
  • which package is imported by default?
    • java.lang.package is imported by default even without a package declaration.
  • what is the purpose of declaring a variable as final?

    • a final variable’s value can’t be changed, final variables should be initialized before using them.
  • what is the impact of declaring a method as final?

    • a method declared as final cannot be overridden. A sub-class can’t have the same method signature with a different implementation.
  • I do not want my class to be inherited by any other class, what should i do?

    • you should declare your classes as final, but you cann’t define your class as final if it is an abstract class. A class declared as final can’t be extended by any other class.
  • can you give few examples of final classes defined in JAVA API?
    -java.lang.string, java.lang.math are final classes.

  • how is final different from finally and finalize()?
    • final is a modifer which can be applied to a class or a method or a variable. final class can’t be overridden and final variable cann’t be changed.
    • The finally keyword is used in association with a try / catch block and guarantees
      that a section of code will be executed, even if an exception is thrown
    • finalize() is a method of object class will be executed by the jvm just before collecting object to give a final chance for resource releasing activity.
  • when will you define a method as static?
    • when a method needs to be accessed even before the creation of the object of the class then we should declare the method as static.
  • what are the restriction imposed on a static method or a static block of code?
    • a static method should not refer to instance variables without creating an instance and cannot use “this” operator to refer the instance
  • what is the importance of static varibale?
    • static variables are class level variable where all objects of the class refer to the same variable. If one object chanegs the value then the change gets reflected in all the objects.
  • can we declare a static variable inside a method?

    • static variables are class level variables and they cann’t be declared inside a method. If declared, the class will not compile.
  • what is an abstract class and what is its purpose?
    a class which doesn’t provide complete implemenation is defined as an abstract class. abstract classes enforce abstraction.

  • what is use of an abstract variable?
    • variables cannot be declared as abstrct, only classes and methods can be declared as abstract.
  • can you create an object of an abstract class?

    • not possible, abstract classes cann’t be instantiated.
  • can an abstract class be defined without any abstract methods?

    • yes it is possible. this is basically to avoid instance creation of the class.
  • can an method inside an interface be declared as final?

    • not possible, doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.
  • can an interface extend another interface?

    • interfaces doesn’t provide implementation hence an interface cannot implement another interface.
  • why is an interface be able to extend more than one interface but a class cann’t be extend more one class

    • basically java doesn’t allow multiple inheritance, so a class is restriced to extend only one class. but an interface is a pure abstraction model and doesn’t have inheritance hierarchy like classes. so an interface is allowed to extend more than one interface.
  • can a class be defined inside an interface?

    • yes it’s possible
  • can an interface be defined inside a class?

    • yes it’s possible
  • what is a marker interface?

    • an interface which doesn’t have any declaration inside but still enforeces a mechanism
  • which object oriented concept is achieved by using overloading and overriding?
    -polymorphism
  • why does java not support operator overloading?
    -operator overloading make the code very difficult to read and maintain. To maintain code simplicity, java does’t support operator overloading
  • can we define private and proteced modifiers for variables in interfaces?

    • no, public abstract
  • what is externalizable?

    • externlizable is an interface that extends serializable interface, and sends data into streams is compressed format, it has two methods, writeExternal(objectoutput out) and readExternal(Object in)
  • what modifiers are allowed for methods in an interfaces?

    • only public and abstract modifiers are allowed for methods in interfaces.
  • what is an abstract method?

    • an abstract method is a method is a method whose implemenation is deferred to a subclass.
  • what value does read() read when it has reached the end of a file?

    • the read() method return -1 when it has reached the end of a file.
  • what is the difference between a static and a non-static inner class?

    • a non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.
  • what’s an object lock and which object’s have locks?

    • an object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. all object and classes have locks. A class’s lock is acquired on the class’s Class object.
  • When can an object reference be cast to an interface reference?
    • An object reference be cast to an interface reference when the object implements the referenced interface.
  • Which non-Unicode letter characters may be used as the first character of an identifier?
    • The non-Unicode letter characters $ and _ may appear as the first character of an identifier
  • what is casting?
    • There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
  • what is downcasting?
    • There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
  • what is a native method?

    • A native method is a method that is implemented in a language other than Java.
  • What does it mean that a method or field is “static”?

    • static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particluarl object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class. That’s how libray methods like system.out.println() work. out is a static field in the java.lang.sytem. class
  • is null| true| false| sizeof a keyword?

    • the null value is not a keyword
  • Does a class inherit the constructors of its superclass?
    • a class does not inherit constructors from any of its superclasses.
  • what is the difference between inner class and nested class?

    • when a class is defined within a scope od another class, then it becomes inner class. If the access modifier of the inner class is static, then it becomes nested class.
  • what is numeric promotion?

    • numberic promotion is the conversion of a smaller numeric type to a larger numberic type, so that integer and floating point operations may take place, in numerical promotion, byte, char, and short values are converted to int values.
  • what is the difference between the prefix and postfix forms of the ++ operator?

    • the prefix form performs the increment operation and returns the value of the increment opeation, the postfix form returns the current value of all of the expression and then performs the increment operation on that value.
  • what is the difference between the >> and >>> operators?

    • the >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
  • hash map
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class MyHashMap<K,V>{
class Entry<K,V>{
K key;
V value;
Entry(K key, V value){
this.key=key;
this.value=value;
}
}
private int capacity =16;
private List<LinkedList<Entry<K,V>>> buckets;
public MyHashMap(){
buckets = new ArrayList<>();
for(int i=0;i<capacity;++i){
buckets.add(i,null);
}
}
public void put(K key, V value){
if(key==null){
return new NullPonterException("Key cannot be null");
}
int index = key.hashCode()%capacity;
if(buckets.get(index)==null)
buckets.set(index,new LinkedList<Entry<K,V>>());
LinkedList<Entry<K,V>>bucket = buckets.get(index);
Iterator<Entry<K,V>>iteartor = bucket.iterator();
while(iterator.hasNext()){
Entry<K,V>entry = iterator.next();
if(entry.key.equals(key)){
entry.value=value;
return;
}
}
bucket.add(new Entry<>(key,value));
}
public V get(K key){
if(key == null){
throw new NullPonterException("key cannot be null!");
}
int index = key.hashCode()%capacity;
if(buckets.get(index)==null)
return null;
LinkedList<Entry<K,V>>bucket = buckets.get(index);
Iterator<Entry<K,V>>iterator = bucket.iterator;
while(iterator.hasNext()){
Entry<K,V>entry = iterator.next();
if(entry.key.equals(key)){
return entry.value;
}
}
return null;
}
}

other questions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
1. What’s difference between the stack and heap?
Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer’s RAM.
stack is faster and its allocation is dealt with when program is compiled
varibale allocated on the heap have their allocated at run time and accessing this memory is a bit slower, its size is only limited by the size of virtual memory
the stack is the memory set aside as scratch space for a thread of execution. When a function is called, a block is reserved on the top of the stack for local varibales and some bookkeeping data
when that function returns, the block becomes unused and can be used the next time a function is called. The stack is always reserved in a LIFO order
the most recently reserved block is always the next block to be freed, this makes it really simple to keep track of the stack.
the heap is memoyr set aside for dynamic allocation, unlike the stack, there is no enforced pattern to be allocation and deallocation of blocks from the heap
you can alloate a block at any time and free it at any time. this makes it much more complex to keep track of which parts of the heap are allocated or free at any given time
2. breaking out of nested loop in java
you can use break with a label for the outer loop
3. can a java file have more than one class
yes, it can.However, there can only be one public class per.java file, as public classes must have the same name as the source file.The purpose of including multiple classes in one source file is to
bundle related support functionality(internal data structures, support classes, etc) together with the main public class
4. switch statement
A switch works with the bytes, short, char and int primitive data types, it also works with enumerated types, the string class and “Character Byte short integer”
5. class and interface
//if class has fields and methods, what about interface:
fileds : must be public final
methods : must be public abstract
6. //four featurs of OOP
Encapsulation is one of the four fundamental OOP concepts.The other three are inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data(variables) and code acting on the data(methods) together as a single unit.
In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class.Therefore, it is also known as data hiding.
To achieve encapsulation in JAVA
Declare the variable of a class as private, provide public setter and getter methods to modify and view the variables value
7. polymorphism
The ability to identify a function to run is called Polymorphism.In java, c++ there are two types of polymorphism : compile time polymorphism(overloading) and runtime polymorphism(overriding)
Mehtod overriding : Overriding occurs when a class method has the same name and signature as a method in parent class.When you override methods,
JVM determines the proper methods to call at the program’s run time, not at the compile time.
Overloading : Overloading is determined at the compile time.It occurs when several methods have same names with :
Different method signature and different number or type of parameters.
Same method signature but different number of parameters.
Same method signature and same number of parameters but of different type
8. abstarction
Occurs during class level design, with the objective of hiding the implementation complexity of how the features offered by
an API / design / system were implemented, in a sense simplifying the interface to acces the underlying implementation
9. What is the difference between an Interface and Abstract class
All methods in an interface are implicitly abstract.On the other hand, an abstract class may contain both abstract and non - abstract methods.
A class may implement a number of Interfaces, but can extend only one abstract class.
In order for a class to implement an interface, it must implement all its declared methods.However, a class may not implement all declared methods of an abstract class.
Abstract classes can implement interfaces without even providing the implementation of interface methods.
Variables declared in a Java interface is by default final.An abstract class may contain non - final variables.
Members of a Java interface are public by default.A member of an abstract class can either be private, protected or public.
//An interface is absolutely abstract and cannot be instantiated.An abstract class also cannot be instantiated, but can be invoked if it contains a main method.
10 Main difference between a CLASS and INTERFACE is :
-Class has both definition and an implementation whereas Interface only has a definition.
-Interfaces are actually implemented via a Class.
11 final keyword
• Variable : The value cannot be changed once initialized.//the context can be changed, but the reference can’t chang.
• Method : The method cannot be overridden by asubclass.
• Class. - The class cannot be subclassed.
The finally keyword is used in association with a try / catch block and guarantees
that a section of code will be executed, even if an exception is thrown.The finally
block will be executed after the try and catch blocks, but before control transfers back
to its origin.
Throws clause in used to declare an exception and throw keyword is used to throw an exception explicitly
Throw new Exception(“You have some exception”)
Throws IOException, ArithmeticException, NullPointerException
Finalize method :
Is is an object method.It is called when an object is about to get garbage collected.That can be at any time after it has become eligible for garbage collection
12 What is the difference between == vs equals in java
The == operator tests whether two variable have the same references : memory address
The equals method tests whether two variables refer to objects that have the same state(values)
13 Difference between an instance and static variable ?
A static variable is shared by all instances of the class, while an instance variable is unique to each instance of the class
A static variable’s memory is allocated at compile time, they are loaded at load time and initialized at class initialization time.
In the case of an instance variable all of the above is done at run time
14. Calling non - static method in static method in java ?
The only way to call a non - static method from a static method is to have an instance of the class containing the non - static method,
by defination, a non - static method is one that is called on an instance of some class, whereas a static method belongs to the class itself.
15 Difference between int and integer
Int is a primitive type.Integer is a class with a single field of type int.
This class is used where you need an int to be treated like any other object, such as generic types of situations where you need nullability
16 Constructor can be override ?
No, cann’t be inherited, so can’t be override
17 Static methods can’t be abstract in java :
Because “abstract” means : ”implements no functionality”, and “static” means : there is functionality even if you don’t have an object instance.That is logical contradiction
18 nested class
Nested classes are divided into two categories : static and non - static.Nested class that are declared static are simply called static nested classes. Non - static nested classes are called inner classes
Static nested classes are accessed using the enclosing class name
//OuterClass.StaticNestedClass
//OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
An instance of InnerClass can exist only within an instance of outerclass and has direct access to the method and fields of its enclosing instance
To instantiate an inner class, you must first instantiate the outer class.The, create the inner object with the outer object with
// Outerclass.innerclass innerObject=outerObject.new Innerclass()
//static class: declared as a static member of another class
//inner class: declared as an instance member of another class
inner class instance has access to the instance members of the containing class instance.These enclosing instance members are
referred to inside the inner class via just their simple names, not via this (this in the inner class refers to the inner class instance, not the associated containing class instance) :
//local inner class : declared inside an instance method of another class
so it can only be instantiated and have its members accessed within its containing method.
public class Outerclass {
// instance method of the outer class
void my_Method() {
int num = 23;
// method-local inner class
class MethodInner_Demo {
public void print() {
System.out.println("This is method inner class " + num);
}
} // end of inner class
// Accessing the inner class
MethodInner_Demo inner = new MethodInner_Demo();
inner.print();
}
public static void main(String args[]) {
Outerclass outer = new Outerclass();
outer.my_Method();
}
}
//anonymous inner class : like a local inner class, but written as an expression which returns a one - off object
have no name
An anonymous inner class is a syntactically convenient way of writing a local inner class
If you want a local inner class which implements multiple interfaces or which implements interfaces
while extending some class other than Object or which specifies its own constructor, you're stuck creating a regular named local inner class//就是说要用anonymous inner class
abstract class Person {
public abstract void eat();
}
class Child extends Person {
public void eat() {
System.out.println("eat something");
}
}
public class Demo {
public static void main(String[] args) {
Person p = new Child();
p.eat();
}
}
actually you can write this way
abstract class Person {
public abstract void eat();
}
public class Demo {
public static void main(String[] args) {
Person p = new Person(){
public void eat() {
System.out.println("eat something");
}
};
p.eat();
}
}
19 does finally always exectutes in JAVA?
Finally will be called
The only times finally won’t be called are :
If you call System.exit()
If the jvm crashes first
If there is an infinite loop in the try block
If the power turns off
20 exception in java
Errors and RuntimeExceptions are unchecked
all other exceptions are checked
Difference between Error and Exception :
Error : indicates serious problems that a reasonable application should not try to catch
Exception : indicates conditions that a reasonable application might want to catch
21 List five runtime exception :
NullPointerException.ArrayIndexOutofBoundsException.ClassCastException
IllegalArgumnetException IllegalStateException
25 What is the difference between asynchronous and synchronous execution ?
27 Difference between arraylist and vector
They are almost same : implement List interface, get element according to its index
Diff :
Vectors are synchronized, arraylist are not :
Data growth methods
Synchronization :
If multiple thread access an Arraylist concurrently then we must externally sunchronize the block of code which modifies the list either structurally or simply modify an element.
structural modeifications means addition or deletions of elemetns from the list, Setting the value of an existing element is not structure modicfication
data growth
Internally, both the arraylist and vector hold onto their contents using an array, when an element is inserted into an arraylist or a vector,
the object will need to expand its internal array if run out of room.A vector defaults to doubling the size of its array, while the arraylist increases its array size by 50 percent
28 diff between hashtable and hashmap
Hashtable is synchronized, whereas hasmap is not.This makes HashMap better for non - treaded applications, as unsynchroinzed objects typically pefrom better than synchronized ones
Hashtable does not allow null keys or values, hasmap allows one null key and any number of null values
29 Difference Between Array And ArrayList In Java
resizeable: array is static in size that is fixed length data struture. one can not change the length after creating the array object
primitives : arralist cannot contains primitive data types(), it can only contains object while aray can contain both primitive data types as well as objects
iterating the values: we can use iterator to iterate through arraylist
multi-dimensional: array can be multi dimensonal, while arraylist is always single dimesional
29 diff between hashset and treeset
ordering: haset stores the object in random order, elements are sorted according to the natrual ordering of its elements in Treeset
NULL value: hashset can store null object while treeset does not allow null object. If one try to store null object in Tree object, it will throw null pointer
performance : hashset take constant time performace for basic operations like add, remove contains and size. while treeset guarantees log(N) time cost for the basic opertions
speed: hasset is much faster than tree set
internal implementation: hashset are interally backed by hashmap, while treeset is RB TREE
hashset uses equals method for comparsion in java while treeset uses compareTo method for maintaing ordering
30 java stream
Character stream implements inputstreamReader and OutputStreamWriter
Byte stream : implements inputStream outputstream
A byte stream access the file byte by byte.A byte stream is a suitable for any kind of file.However not quite appropriate for text files.
if the file is using a unicode encoding and a character is represented with two bytes,
the byte stream will treat these separately and you will need to do the conversion yourself.
A character stream will read a file character by character.A character stream needs to be given the file encoding in order to work properly
Character Stream is a higher level concept than Byte Stream
31 Serializable is a special interface that specifies that class is serializable, it’s special in that unlike a normal interface it does not define any methods that must be implemented,
it is simply marking the class as serializabl
As to what “Serializable” means, it simply means converting an instance of an object into a format where it can be written to disk,
or possibly transmitted over a network, you could for example save your object to disk and reload it later, with all the field values and internal state saved.
32 garbage collector
garbage collector is a program which runs on the java virtual machine which gets rid of objects which are not being used by a java application anymore, it is a form of automatic memory management
Automatic memory management schemes like garbage collection makes it so the programmer does not have
to worry about memory management issues, so he or she can focus more on developing the applications they need to develop
33 what is the most important feature of Java ?
Java is a platform independent language.
34 What do you mean by platform independence ?
Platform independence means that we can write and compile the java code in one platform(eg Windows) and can execute the class in any other supported platform eg(Linux, Solaris, etc).
35 What is a JVM ?
JVM is Java Virtual Machine which is a run time environment for the compiled java class files.
36 Are JVM's platform independent?
JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor.
37What is the difference between a JDK and a JVM ?
JDK is Java Development Kit which is for development purpose and it includes execution environment also.But JVM is purely a
run time environment and hence you will not be able to compile your source files using a JVM.
Java Developer Kit contains tools needed to develop the Java programs, and JRE to run the programs.The tools include compiler(javac.exe), Java application launcher(java.exe), Appletviewer, etc…
Compiler converts java code into byte code.Java application launcher opens a JRE, loads the class, and invokes its main method.
You need JDK, if at all you want to write your own programs, and to compile them.For running java programs, JRE is sufficient.
//JRE is targeted for execution of Java files
i.e.JRE = JVM + Java Packages Classes(like util, math, lang, awt, swing etc) + runtime libraries.
JDK is mainly targeted for java development.I.e.You can create a Java file(with the help of Java packages), compile a Java file and run a java file.
JRE(Java Runtime Environment)
Java Runtime Environment contains JVM, class libraries, and other supporting files.It does not contain any development tools such as compiler, debugger, etc.
Actually JVM runs the program, and it uses the class libraries, and other supporting files provided in JRE.If you want to run any java program, you need to have JRE installed in the system
The Java Virtual Machine provides a platform - independent way of executing code; That mean compile once in any machine and run it any where(any machine).
JVM(Java Virtual Machine)
As we all aware when we compile a Java file, output is not an ‘exe’ but it’s a ‘.class’ file.‘.class’ file consists of Java byte codes
which are understandable by JVM.Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating
system and hardware combination.It is responsible for all the things like garbage collection, array bounds checking, etc… JVM is platform dependent.
The JVM is called “virtual” because it provides a machine interface that does not depend on the underlying operating system and
machine hardware architecture.This independence from hardware and operating system is a cornerstone of the write - once run - anywhere value of Java programs.
There are different JVM implementations are there.These may differ in things like performance, reliability, speed, etc.These
implementations will differ in those areas where Java specification doesn’t mention how to implement the features,
like how the garbage collection process works is JVM dependent, Java spec doesn’t define any specific way to do this.
38//What is a pointer and does Java support pointers ?
Pointer is a varible to store the address.Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers.
39//What is the base class of all classes ?
java.lang.Object
40//Does Java support multiple inheritance ?
Java doesn't support multiple inheritance.
41 //Is Java a pure object oriented language ?
Java uses primitive data types and hence is not a pure object oriented language.
42 //Are arrays primitive data types ?
In Java, Arrays are objects.
42 //What is difference between Path and Classpath ?
Path and Classpath are operating system level environment variales.Path is used define where the system can find the executables(.exe)
files and classpath is used to specify the location .class files.
43 //What are local variables ?
Local varaiables are those which are declared within a block of code like methods.Local variables should be initialised before accessing them.
44 //What are instance variables ?
Instance variables are those which are defined at the class level.Instance variables need not be initialized before using them as they are automatically initialized to their default values.
45 //How to define a constant variable in Java ?
The variable should be declared as static and final.So only one copy of the variable exists for all instances of the class and the value can't be changed also.
static final int MAX_LENGTH = 50; is an example for constant.
46 //Should a main() method be compulsorily declared in all java classes ?
No not required.main() method should be defined only if the source class is a java application.
47 //What is the return type of the main() method ?
Main() method doesn't return anything hence declared void.
48 //Why is the main() method declared static ?
main() method is called by the JVM even before the instantiation of the class hence it is declared as static.
49 //What is the arguement of main() method ?
main() method accepts an array of String object as arguement.
50 //Can a main() method be overloaded ?
Yes.You can have any number of main() methods with different method signature and implementation in the class.
51 //Can a main() method be declared final ?
Yes.Any inheriting class will not be able to have it's own default main() method.
52 //Does the order of public and static declaration matter in main() method ?
No.It doesn't matter but void should always come before main().
53 //Can a source file contain more than one class declaration ?
Yes a single source file can contain any number of Class declarations but only one of the class can be declared as public.
54 //What is a package ?
Package is a collection of related classes and interfaces.package declaration should be first statement in a java class.
55 //Which package is imported by default ?
java.lang package is imported by default even without a package declaration.
56 //Can a class declared as private be accessed outside it's package?
Not possible.
57 //Can a class be declared as protected ?
The protected access modifier cannot be applied to class and interfaces.Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.
58 //What is the access scope of a protected method ?
A protected method can be accessed by the classes within the same package or by the subclasses of the class in any package.
59 //What is the purpose of declaring a variable as final ?
A final variable's value can't be changed.final variables should be initialized before using them.
60 //What is the impact of declaring a method as final ?
A method declared as final can't be overridden. A sub-class can't have the same method signature with a different implementation.
61 //I don't want my class to be inherited by any other class. What should i do?
You should declared your class as final.But you can't define your class as final, if it is an abstract class. A class declared as final can't be extended by any other class.
62 //Can you give few examples of final classes defined in Java API ?
java.lang.String, java.lang.Math are final classes.
63 //How is final different from finally and finalize() ?
final is a modifier which can be applied to a class or a method or a variable.final class can't be inherited, final method can't be overridden and final variable can't be changed.
finally is an exception handling code section which gets executed whether an exception is raised or not by the try block code segment.
finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.
64 //Can a class be declared as static ?
We can not declare top level class as static, but only inner class can be declared static.
public class Test
{
static class InnerClass
{
public static void InnerMethod()
{
System.out.println("Static Inner Class!");
}
}
public static void main(String args[])
{
Test.InnerClass.InnerMethod();
}
}
//output: Static Inner Class!
64 //When will you define a method as static ?
When a method needs to be accessed even before the creation of the object of the class then we should declare the method as static.
65 //What are the restriction imposed on a static method or a static block of code ?
A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance.
66 //I want to print "Hello" even before main() is executed.How will you acheive that ?
Print the statement inside a static block of code.Static blocks get executed when the class gets loaded into
the memory and even before the creation of an object.Hence it will be executed before the main() method.And it will be executed only once.
67 //What is the importance of static variable ?
static variables are class level variables where all objects of the class refer to the same variable.If one object changes the value then the change gets reflected in all the objects.
68 //Can we declare a static variable inside a method ?
Static varaibles are class level variables and they can't be declared inside a method. If declared, the class will not compile.
69 //What is an Abstract Class and what is it's purpose?
A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.
70 //Can a abstract class be declared final ?
Not possible.An abstract class without being inherited is of no use and hence will result in compile time error.
71 //What is use of a abstract variable ?
Variables can't be declared as abstract. only classes and methods can be declared as abstract.
72 //Can you create an object of an abstract class ?
Not possible.Abstract classes can't be instantiated.
73 //Can a abstract class be defined without any abstract methods ?
Yes it's possible. This is basically to avoid instance creation of the class.
74 //Class C implements Interface I containing method m1 and m2 declarations.Class C has provided implementation for method m2.Can i create an object of Class C ?
No not possible.Class C should provide implementation for all the methods in the Interface I.Since
Class C didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be instantiated.
75 //Can a method inside a Interface be declared as final ?
No not possible.Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.
76 //Can an Interface implement another Interface ?
Intefaces doesn't provide implementation hence a interface cannot implement another interface.
77// Can an Interface extend another Interface ?
Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.
78//Can a Class extend more than one Class ?
Not possible.A Class can extend only one class but can implement any number of Interfaces.
79 //Why is an Interface be able to extend more than one Interface but a Class can't extend more than one Class?
Basically Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class.
But an Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes(
do remember that the base class of all classes is Object).So an Interface is allowed to extend more than one Interface.
80 //Can an Interface be final ?
Not possible.Doing so so will result in compilation error.
81 //Can a class be defined inside an Interface ?
Yes it's possible.
82 //Can an Interface be defined inside a class ?
Yes it's possible.
83 //What is a Marker Interface ?
An Interface which doesn't have any declaration inside but still enforces a mechanism.
84 //Which object oriented Concept is achieved by using overloading and overriding ?
Polymorphism.
85 //Why does Java not support operator overloading ?
Operator overloading makes the code very difficult to read and maintain.To maintain code simplicity, Java doesn't support operator overloading.
86 //Can we define private and protected modifiers for variables in interfaces ?
No.
87 //What is Externalizable ?
Externalizable is an Interface that extends Serializable Interface.And sends data into Streams in Compressed Format.It has two methods,
writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
88 //What modifiers are allowed for methods in an Interface ?
Only public and abstract modifiers are allowed for methods in interfaces.
89 //What is a local, member and a class variable ?
Variables declared within a method are "local" variables.
Variables declared within the class i.e not within any methods are "member" variables(global variables).
Variables declared within the class i.e not within any methods and are defined as "static" are class variables.
90 //What is an abstract method ?
An abstract method is a method whose implementation is deferred to a subclass.
91 //What value does read() return when it has reached the end of a file ?
The read() method returns - 1 when it has reached the end of a file.
92 //Can a Byte object be cast to a double value ?
No, an object cannot be cast to a primitive value.
93 //What is the difference between a static and a non - static inner class ?
A non - static nested class has full access to the members of the class within which it is nested.
A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non - static methods or access
non - static fields of an instance of the class within which it is nested.
94 //What is an object's lock and which object's have locks ?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object.
A thread may execute a synchronized method of an object only after it has acquired the object's lock.All objects and classes have locks.A class's lock is acquired on the class's Class object.
95 //What is the % operator ?
It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.
96 //When can an object reference be cast to an interface reference ?
An object reference be cast to an interface reference when the object implements the referenced interface.
97 //Which class is extended by all other classes ?
The Object class is extended by all other classes.
98//Which non - Unicode letter characters may be used as the first character of an identifier ?
The non - Unicode letter characters $ and _ may appear as the first character of an identifier
99//What restrictions are placed on method overloading ?
Two methods may not have the same name and argument list but different return types.
100 //What is casting ?
There are two types of casting, casting between primitive numeric types and casting between object references.Casting
between numeric types is used to convert larger values, such as double values, to smaller values,
such as byte values.Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
101// What is the return type of a program's main() method?
void.
102 //If a variable is declared as private, where may the variable be accessed ?
A private variable may only be accessed within the class in which it is declared.
103 //What do you understand by private, protected and public ?
These are accessibility modifiers.Private is the most restrictive, while public is the least restrictive.There
is no real difference between protected and the default type(also known as package protected) within the context of the same package,
however the protected keyword allows visibility to a derived class in a different package.
104 //What is Downcasting ?
Downcasting is the casting from a general to a more specific type, i.e.casting down the hierarchy
Animal animal = new Dog();
Dog castedDog = (Dog)animal;
105 //What modifiers may be used with an inner class that is a member of an outer class ?
A(non - local) inner class may be declared as public, protected, private, static, final, or abstract.
106 //How many bits are used to represent Unicode, ASCII, UTF - 16, and UTF - 8 characters ?
Unicode requires 16 bits and ASCII require 7 bits Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits.
UTF - 8 represents characters using 8, 16, and 18 bit patterns.
UTF - 16 uses 16 - bit and larger bit patterns.
107 //What restrictions are placed on the location of a package statement within a source code file ?
A package statement must appear as the first line in a source code file(excluding blank lines and comments).
108 //What is a native method ?
A native method is a method that is implemented in a language other than Java.
109 //What are order of precedence and associativity, and how are they used ?
Order of precedence determines the order in which operators are evaluated in expressions.Associatity determines whether an expression is evaluated left - to - right or right - to - left.
110 //Can an anonymous class be declared as implementing an interface and extending a class ?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
111//What is the range of the char type ?
The range of the char type is 0 to 216 - 1 (i.e. 0 to 65535.)
112 //What is the range of the short type ?
The range of the short type is - (215) to 215 - 1. (i.e. - 32, 768 to 32, 767)
113 //Why isn't there operator overloading?
Because C++ has proven by example that operator overloading makes code almost impossible to maintain.
114 //What does it mean that a method or field is "static" ?
Static variables and methods are instantiated only once per class.In other words they are class variables,
not instance variables.If you change the value of a static variable in a particular object, the value of that variable changes for
all instances of that class.Static methods can be referenced with the name of the class rather than the name of a particular object of the
class (though that works too).That's how library methods like System.out.println() work. out is a static field in the java.lang.System class.
115 //Is null a keyword ?
The null value is not a keyword.
116 //Which characters may be used as the second character of an identifier, but not as the first character of an identifier ?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
117 //Is the ternary operator written x : y ? z or x ? y : z ?
It is written x ? y : z.
118 //How is rounding performed under integer division ?
The fractional part of the result is truncated.This is known as rounding toward zero.
119 //If a class is declared without any access modifiers, where may the class be accessed ?
A class that is declared without any access modifiers is said to have package access.This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
120 //Does a class inherit the constructors of its superclass ?
A class does not inherit constructors from any of its superclasses.
121 //Name the eight primitive Java types.
The eight primitive types are byte, char, short, int, long, float, double, and boolean.
122 //What restrictions are placed on the values of each case of a switch statement ?
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
123 //What is the difference between a while statement and a do while statement ?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur.
A do while statement checks at the end of a loop to see whether the next iteration of a loop should occur.The do whilestatement will always execute the body of a loop at least once.
124 //What modifiers can be used with a local inner class ?
A local inner class may be final or abstract.
125 //When does the compiler supply a default constructor for a class ?
The compiler supplies a default constructor for a class if no other constructors are provided.
126 //If a method is declared as protected, where may the method be accessed ?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
127 //What are the legal operands of the instanceof operator ?
The left operand is an object reference or null value and the right operand is a class, interface, or array type.
128 //Are true and false keywords ?
The values true and false are not keywords.
129 //What happens when you add a double value to a String ?
The result is a String object.
130 //What is the diffrence between inner class and nested class ?
When a class is defined within a scope od another class, then it becomes inner class.If the access modifier of the inner class is static, then it becomes nested class.
131 //Can an abstract class be final ?
An abstract class may not be declared as final.
132 //What is numeric promotion ?
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type,
so that integer and floating - point operations may take place.In numerical promotion, byte, char, and short values are converted to int values.
The int values are also converted to long values, if necessary.The long and float values are converted to double values, as required.
133 //What is the difference between a public and a non - public class ?
A public class may be accessed outside of its package.A non - public class may not be accessed outside of its package.
134 //To what value is a variable of the boolean type automatically initialized ?
The default value of the boolean type is false.
135 //What is the difference between the prefix and postfix forms of the++ operator ?
The prefix form performs the increment operation and returns the value of the increment operation.
The postfix form returns the current value all of the expression and then performs the increment operation on that value.
136 //What restrictions are placed on method overriding ?
Overridden methods must have the same name, argument list, and return type.The overriding method may not limit the
access of the method it overrides.The overriding method may not throw any exceptions that may not be thrown by the overridden method.
137 //What is a Java package and how is it used ?
A Java package is a naming context for classes and interfaces.A package is used to create a separate name space
for groups of classes and interfaces.Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.
138 //What modifiers may be used with a top - level class ?
A top - level class may be public, abstract, or final.
139 What is the difference between an if statement and a switch statement ?
The if statement is used to select among two alternatives.It uses a boolean expression to decide which alternative should be executed.
The switch statement is used to select among multiple alternatives.It uses an int expression to determine which alternative should be executed.
140 //What are the practical benefits, if any, of importing a specific class rather than an entire package(e.g.import java.net.*versus import java.net.Socket) ?
It makes no difference in the generated class files since only the classes that are actually used are referenced by the generated class file.
There is another practical benefit to importing single classes, and this arises when two(or more) packages have classes with the same name.Take java.util.Timer and javax.swing.Timer,
for example.If I import java.util.*and javax.swing.*and then try to use "Timer", I get an error while compiling(the class name is ambiguous between both packages).
Let's say what you really wanted was the javax.swing.Timer class, and the only classes you plan on using in java.util are Collection and HashMap.
In this case, some people will prefer to import java.util.Collection and import java.util.HashMap instead of importing java.util.*.
This will now allow them to use Timer, Collection, HashMap, and other javax.swing classes without using fully qualified class names in.
141 //Can a method be overloaded based on different return type but same argument type ?
No, because the methods can be called without using their return type in which case there is ambiquity for the compiler.
142 //What happens to a static variable that is defined within a method of a class ?
Can't do it. You'll get a compilation error.
143 //How many static initializers can you have ?
As many as you want, but the static initializers and class variable initializers are executed in textual order and may not refer to class variables declared in the class
whose declarations appear textually after the use, even though these class variables are in scope.
144 //What is the difference between method overriding and overloading ?
Overriding is a method with the same name and arguments as in a parent, whereas overloading is the same method name but different arguments
145 //What is constructor chaining and how is it achieved in Java ?
A child object constructor always first needs to construct its parent(which in turn calls its parent constructor.).In Java it is done via an implicit call
to the no - args constructor as the first statement.
146 //What is the difference between the Boolean & operator and the && operator ?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated.Then the & operator
is applied to the operand.When an expression involving the && operator is evaluated, the first operand is evaluated.
If the first operand returns a value of true then the second operand is evaluated.The && operator is then applied to the first and
second operands.If the first operand evaluates to false, the evaluation of the second operand is skipped.
147 //Which Java operator is right associative ?
The = operator is right associative.
148 //Can a double value be cast to a byte ?
Yes, a double value can be cast to a byte.
149 //What is the difference between a break statement and a continue statement ?
A break statement results in the termination of the statement to which it applies(switch, for, do, or while).
A continue statement is used to end the current loop iteration and return control to the loop statement.
150 //Can a for statement loop indefinitely ?
Yes, a for statement can loop indefinitely.For example, consider the following : for (;;);
151 //To what value is a variable of the String type automatically initialized ?
The default value of an String type is null.
152 //What is the difference between a field variable and a local variable ?
A field variable is a variable that is declared as a member of a class.A local variable is a variable that is declared local to a method.
153//How are this() and super() used with constructors ?
this() is used to invoke a constructor of the same class.super() is used to invoke a superclass constructor.
154 //What does it mean that a class or member is final ?
A final class cannot be inherited.A final method cannot be overridden in a subclass.A final field cannot be changed after it's initialized, and it must include an initializer statement where it's declared.
155 //What does it mean that a method or class is abstract ?
An abstract class cannot be instantiated.Abstract methods may only be included in abstract classes.However, an abstract class is not required to have any abstract methods, though most of them do.
Each subclass of an abstract class must override the abstract methods of its superclasses or it also should be declared abstract.
156 //What is a transient variable ?
Transient variable is a variable that may not be serialized.
157 //How does Java handle integer overflows and underflows ?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
158 //What is the difference between the >> and >> > operators ?
The >> operator carries the sign bit when shifting right.The >> > zero - fills bits that have been shifted out.
159 //Is sizeof a keyword ?
The sizeof operator is not a keyword.
160 hashmap implementation
A hashmap works like this (this is a little bit simplified, but it illustrates the basic mechanism) :
It has a number of "buckets" which it uses to store key - value pairs in. Each bucket has a unique number -
that is what identifies the bucket. When you put a key-value pair into the map, the hashmap will look at the hash code of the key,
and store the pair in the bucket of which the identifier is the hash code of the key. For example: The hash code of the key is 235 ->
the pair is stored in bucket number 235. (Note that one bucket can store more then one key-value pair).
When you lookup a value in the hashmap, by giving it a key, it will first look at the hash code of the key that you gave.The hashmap will
then look into the corresponding bucket, and then it will compare the key that you gave with the keys of all pairs in the bucket, by comparing them with equals().
Now you can see how this is very efficient for looking up key - value pairs in a map : by the hash code of the key the hashmap
immediately knows in which bucket to look, so that it only has to test against what's in that bucket.
Looking at the above mechanism, you can also see what requirements are necessary on the hashCode() and equals() methods of keys :
If two keys are the same(equals() returns true when you compare them), their hashCode() method must return the same number.If keys violate this,
then keys that are equal might be stored in different buckets, and the hashmap would not be able to find key - value pairs(because it's going to look in the same bucket).
If two keys are different, then it doesn't matter if their hash codes are the same or not. They will be stored in the same bucket
if their hash codes are the same, and in this case, the hashmap will use equals() to tell them apart.
161 //synchronzed
synchronized means that in a multi threaded environment, an object having synchronized method(s) / block(s) does
not let two threads to access the synchronized method(s) / block(s) of code at the same time.This means that one thread can't read while another thread updates it.
The second thread will instead wait until the first thread completes its execution.The overhead is speed, but the advantage is guaranteed consistency of data.
If your application is single threaded though, synchronized blocks does not provide benefits.
161.1 //thread lock;
Java ThreadLocal is used to create thread - local variables.We know that all threads of an Object share it’s variables,
so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables.
162 //multithread
By definition, multitasking is when multiple processes share common processing resources such as a CPU.
Multi - threading extends the idea of multitasking into applications where you can subdivide specific operations within a single
application into individual threads.Each of the threads can run in parallel.The OS divides processing time not only among different applications, but also among each thread within an application.
Multi - threading enables you to write in a way where multiple activities can proceed concurrently in the same program.
Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY(a constant of 1) and MAX_PRIORITY(a constant of 10).By default, every thread is given priority NORM_PRIORITY(a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower -
priority threads.However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.
162.2 //advatages of java multithreading
1) It doesn't block the user because threads are independent and you can perform multiple operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.
163 //diff between thread and process
What is the difference between Process and Thread ?
A process is a self contained execution environment and it can be seen as a program or application whereas Thread is a single task of execution within the process.
Java runtime environment runs as a single process which contains different classes and programs as processes.
Thread can be called lightweight process.Thread requires less resources to create and exists in the process, thread shares the process resources.
22 thread
Thread :
A thread is a series of executed statements
Referred as lightweight process
Each thread has its own program counter, stack and local variable
life cycle
New :
The thread is in new state if you create an instance of Thread class but before the invocation of start() method
Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread
Running
The thread is in running state if the thread scheduler has selected
Blocked
This is the state when the thread is still alive, but is currently not eligible to run
Terminated
A thread is in terminated or dead when its run() method exit
23 two ways to start a thread
Implement runnable or extends Thread
Implement of run()
(new Thread(new HelloRunnable())).start();//implements the runnable
(new HelloThread()).start();//extends thread
24 thread method
String getName() retrieves the same of running thread in the current context in string format
Void start() this method will start a new thread of execution by calling run() method of Thread / runnable object
Void run() this method is the entry point of the thread, execution of thread starts from this method
Void sleep() this method suspend the thread for mentioned time duration in argument
Void yield() by invoking this method the current thread pause its execution temporarily and allow other threads to exectute
Void join() this method is used to queue up a thread in execution, once called on thread, current thread will wait till calling thread completes its exectution
Boolean isAlive() this method will check if thread is alive or dead
164//thread communicate with each other
When threads share resources, communication between Threads is important to coordinate their efforts.Object
class wait(), notify() and notifyAll() methods allows threads to communicate about the lock status of a resource.Check this post to learn more about thread wait, notify and notifyAll.
165 //volatile keyword
When we use volatile keyword with a variable,
all the threads read it’s value directly from the memory and don’t cache it.This makes sure that the value read is the same as in the memory.
166 //thread deadlock
Deadlock is a programming situation where two threads wait for each other to take action which allows them to move further.
To analyze a deadlock, we need to look at the java thread dump of the application, we need to look out for the threads with state as BLOCKED and then the resources
it’s waiting to lock, every resource has a unique ID using which we can find which thread is already holding the lock on the object.
Avoid Nested Locks, Lock Only What is Required and Avoid waiting indefinitely are common ways to avoid deadlock situation, read this post to learn how to analyze deadlock in java with sample program
//167 thread pool
A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed.
A thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue.
java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java.
Thread Pool Example program shows how to create and use Thread Pool in java.Or read ScheduledThreadPoolExecutor Example to know how to schedule tasks after certain delay.