Basics Flashcards

1
Q

Tell me about JDK, JRE and JVM

A

JDK - Java development tookit

  1. contains JRE + development tools(compiler, debugger)
  2. Platform specific
  3. provide all tools/executables/binaries used to compile/debug/execute a java program

JRE - Java Runtime environment

  1. JVM + binaries and other classes to execute java program
  2. no development tools:java compiler/debugger

JVM - Java virtual Machine

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Different Blocks execution order in Java class initialization

A
  1. Ananymous block
    {
    Logger.info(“this is ananymous block”);
    }
2. Static block
static {
   Logger.info("this is static block");
}
3. constructors
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Inner class

A
  1. 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 )
  2. Method local inner class(not anonymous)
    - inner class inside a method
    - can only access local variables in outer method which are declared as final
  3. static inner class
    - treated as a static member of outer class
  4. Anonymous inner class(lamda)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

String Builder and String Buffer

A
  1. String is unmodifiable, using concat is low performance also create a lot garbage
  2. String builder is fast , not thread safe
  3. String buffer is slow, thread safe(methods are synchronized)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

String Pool contains what?

Where is it located ?

A
  1. Contains String literals and interned Strings
  2. 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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why String is immutable?

A
  1. String are stored in Pool, 2 reference will point to same string
  2. HashMapkey - Always used as hashmap Key, also String cache its hashcode, so we do not need to compute every time, fast retrieve
  3. Security : used as passing host name, port, db connections
  4. 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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to compare String

A

0) Should not use “==” to compare string
1) equals method
2) equalsIgnoreCase method

lexicographically Ordered:

2) compareTo method
4) compareToIgnoreCase method

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Why character array is better than String for storing password in Java

A

Security risk - String is immutable and cached in string pool, so will be kept in memory for longer time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How does substring method work in Java?

A
  1. Substring shares same character array as original String
  2. 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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

String Pool

A
  1. In Java heap
  2. new string literal will be in pool
  3. new String obj will not in pool unless you call intern()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Exceptions - What is Java Exceptions

A

Throwable(Class):

1) exceptions - more deal programming mistakes, non availability of requested resource
2) errors (stackoverflowError, outofmemoryError) - more deal witn system errors

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is difference between Checked and Unchecked Exception in Java ?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Best practices to avoid exception

A
  1. return a default/zero value instread of null
  2. do not leave catch block empty
  3. handle checked exception at proper layer rather than just escalate(i.e. SQL exception)
  4. Have your own customized exception defined
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is difference between throw and throws keyword in Java?

A

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”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

New features for Exception handling

A
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())
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

finally block

A

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

17
Q

What is Enum in Java

A

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.

18
Q

Compare Enums

A

1) using == or the equals function.

2) the default implementation of Equals is == as well

19
Q

Can Enum implement interface in Java?

A

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

20
Q

Can we instantiate Enum

A

no, it always have a private constructor

21
Q

Advantages of using Enum(conpair with String)

A
  1. type safe
  2. limits inputs
  3. ilterable
22
Q

What is Generics in Java?

What is type erasure?

A
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.

23
Q

What is type inference?

A

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());
24
Q

What is blocking Vs non blocking I/O?

A

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 -

  1. 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
  2. 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.

25
Q

What is Java reflection?

A
  1. The name reflection is used to describe code which is able to inspect other code in the same system (or itself). 2. Invoke a method on a obj without knowing its type 3. Java annotation, In Junit test, java will find all method annotated with @Test and will call then when running the unit test