-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompiler vs Interpreter
More file actions
375 lines (330 loc) · 19.9 KB
/
Copy pathCompiler vs Interpreter
File metadata and controls
375 lines (330 loc) · 19.9 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
1.) Compiler:
Converts highlevel language code(.java) to byte code(understandable by JVM)
Done by javac which is inside tools.jar
Steps:
1.) Parsing entire source file by reading it and stripping boundary characters such as {}.
2.) AST/ Abstract Syntax Tree creation by representing each expression and statement into a tree with class com.sun.tools.JCTree. Syntax validation of literals done.
3.) Desugar - extended for loops to normal iterators etc
4.) Type check/ Inference - To validate type of everything, method signatures etc. Done by traversing AST with the help of visitor pattern.
5.) Byte code conversion
6.) .class file writing
2.) Interpreter:
'java' is app laucher as per Oracle doc (java <name of .class file for main program>). It gives a console. javaw is same as java but without console.
Startup Errors comes as popup window if any for javaw.
Line by line conversion from one language to another including syntax verification.
Laucher starts a runtime environement. A Java virtual machine.
For Java, interpreter is part of JVM/ runtime and it can translate byte code to machine code/ native instructions and runs immediately lin by line.
Eg: for runtime are Hotspot VM, Azul VM etc.
Nowadays there is JIT or Just In Time compiler which can optimize execution speed in JVM. What it does is cache machine code equivalent for frequently executing byte code parts.
But this is also considered as interpreter.
Java Intepreter
3.) Float vs Double (4byte vs 8byte in space. Double has more precision with decimal points. By default everything with decimal precision are treated double in Java.
But for some processors, float takes half space but not accurate on round off while double takes more space but is more precise.
Nowadays there are processors optimised for Mathematical calculatiosn which can process double better than float.)
Why char is 2byte in Java?
ASCII was 1byte. Numbers from 0-127 used to encode characters and symbols.
To include all languages people started using 128-255 as well which is part of 1 byte itself.
But all languages in universe were not fit in that.
So came unicode. It can use 2 byte 2^16 possibilities. This is what Java is used and that's why char is 2byte in Java.
encode -> convert to bytes
decode -> convert from bytes
codec -> logic to encode and decode in a format. Eg: codec for unicode is UTF-8 and UTF-16.
Unicode uses code points to prepresent each leter/ symbol in any language. It's standard. Uses U(unicode)+hex to indicate chars in the world.
UTF-8 Uses min 8bit to represent unicode chars. uses 1byte for 0-127. Above that it uses max 6bytes to represent in encoded form.
UTF-16 uses min 16bits to represent unicode characters
4.) Note: >=1.7 allows 20_0_0 considered as 2000
byte - 1byte
char - 2byte
short - 2byte
int - 4byte
float - 4byte
long - 8byte
double - 8byte
5.) switch case supports String only after >=1.7
6.) Constructors are for creating object or more precisely, it is to allocate memory for the object of the class.
7.) class Constructor{
Constructor(Integer i){"int"}
Constructor(Long l){"long"}
when we do;
new Constructor(10.5);// error comes since input is double and need to cast to int ot long to get accepted. If
Constructor(Object o){"any"}
was also present, no error comes since 10.5 will be considered and casted to Object.
8.) Static variables are kept in class loader memory
9.) By convension one public class per file name is followed in Java.
It's for maintanability of code as well as to reduce burden of compiler to map public classes easily.
If multiple public classes kept in one file, for compiler, it will be difficult to map .class files and source code.
10.) Static Block:
When used in a public class without main, till 1.5, it used to execute static block and terminates with error as main is not found.
But from 1.6, it will compile but will not run showing error as main not found.
If multiple static blocks are there, it followes the order of defining in code and execute one by one.
Internally in .class files what is shown on decompiling is, all static blocks are aggregated together.
11.) Inner class usage:
Outer{
Inner{
}
}
usage: Outer o = new Outer();
Outer.Inner i = o.new Inner();// Here, type is given as Outer class. Inner class. new is using outer object . new Inner class
Internally, creates Outer.class, Outer.class and Outer$Inner.class. Internally what it does is, creates a constructor for Inner which accepts outer and uses it.
For static inner classes,
Outer.Inner i = new Outer.Inner(); will work.
We can define classes inside a method as well.
class A{
void test(){
class X{
void show(){
System.out.println("Test X");
}
}
new X().show();//will work. Can use annonymous classes also instead.
}
}
This type of classes inside methods will create byte code in files as A$1X.class, A$2X.class etc.
12.) Iterator and Enhanced For Loop:
Enhanced for loop used to iterate whole set of data. We can consider as it's condition is length of array/ collection.
Internally, compiler converts enhanced for loop used over array into normal for loop.
In case of Collections, enhanced for loop/ for each is converted into iterator.
13.) 2 dimentional array is array of arrays. If the arrays contained in 2D array is of variable length, this 2D array is called Jagged array(number of cols are not fixed).
14.) Var args:
Treats the values as an array. Not a list.
15.) Inheritance:
For default methods in interface;
interface A{default show(){}}
interface B{default show(){}}
C implements A, B{
show(){
A.super.show();//if need to invoke.
}
} //will give error to override show() since both have same default method.
16.) Dinamic Method Dispatch:
When we use runtime polymorphism;
class A{public void show()}
class B extends A{public void show()}
class C extends A{public void show()}
Now;
A a = new B();// Dynamic binding/ runtime polymorphism. Decides which object to be created and mapped at runtime.
a.show(); // Dynamic method dispatch. Decides which method to call based on bounding class. Here, of B
a = new C();// Dynamic binding/ runtime polymorphism. Decides which object to be created and mapped at runtime.
a.show(); // Dynamic method dispatch. Decides which method to call based on bounding class. Here, of C
Dynamic method dispatch is required due to runtime polymorphism.
17.) encapsulation vs abstraction:
encapsulation: bind data to methods. Eg: make fileds private and make it accessible only via getters and setters. Ie; here it's visibility controlling.
Why needed? For data safety. If exposed through methods, eve we can log access to the data rather than no clue of change in case of direct use of var.
Can check if someone accessing is authorised to use before access in methods.
It's data hiding behind methods.
With the help of access modifiers
abstraction: give only relevant details and hide other things.
Eg: When we see a car, its internal parts are hidden.
With the help of abstract classes/interfaces.
Eg: expose only APIs as part of interface and implemnetation class methods will be hidden from the user of that interface.
18.) Boxing/ Wrapping - primitive to Wrapper. (Integer i = Integer(10);)
Unboxing/ Unwrapping - wrapper to primitive. (int ii = i.intValue();)
Autoboxing - wraps automatically. Eg: Integer i = 10; (casts automatically to Integer from int)
Autounboxing - unwraps automatically. Eg: int ii = i; (casts to int from Integer)
When we do int ii = i.intValue(), compiler treats it like ii = i; with auto unboxing in byte code. Can check by decompiling.
Why we need wrappers?
To use with some frameworks which supports non-primitive types only.
Also it helps to use with generics. Primitives are not treated as Objects. But Collection<E> expects an object type.
So, Collection<int> is not supported whereas Collection<Integer> is possible. That's the relavance of primitive wrappers.
But primitives are faster than wrappers as it does not have autoboxing and unboxing overhead.
19.) Abstract classes vs Interfaces after Java8:
Object creaton and constructor is possible only for abstract classes.
Fields are public static final for interfaces.
No final methods allowed in interface. Only public static default strictfp(
strict floating point precision for calculations irrespective of platforms. Can be used on with class, interface or methods.
If class A is strictfp doesn't mean it's children are also strictfp. But parent's methods will be strictfp.) abstract methods allowed.
Interfaces not accepts private or protected for any tpe of methods or variables.
20.) When to use abstract class vs interface:
Use interfaces when a standardized API contract is to be maintained.
Interfaces enables classes inheriting interface to inherit other class if required in future. Abstract classes cannot as multiple inheritance with class is not there in Java.
Interface can be used for more generic methods.
Abstract classes are preferred when closely related is the child classes.
21.) Anonnymous Classes:
Used to avoid creation of another child class which is not having much reusability. Ie; if object is of one time use, narrow scoped childcClasses are created this way.
Internally,
class A{void show(){System.out.println("A");}}
class Main{
public static void main(String[] args){
new A(){
show(){
System.out.println("Annonymous");
}
}().show();// output Annonymous
//or
new A(){
}().show();// gives output A
}
A.class, Main$1.class, Main$2.class etc will be class files equivalent to actual class and annonymous classes of the same. $Count is added to name of class calling it.
22.) Funcational Interfaces:
Only one method.
Can use @FuncationalInterface for type safety at compile time itself.
Lambda expressions are used to provide implementations of functional interfaces as a replacement of annonymous classes.
interface I{void show(){}}
I i = ()->{System.out.println("Hai from lambda");} is the format. ()->{} is method body for show method.
Funcational interface can have static or default methods. But only one abstract method.
23.) package-info.java:
File that can hold info related to a package.
It can hold annotations applicable for all classes of a package etc.
Mainly for documenting and annotating.
Eg:
package-info.java
-----------------
/**
*@author asha
*/
@Depricated// this annotation is package scope. So can be used. But when we use classes in other packages, no deprication warning comes.
//But for a class inside this package, the package com.basic's basic will be striped to indicate as depricated.
package com.basic;
24.) Exception Handling:
Object
|
Throwable
| |
Exception ---| Error
| |
RuntimeException Other compile time exceptions(IO exception, No such method, class not found etc)
|
unchecked exceptions(null pointer, index out of bound, class cast, number format etc)
test(){
try{
return 5;
}catch(Exception e){
return 10;
}finally{
return 20;
}
}
returns 20 irrespective of if normal flow or exception occurs.
If System.exit(0); in try or catch vlock, then only finally block is skipped.
try{
doException();
System.exit(0);
}catch(Exception e){
}finally{
}
Comes to try, catch and finally if exception throws.
Else,
terminates at System.exit(0); itself.
If Parent class ethod throws a check exception, child may or may not throw it. But child cannot throw a checked exception which is not defined in Parent.
But child method can throw any number of runtime exceptions.
25.) Error:
Error extends Throwable{}. This is for serious blockers. Eg: LinkageError, OutOfMEmoryError, StackOverFlowError, NoClassDefFoundError etc.
Don't try to catch it.
It's child classes are treated like runtime exceptions itself. But not extending RuntimeException.
26.) Runtime Exceptions are thrown by JVM/ runtime system at runtime.
27.) Error: Programatically unrecoverable. Eg: out of memory
Runtime Exception: Due to negligence from developers. Recoverable. Eg: null pointer
Exception: Programatically recoverable but unexpected condition outside of code.Eg: DB down
28.) Multi exception catch, try with resource etc came from 1.7.
But multi-catch exceptions should be disjoint.
Ie;
catch(Exception | IOException e) // is error as IOException is child of Exception.
29.) Try with Resource:
try(AutoTry at = new AutoTry()){
}
Note: Try can be given alone if AutoClosable's close() method is not throwing exception
Eg:
class AutoTry extends AutoClosable{
public void close() /*throws Exception*/{
//hai
}
}
or the method in which we use try with resource throws the exception from close() method explicity.
ie;
void method() throws IOException{
try(AutoTry at = new Autotry()){
}
}
Eg:
class AutoTry extends AutoClosable{
public void close() throws IOException{
//hai
}
}
30.) Threads:
For:
1.)Efficient utilization of resources(processor cores)
2.)Do multiple tasks at the same time to achieve a single process result.
3.)Achieve async(threads to serve multiple requests in web servlets)
Parallelism vs Concurrency:
Parallel - 2 people doing same or different tasks independently(Eg: students writing their exams in parallel).
Concurrent - Interruptability. Resource is only one and 2 people are sharing it time sliced(Eg: cooking and office work done by one person interruptably).
Parallelism can be related to drive through 8 line road
whereas
Concurrency is drive in a single line road with good traffic. Gaps are used by various cars to reach destination.
Or
2 queues to same cashier(shared resource) is concurrency.
2 queues to two cashiers(non-shared resources) is parallelism.
31.) Thread.yeild():
---------------
Indicates that this current thread is ready to release it's processor since it is ok to delay it's task for a while. Scheduler can accept it or can neglect it.
Not much recommended to use. Use only for bench marking etc as per doc.
If OS scheduler is time sliced, it will be oever burden since yeild gives a selection time where chance is there for selection of yeilded thread.
t1.join():
---------------
Indicates that the thread calling t1.join() have to wait() till the thread t1 finishes it's job.
object.wait():
---------------
Asks current thread using this object to wait for sometime releasing all holding resources and go to waiting threads. If lucky enough, will get chance to go live soon.
Give only inside sync block. Else IllegalMonitorStateException comes since the current thread is not owner of this object's monitor.
object.notify():
---------------
Indicates that this object is free to be used by threads who all are waiting for that particular object. But selection of one eligible thread is done by scheduler.
Give only inside sync block.
object.nofifyAll():
---------------
informs all waiting threads that this object is free to be used now. Who ever wins, can take it.
Give only inside sync block.
32.) notify vs notifyAll:
Use notify if any specific reason is there to wake up one thread at a time. Else use notifyAll.
If n threads are waiting on an object and each of them are going to do different type of operations on notification, it's better to use notifyAll().
If there is a special case of doing something by one thread at a time is allowed, go for notify().
33.) Startvation:
------------
Due to lack of priority, a thread waits indefinitly to get a chance for processor.
Racce Condition:
----------------
Multiple threads are trying to change the same data and end up doing it together and gets wrong value.
Eg: b= true;
t1 changes it to false if it was true.
By the time t1 changing, t2 changed it to false.
So, now t1 should ideally not make it false as it's already false. But end up in chnaging by t1 as well.
This is a race condition.
Atomic variables can avoid this. Else proper locking/ synchronization can do.
Deadlock:
---------
Due to T1 waits for T2 and T2 waits for T1 to release the resources which never happens.
Priority Inversion:
Waiting of a high priority thread to get execution chance due to a low priority thread execution in progress,
actually the high priority thread becomes similar to a low priority one, waiting. This situation is priority inversion.
JVM resolves this problem by priority inheritance where JVM scales the currently running low priority thread
to the same priority of the high priority one came in. Then once the exceuiton of enhanced proirity thread is done,
gives control to that high priority thread came in.
Most JVMs prefer to use OS schedulers to get rid of such issues as OS uses time slicing as well.
Time slicing helps to avoid starving of equal priority threads.
34.) Collections:
1.2 - Collections
1.5 - Generics
1.7 - Diamond
35.) For LinkedHashSet, internally uses HashSet. This hashset uses map internally. So, map used will be HashMap or LinkedHashMap accordingly.
36.) Collections.java:
sort() expects a list of Comparable(compareTo(otherObj)) type. We can ovveride how to sort using Comparator's compare(a, b) method and pass it to sort() method..
Proxy vs Reverse Proxy:
Proxy : dummy behind which our actual systems are masked and all requests goes to servers through this proxy.
anonymity, caching, blocking unwanted sites, geo fencing etc are advantages
client 1
\
\
client 2 - proxy - google server
/
client 3 /
----------------------------------------------------------
Reverse Proxy: There will be a dummy server to which all client requests are coming and it will be routed to different services serving the same purpose.
Best for micro services.
traffic control, load balancing, caching of response for idempotent requests, logging, canary deployement
server 1
/
client - reverse proxy - server 2
\
server 3
-----------------------------------------------------------