Basics Flashcards
Tell me about JDK, JRE and JVM
JDK - Java development tookit
- contains JRE + development tools(compiler, debugger)
- Platform specific
- provide all tools/executables/binaries used to compile/debug/execute a java program
JRE - Java Runtime environment
- JVM + binaries and other classes to execute java program
- no development tools:java compiler/debugger
JVM - Java virtual Machine
Different Blocks execution order in Java class initialization
- Ananymous block
{
Logger.info(“this is ananymous block”);
}
2. Static block static { Logger.info("this is static block"); } 3. constructors
Inner class
- Nested(private/member) inner class
- can access all members in outer class
- cannot have static method( is implicitly associated with an object of its outer class ) - Method local inner class(not anonymous)
- inner class inside a method
- can only access local variables in outer method which are declared as final - static inner class
- treated as a static member of outer class - Anonymous inner class(lamda)
String Builder and String Buffer
- String is unmodifiable, using concat is low performance also create a lot garbage
- String builder is fast , not thread safe
- String buffer is slow, thread safe(methods are synchronized)
String Pool contains what?
Where is it located ?
- Contains String literals and interned Strings
- Moved from PermGen to heap since Java 7
(The biggest issue of having String pool in PermGen is the small and fixed size of PermGen space. In some JVM it ranges from 32M to 96M, which is quite small for a large program.)
Read more: https://javarevisited.blogspot.com/2016/07/difference-in-string-pool-between-java6-java7.html#ixzz6AuJZzDwW
Why String is immutable?
- String are stored in Pool, 2 reference will point to same string
- HashMapkey - Always used as hashmap Key, also String cache its hashcode, so we do not need to compute every time, fast retrieve
- Security : used as passing host name, port, db connections
- Classloading mechanisim - it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load “java.io.Writer” could have been changed to load “mil.vogoon.DiskErasingWriter”
Read more: https://javarevisited.blogspot.com/2010/10/why-string-is-immutable-or-final-in-java.html#ixzz6AuLBIk3p
How to compare String
0) Should not use “==” to compare string
1) equals method
2) equalsIgnoreCase method
lexicographically Ordered:
2) compareTo method
4) compareToIgnoreCase method
Why character array is better than String for storing password in Java
Security risk - String is immutable and cached in string pool, so will be kept in memory for longer time
How does substring method work in Java?
- Substring shares same character array as original String
- Could load to memory leak is original string is no longer used and sub string is very small - origin string will be retained by substring from GC.
String Pool
- In Java heap
- new string literal will be in pool
- new String obj will not in pool unless you call intern()
Exceptions - What is Java Exceptions
Throwable(Class):
1) exceptions - more deal programming mistakes, non availability of requested resource
2) errors (stackoverflowError, outofmemoryError) - more deal witn system errors
What is difference between Checked and Unchecked Exception in Java ?
1) Different in how we handle them
2) checked needs to handle at compile time: try/catch/finally 'throws' IOException all drived from Exception class
3) unchecked
no need to handle at compiletime
all drived from RuntimeException: indexoutofbount/classcast
Best practices to avoid exception
- return a default/zero value instread of null
- do not leave catch block empty
- handle checked exception at proper layer rather than just escalate(i.e. SQL exception)
- Have your own customized exception defined
What is difference between throw and throws keyword in Java?
1) throws keyword is used in method signature
2) throw keyword is actually used to throw any Exception
i. e: throw new UnsupportedOperationException(“Not yet implemented”);
New features for Exception handling
1. multi catch block try { if (number.length() > 5) { throw new IllegalArgumentException(); } Integer.parseInt(number);
} catch (NumberFormatException | IllegalArgumentException e) { e.printStackTrace(); }
2. Automic resource management try ( FileInputStream stockQuoteReader = new FileInputStream("StockQuotes.txt"); FileOutputStream stockQuoteWriter = new FileOutputStream("StockQuotes.txt") ) { int var; while((var= stockQuoteReader.read())
finally block
1) always executed - even if you have return in try block
2) System.exit() /Runtime.getRuntime().halt(exitStatus) in try block, it will not executed
What is Enum in Java
1) Each enum class is compiled as a final class being a subclass of java.lang.Enum.so the class can not be extended
2) Each enum constant becomes a static final constant within that class.
3) an array $VALUES is created with all of the enum constants, in order of declaration.
Compare Enums
1) using == or the equals function.
2) the default implementation of Equals is == as well
Can Enum implement interface in Java?
Yes, Enum can implement interface in Java. Since enum is a type, similar to class and interface, it can implement interface. This gives a lot of flexibility to use Enum as specialized implementation in some cases
Can we instantiate Enum
no, it always have a private constructor
Advantages of using Enum(conpair with String)
- type safe
- limits inputs
- ilterable
What is Generics in Java?
What is type erasure?
Generics: 1. Use Type as parameters when defining classes/method 2. Reuse the same code for different inputs 3. Stronger type check at compile time 4.Generic programming 5.Elimination of casts List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0);
Type erasure
At Class/Method level
Aim is to Implement Java Generics.
1)Replace all unbounded parameter–> Object
Replace all bounded parameter –> its upper bound
2)Insert type casts if necessary to preserve type safety.
3)Generate bridge methods to preserve polymorphism in extended generic types.
What is type inference?
Java compiler’s ability to look at
each method invocation
corresponding declaration
-> the type argument (or arguments) that make the invocation applicable.
The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned.
Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.
To illustrate this last point, in the following example, inference determines that the second argument being passed to the pick method is of type Serializable:
static T pick(T a1, T a2) { return a2; } Serializable s = pick("d", new ArrayList());
What is blocking Vs non blocking I/O?
IO
Stream oriented
blocking(not returning) until read data
NIO
Buffer oriented
It is the block of memory into which we can write data, which we can later be read again
ByteBuffer buf = ByteBuffer.allocate(28);
Channel - It reads the data from an entity and places it inside buffer blocks for consumption. Channel implementation uses the native code to perform actual work.
channel. read(buffer)
channel. write(buffer)
Selector -
- which is used as a special type of channel that can be put into non-blocking mode. It can examine one or more NIO Channel’s and determines which channel is ready for communication i.e. reading or writing
- used for handling the multiple channels using a single thread - avoid switching thread
Main issue
Diffidult to know when the data finished loading as the method returns immediately(non-blocing),
when to use IO and NIO
NIO allows you to manage multiple channels (network connections or files) using only a single (or few) threads, but the cost is that parsing the data might be somewhat more complicated than when reading data from a blocking stream.
NIO - If you need to manage thousands of open connections simultanously, which each only send a little data, for instance a chat server, implementing the server in NIO is probably an advantage. Similarly, if you need to keep a lot of open connections to other computers, e.g. in a P2P network, using a single thread to manage all of your outbound connections might be an advantage.
IO - If you have fewer connections with very high bandwidth, sending a lot of data at a time, perhaps a classic IO server implementation might be the best fit.