-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCore Java Notes.txt
More file actions
917 lines (712 loc) · 46.3 KB
/
Core Java Notes.txt
File metadata and controls
917 lines (712 loc) · 46.3 KB
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
Complete Java Notes
------------------------------
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is known as the father of Java
---------------------------------------------------------------------------------------------------------------------------------------------
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
No explicit pointer
Java Programs run inside a virtual machine sandbox
Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file system from those that are imported from network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.
Security Manager: It determines what resources a class can access such as reading and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
---------------------------------------------------------
Q. difference between compiler and interpreter and assembler
A compiler is a software that converts programs written in a high level language into machine language. An interpreter is a software that translates a high level language program into machine language while an assembler is a software that converts programs written in assembly language into machine language
What is meant by assembly language?
An assembly language is a type of low-level programming language that is intended to communicate directly with a computer's hardware. Unlike machine language, which consists of binary and hexadecimal characters, assembly languages are designed to be readable by humans.
eg ADd ... MATLAB , c
---------------------------------------------------------
Q.. why JVM is an abstract machine ?
VM = JAVA VIRTUAL MACHINE:- The word virtual itself indicates that it doesn't exists PHYSICALLY.
Elaborated here:
Abstract means HIDDEN.
When assembly programs runs on a computer, it is executed in the system runtime environment:
Properties
Platform dependent (if compiled for windows, a program will run only in windows not in Linux/UNIX etc.)
Not portable (same as above)
Systems runtime (in user's PC mainly under OS's control)
When Java Program runs into a computer, it is executed in another virtual machine (JVM) for which, the runtime environment is provided by JRE (JAVA Runtime Environment), it is installed automatically when you install JDK (Java Development Kit).
Without JRE, it is impossible to run Java Programs (Update: You can bundle your custom JRE with your code, in that case no need to install JDK or JRE separately but only in JDK9 & above)
This JVM itself runs in the system runtime (in user's PC/OS) but when Java program runs it is loaded into this running JVM.
For more practical AND visual experience:(for Windows only)
Open Task Manager
Go to Processes Tab
Find Java(TM) Platform SE Binary (This is JVM) - Java Instance
And now run a java program and write some code to delay the execution, like multi-threading with wait and notify (you can find such programs on google), due to this running program your Java Instance will show a little high memory and disk usage (not much high but slightly higher than that when no program was running in JRE/JVM). These processes you see in Task Manager, are running in System Runtime, and your Java program will not be listed there.
Instead it will be running inside this already running JRE.
This is the reason why JVM is ABSTRACT.
Now, do a little cross check and prove it..
Run 2-3 java programs, either keep them in longer waiting or just write Input Scanner and don't provide input, program will continue to run in blocking state so that we can see them later.
Once gain, confirm that only one instance of JVM/Java is running in task manager (Depends on how many JREs you have installed, sometimes IDEs can also create one instance, so better close it first for clear observation)
Now, where are those 2-3 Java Programs running?? Open VisualVM (it's under the same package/folder where your java executable resides)..
In this VisualVM, you can clearly see that, all your RUNNING Java Programs are listed.
Now, open side by side windows... Task Manager, VisualVM and one of your Running Code's Console.
Verify,
in Task manager - 1 instance of Java Binary.
in VisualVM - 3 different instances of your programs (if you run 3 java porgram)
Now, provide input in one of your code so that blocking state goes away and program terminates successfully.
Now verify,
in Task Manager - still 1 instance of Java Binary.
in VisualVM - 2 instances, because 1 code terminated/finished.
So, all your Java programs run under a Virtual Machine, a machine that is hidden, physically not available, abstract.
-----------------------------------------------------------------------------------------------------------------------------------------
Imp - ven tho OP is only talking about the String[] args, i want to give a complete example of the public static void main(String[] args).
Public : is an Access Modifier, which defines who can access this Method. Public means that this Method will be accessible by any Class(If other Classes are able to access this Class.).
Static : is a keyword which identifies the class related thing. This means the given Method or variable is not instance related but Class related. It can be accessed without creating the instance of a Class.
Void : is used to define the Return Type of the Method. It defines what the method can return. Void means the Method will not return any value.
main: is the name of the Method. This Method name is searched by JVM as a starting point for an application with a particular signature only.
String[] args : is the parameter to the main Method.
can be written as
public static void main(String...arg)
or
public static void main(String...strings)
When you finish your code, you will turn it into a file with the extension .java, which can be run by double clicking it, but also throughout a console (terminal on a mac, cmd.exe on windows) which lets the user do many things. One thing is they can see console messages (System.out.print or System.out.println) which they can't see if they double click. Another thing they can do is specify parameters, so normally you would use the line
java -jar MyCode.jar
after navigating to the folder of the program with
cd C:My/Code/Location
on windows or
cd My/Code/Location
on Mac (notice that mac is less clunky) to run code, but to specify parameters you would use
java -jar MyCode.jar parameter1 parameter2
These parameters stored in the args array, which you can use in your program is you want to allow the user to control special parameters such as what file to use or how much memory the program can have. If you want to know how to use an array, you could probably find a topic on this site or just google it. Note that any number of parameters can be used.
------------------------------------------------------------------------------------------------------------------------------
1 . What are the different ways to create an object in Java?
There are many ways to create an object in java. They are:
By new keyword
By newInstance() method
By clone() method
By deserialization
By factory method etc.
----------------------------------------
2 . Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling a method, etc. You can perform any operation in the constructor as you perform in the method.
---------------------------------------
3 . What is the purpose of Constructor class?
Java provides a Constructor class which can be used to get the internal information of a constructor in the class. It is found in the java.lang.reflect package.
------------------------------------------
4 . Rules for creating Java constructor
There are two rules defined for the constructor.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
------------------------------------------------------
5 . why constructor is used in oop ?
the role of the constructor is to initialize the variables/values.it is the "initialization function".The only reason i find on why we use a constructor instead of a normal function to initialize the variables is to stop different people from using different function names and avoid ambiguity and it is much more easier to use a constructor which is instantiated automatically as soon as the class is run,instead of having to write a separate code for instantiation.this may seem small and like something that doesn't require much work,but only for a very small program,for larger ones the struggle is real.
The constructor IS the "Initialize function"
Rather than calling two functions
object = new Class;
object.initialize();
You just call
object = new Class();
------------------------------------------------------------
6 . Static Keyword
1) Java static variable
If you declare any variable as static, it is known as a static variable.
The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc.
The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
2) Java static method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
---->Restrictions for the static method
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
3) Java static block
Is used to initialize the static data member.
It is executed before the main method at the time of classloading.
----------------------------------------------------------------
7.
Usage of Java this keyword
Here is given the 6 usage of java this keyword.
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this can be used to return the current class instance from the method.
https://www.javatpoint.com/this-keyword -- Imp
----------------------------------------------------------------
8. One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept by the figure given below:
Java Method Overloading with Type Promotion
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int, long, float or double. The char datatype can be promoted to int,long,float or double and so on.
Example of Method Overloading with TypePromotion
class OverloadingCalculation1{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
------------------------------
9 . Inheritance - IS-a and Aggregation - HAS-A
-------------------------------
Imp link related to method overriding - https://www.geeksforgeeks.org/overriding-in-java/
----------------------------
10 . Important Topic related to Method overriding for interview purpose
------
--class Shape{
int x =10 ;
public void Area() {
System.out.println("Shape area _ "+x);
}
}
class Circle extends Shape{
int x = 20;
@Override
public void Area() {
System.out.println("Circle area " + x); }
}
public class OverloadingAndRiding {
public static void main(String[] args) {
// TODO Auto-generated method stub
Shape p = new Circle(); // upcasting
int t = p.x;
System.out.println(t);
p.Area();
}
}
In above PRogram output - 10
Circle area 20
AS in java method only overrided not variable -- > Reference obj = new Instantiation to print x = 20 we have to make reference also circle ...
-----------------------------------------------------
check this - https://www.javatpoint.com/covariant-return-type
------------------------------------------------
11 . Usage of Java super Keyword
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
------------------------------------------------------------------------
12 . Rules for instance initializer block :
There are mainly three rules for the instance initializer block. They are as follows:
The instance initializer block is created when instance of the class is created.
The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
The instance initializer block comes in the order in which they appear.
Program of instance initializer block that is invoked after super()
class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B2 extends A{
B2(){
super();
System.out.println("child class constructor invoked");
}
{System.out.println("instance initializer block is invoked");}
public static void main(String args[]){
B2 b=new B2();
}
}
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
--------------------------------
13. Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it.
------------------------------
14 . Can we initialize blank final variable?
Yes, but only in constructor. For example:
class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike10();
}
}
-- Example of static blank final variable
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
---------------------------------------
15 . Why a constructor cannot be final in Java?
Ans - No, because constructor is never inherited.Whenever you make a method final, you cannot override it. i.e. you cannot provide implementation to the superclass's final method from the subclass.
i.e. The purpose of making a method final is to prevent modification of a method from outside (child class).
In inheritance whenever you extend a class. The child class inherits all the members of the superclass except the constructors.
In other words, constructors cannot be inherited in Java therefore you cannot override constructors.
So, writing final before constructors makes no sense. Therefore, java does not allow final keyword before a constructor.
If you try, make a constructor final a compile time error will be generated saying “modifier final not allowed here”.
Example
In the following Java program, the Student class has a constructor which is final.
public class Student {
public final String name;
public final int age;
public final Student() {
this.name = "Raju";
this.age = 20;
}
public void display() {
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
new Student().display();
}
}
Compile time error
On compiling, the above program generates the following error.
Student.java:6: error: modifier final not allowed here
public final Student(){
^
-----------------------------------------------------
16 . static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
Example of static binding
class Dog{
private void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Dog d1=new Dog();
d1.eat();
}
}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Animal a=new Dog();
a.eat();
}
}
Output:dog is eating...
In the above example object type cannot be determined by the compiler, because the instance of Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.
--------------------------------------------------------------------
Important for interview - Downcasting using instance of
- https://www.javatpoint.com/downcasting-with-instanceof-operator
-------------------------------------------------------------
17 . Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of the method.
-----------------------------------------------------------------
https://www.javatpoint.com/abstract-class-in-java -- More on abstraction
-------------------------------------------------------------------
Interface ----
18 . Multiple inheritance is not supported through class in java, but it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class. For example:
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestInterface3 implements Printable, Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
Test it Now
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods but its implementation is provided by class TestTnterface1, so there is no ambiguity.
-----------------------------------------------------------------------
In other words, Interface fields are public, static and final by default, and the methods are public and abstract. -- Imp
-----------------------------------------------------------------------
18. VV Important for interview - related to interface --- https://www.baeldung.com/java-static-default-methods
-- Also included Diamond problem - > which is due to default method in interface .
---
-----
-------
-----------------------------------------------------------------------------
19 . Difference between abstract class and interface
https://www.javatpoint.com/difference-between-abstract-class-and-interface
-----------------------------------------------------------------------------
20 . Java Access Modifiers with Method Overriding
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.
class A{
protected void msg(){System.out.println("Hello java");}
}
public class Simple extends A{
void msg(){System.out.println("Hello java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}
The default modifier is more restrictive than protected. That is why, there is a compile-time error.
-----------------------------------------------------------------------------
https://www.javatpoint.com/wrapper-class-in-java - Wrapper Class -- autoboxing and unboxing
------------------------------------------------------------------------
21. Object class in Java
The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.
public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's monitor.
public final void wait(long timeout)throws InterruptedException causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait(long timeout,int nanos)throws InterruptedException causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).
public final void wait()throws InterruptedException causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected.
-------------------------------------------------
https://www.javatpoint.com/object-cloning -- check object cloning
---------------------------------------------------
String
---->
For Interview Purpose <<<<<VVIP>>>>
Do You Know?
Why are String objects immutable?
How to create an immutable class?
What is string constant pool?
What code is written by the compiler if you concatenate any string by + (string concatenation operator)?
What is the difference between StringBuffer and StringBuilder class?
------------------------------------------
22 . Why String class is Final in Java?
The reason behind the String class being final is because no one can override the methods of the String class. So that it can provide the same features to the new String objects as well as to the old ones.
---------------------------------------------------
23 . Why String objects are immutable in Java?
As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to one object "Sachin". If one reference variable changes the value of the object, it will be affected by all the reference variables. That is why String objects are immutable in Java.
Following are some features of String which makes String objects immutable.
1. ClassLoader:
A ClassLoader in Java uses a String object as an argument. Consider, if the String object is modifiable, the value might be changed and the class that is supposed to be loaded might be different.
To avoid this kind of misinterpretation, String is immutable.
2. Thread Safe:
As the String object is immutable we don't have to take care of the synchronization that is required while sharing an object across multiple threads.
3. Security:
As we have seen in class loading, immutable String objects avoid further errors by loading the correct class. This leads to making the application program more secure. Consider an example of banking software. The username and password cannot be modified by any intruder because String objects are immutable. This can make the application program more secure.
4. Heap Space:
The immutability of String helps to minimize the usage in the heap memory. When we try to declare a new String object, the JVM checks whether the value already exists in the String pool or not. If it exists, the same value is assigned to the new object. This feature allows Java to use the heap space efficiently.
-------------------------------------------------------------
24. String s=50+30+"Sachin"+40+40;
System.out.println(s);//80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.
---------------------------------------------------------
25 . https://www.javatpoint.com/string-concatenation-in-java --> Concatenation methods in java
-------------------------------------------------------------------
26 - https://www.javatpoint.com/StringBuffer-class --- > StringBuffer Methods
----------------------------------------
27 . Java StringBuilder Class
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
https://www.javatpoint.com/StringBuilder-class
--------------------------------------------
29 . Difference between String and StringBuffer
There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below:
No. String StringBuffer
1) The String class is immutable. The StringBuffer class is mutable.
2) String is slow and consumes more memory when we concatenate StringBuffer is fast and consumes less memory when we concatenate t strings.
too many strings because every time it creates new instance.
3) String class overrides the equals() method of Object class. StringBuffer class doesn't override the equals() method of Object class.
So you can compare the contents of two strings by equals() method.
4) String class is slower while performing concatenation operation. StringBuffer class is faster while performing concatenation operation.
5) String class uses String constant pool. StringBuffer uses Heap memory .
-----------------------------------------------
30 . Difference between StringBuffer and StringBuilder
No. StringBuffer StringBuilder
1) StringBuffer is synchronized i.e. thread safe. It means two StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of
threads can't call the methods of StringBuffer simultaneously. StringBuilder simultaneously.
2) StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.
3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
---------------------------------------------------
31 . How to create Immutable class?
There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members as the example given below:
Example to create Immutable class
In this example, we have created a final class named Employee. It have one final datamember, a parameterized constructor and getter method.
ImmutableDemo.java
public final class Employee
{
final String pancardNumber;
public Employee(String pancardNumber)
{
this.pancardNumber=pancardNumber;
}
public String getPancardNumber(){
return pancardNumber;
}
}
public class ImmutableDemo
{
public static void main(String ar[])
{
Employee e = new Employee("ABC123");
String s1 = e.getPancardNumber();
System.out.println("Pancard Number: " + s1);
}
}
Output:
Pancard Number: ABC123
The above class is immutable because:
The instance variable of the class is final i.e. we cannot change the value of it after creating an object.
The class is final so we cannot create the subclass.
There is no setter methods i.e. we have no option to change the value of the instance variable.
These points makes this class as immutable.
----------------------------------------------------------------------------------------------------------------------------------------------------------
32 . Java toString() Method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the String representation of the object.
If you print any object, Java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depending on your implementation.
Advantage of Java toString() method
By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.
Understanding problem without toString() method
Let's see the simple code that prints reference.
Student.java
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:
Student@1fee6fc
Student@1eed786
As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects but I want to print the values of these objects. Since Java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:
Example of Java toString() method
Let's see an example of toString() method.
Student.java
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city){
this.rollno=rollno;
this.name=name;
this.city=city;
}
public String toString(){//overriding the toString() method
return rollno+" "+name+" "+city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:
101 Raj lucknow
102 Vijay ghaziabad
In the above program, Java compiler internally calls toString() method, overriding this method will return the specified values of s1 and s2 objects of Student class.
--------------------------------------------------------------------------------------------------------
https://www.javatpoint.com/string-tokenizer-in-java -- String Tokenizer
------------------------------------------------------------------------------------------------------
https://www.javatpoint.com/java-regex -- Java Regex check before interview
---------------------------
Exception Handling
Ticky Questions for Interview -->
What happens behind the code int data=50/0;?
Is there any possibility when the finally block is not executed? --- > only when program is terminated abnormally
33 .Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError, AssertionError etc.
-----------------------------------------------------------------------------------
34. Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
-------------------------------------------------------------------------------------
For Interview - Try putting wrong exception , and also try to put 10/0 in catch block similarly try other exception in these cases exception wont be able to handle and it wont print
the sop after the catch block , but it will print the finally block .. (try by yourself)
-------------------------------------------------------------------------------------------
Let's see an example, to handle the exception without maintaining the order of exceptions (i.e. from most specific to most general).
MultipleCatchBlock5.java
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){System.out.println("common task completed");}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
System.out.println("rest of the code...");
}
}
Output:
Compile-time error // So we have to maintain the order of exception here means parent Exception e should come after ArithmeticException
---------------------------------------
35 . Throw and Throws --------- VVIP
The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.
throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
Important points to remember about throws keyword:
throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless. ------------------ Important
We can declare both types of exceptions using throws clause i.e. checked and unchecked exceptions. But the method calling the given method must handle only checked exceptions. Handling of unchecked exceptions is optional.
Can skip handling of unchecked exceptions
public class JavaExample
{
public static void main(String[] args)
{
try
{
//Can skip handling of NullPointerException (unchecked exception)
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public static void method( ) throws NullPointerException, FileNotFoundException {
//code
}
}
throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program.
By the help of throws keyword we can provide information to the caller of the method about the exception.
FOR CHECKED EXCEPTION THROW Keyword SHOULD BE COVERED WITH CATCH BLOCK , WHILE FOR UNCHECKED EXCEPTION ONLY THROW WOULD BE FINE .
--- << CHECK javatNotes.com
----------------------------------------------------------------------------
36. Java throws Example
TestThrows.java
public class TestThrows {
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}
System.out.println("Rest of the code..");
}
}
In the above program if we do not write throws ArithmeticExcep[tion then it will throw error we need both try catch and throws in this case , throws in another method and try catch in main method .
------------------------------------------------------------------------------------------------------------------------------------------------------------------
37. https://www.javatpoint.com/difference-between-final-finally-and-finalize - Difference between final , finally and finalize ...
https://www.javatpoint.com/custom-exception -- Custom Exception
--------------------------------------------------------------------------------------------------------
38 . Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
Each process has an address in memory. In other words, each process allocates a separate memory area.
A process is heavyweight.
Cost of communication between the process is high.
Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
Threads share the same address space.
A thread is lightweight.
Cost of communication between the thread is low.
------------------------------------------------------------------------------------
39 . Java Thread class
Java provides Thread class to achieve thread programming. Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.
------------------------------------------------------------------------------------
40 . Explanation of Different Thread States
New: Whenever a new thread is created, it is always in the new state. For a thread in the new state, the code has not been run yet and thus has not begun its execution.
Active: When a thread invokes the start() method, it moves from the new state to the active state. The active state contains two states within it: one is runnable, and the other is running.
Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the thread may be running or may be ready to run at any given instant of time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual thread. Each and every thread runs for a short span of time and when that allocated time slice is over, the thread voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice of time. Whenever such a scenario occurs, all those threads that are willing to run, waiting for their turn to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.
Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally, the most common change in the state of a thread is from runnable to running and again back to runnable.
Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in the blocked state or is in the waiting state.
For example, a thread (let's say its name is A) may want to print some data from the printer. However, at the same time, the other thread (let's say its name is B) is using the printer to print some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable to perform any execution and thus never consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread A remains idle until the thread scheduler reactivates thread A, which is in the waiting or blocked state.
When the main thread invokes the join() method then, it is said that the main thread is in the waiting state. The main thread then waits for the child threads to complete their tasks. When the child threads complete their job, a notification is sent to the main thread, which again moves the thread from waiting to the active state.
If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread scheduler to determine which thread to choose and which one to reject, and the chosen thread is then given the opportunity to run.
Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its name is A) has entered the critical section of a code and is not willing to leave that critical section. In such a scenario, another thread (its name is B) has to wait forever, which leads to starvation. To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in the waiting state for a specific span of time, and not forever. A real example of timed waiting is when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in the timed wait state. After the time runs out, the thread wakes up and start its execution from when it has left earlier.
Terminated: A thread reaches the termination state because of the following reasons:
When a thread has finished its job, then it exists or terminates normally.
Abnormal termination: It occurs when some unusual events such as an unhandled exception or segmentation fault.
A terminated thread means the thread is no more in the system. In other words, the thread is dead, and there is no way one can respawn (active after kill) the dead thread.
-------------------------------------------------------------------------------------------------------------------------------
41 . Ways to create a Thread in Java ?
https://www.javatpoint.com/how-to-create-a-thread-in-java
-------------------------------------------------------------------------------------------------------------------------------
42 . https://www.javatpoint.com/thread-scheduler-in-java -- setting priority for the thread to run first --- > check copy and this link for detail .
---------------------------------------------------------------------------------------------------------------------------------------
43 . Can we start a thread twice
No. After starting a thread, it can never be started again. If you does so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception.
Let's understand it by the example given below:
public class TestThreadTwice1 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
}
}
Test it Now
Output:
running
Exception in thread "main" java.lang.IllegalThreadStateException
----------------------------------------------------------------------------------------------------------------------
44 . What if we call Java run() method directly instead start() method?
Each thread starts in a separate call stack.
Invoking the run() method from the main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
Problem if you direct call run() method--->
class TestCallRun2 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestCallRun2 t1=new TestCallRun2();
TestCallRun2 t2=new TestCallRun2();
t1.run();
t2.run();
}
}
Test it Now
Output:
1
2
3
4
1
2
3
4
As we can see in the above program that there is no context-switching because here t1 and t2 will be treated as normal object not thread object.
--------------------------------------------------------------------------------------------------------