Java Programming Language

17 October 2017

Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.

Pass by Value vs Pass By Reference in Java

  • Pass-by-value

The actual parameter (or argument expression) is fully evaluated and the resulting value is copied into a location being used to hold the formal parameter’s value during method/function execution. That location is typically a chunk of memory on the runtime stack for the application (which is how Java handles it), but other languages could choose parameter storage differently.

  • Pass-by-reference The formal parameter merely acts as an alias for the actual parameter. Anytime the method/function uses the formal parameter (for reading or writing), it is actually using the actual parameter. Java is strictly pass-by-value,

OverLoading vs OverRiding in Java

  • Overloading : It occurs when two or more methods in the same class have same method name but different parameters .
public class Shape {

public void drawCircle() {
System.out.println("Drawing Circle");
}
//Overloading Method with Parameters
public void drawCircle(int radius){
System.out.println(" Drawing Circle With radius"+r);
}}
  • Overriding : It means when two methods have same name and parameters where one method is in the parent class and other method is in the child class.It allows a child class to provide a specific implementation of a method that is already provided in the parent Class.
class Shape{
public void drawCircle(){
System.out.println("Drawing Circle from Shape Class");
}
class Circle extends Shape(){

public void drawCircle(){
System.out.println(" Drawing Circle from Circle CLass");
}}}

public class OverridingTest{

public static void main(String [] args){
Shape shape = new Circle();
shape.drawCircle();
}}

Above example prints >Drawing “Circle from Circle Class “

Abstract classes vs. Interfaces

Field Abstract Class Interface
Method Type Abstract ,Non-Abstract ,default and Static Abstract Method
Final Variable final and non-final variable Variables final by Default
Variable Type final, non-final, static and non-static variables only static and final variables
Access Modifiers can have class members like private, protected, etc. All the Members of a Java interface are public by default
Keywords abstract class can be extended using keyword “extends”. A Java interface can be implemented using keyword “implements”
Implementation Abstract class can provide the implementation of interface. Interface can’t provide the implementation of abstract class.
Multiple Implementation An interface can extend another Java interface only an abstract class can extend another Java class and implement multiple Java interfaces

Thread Safety in Java

Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized

How Concurrent Hash Map Works

ConcurrentHashMap is the implementation of HashMap which is thread safe. It allows multiple readers to read concurrently without any blocking. This is achieved by partitioning Map into different parts based on concurrency level and locking only a portion of Map during updates.

Hashtable vs HashMap

Factors HashMap Hashtable
Synchronization java.util.HashMap methods is not synchronized, not thread safe and can’t be shared between many threads java.util.Hashtable methods is synchronized,thread-safe and can be shared with many threads
Null Key/Values HashMap allows one null key and multiple null Values Hashtable doesnot allows any null key or value
Preference HashMap is preferred if thread synchronization is not needed Since Hashtable is legacy class ,use ConcurrentHashMap instead if needed synchronization
Instantiate Map<String, List<String>> foo = new HashMap<String, List<String>>(); Map<String ,List<String>> foo = new Hashtable<String,List<String>>();
Insertion Order Does not maintain Insertion Order Does not maintain Insertion Order

Why HashTable doesn’t allow null and HashMap does?

To successfully store and retrieve objects from a HashTable, the objects used as keys must implement the hashCode method and the equals method. Since null is not an object, it can’t implement these methods. HashMap is an advanced version and improvement on the Hashtable. HashMap was created later.

source: HashTable and Hash Map Differences

Maintaining Insertion order in Hashmap

HashMap itself doesn’t maintain insertion order - but LinkedHashMap does.

HashMap

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

LinkedHashMap

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

Synchronization in Java

In Java the coordination of multiple threads that must access shared data is called synchronization.

It is mainly used to prevent race condition that can cause data to be found in intermediate or inconsistent state. When using Synchronization ,following things needs to be considered

  • Threads might be racing prior to the synchronized section of code.
  • Order in which threads execute the synchronized code is determined by order in which lock is granted.
  • To design code so that is threadsafe with minimal synchronization ,we can use Atomic classes.

Failure Atomic in Java

After an object throws an exception, it is generally desirable that the object still be in a well-defined, usable state, even if the failure occurred in the midst of performing an operation. This is especially true for checked exceptions, from which the caller is expected to recover. Generally speaking, a failed method invocation should leave the object in the state that it was in prior to the invocation. A method with this property is said to be failure atomic.

Why main method is static in Java

Because object is not required to call static method. if It were non-static method, jvm creates object first then call main() method that will lead to the problem of extra memory allocation.

Volatile keyword in Java

Volatile keyword is used in Java to defined a variable which will be modified by different threads. The value of the volatile variable will never be cached thread locally but all read and writes go straight to main memory .

Wrapper Classes in Java

A wrapper class wraps or encloses around a data type and gives it an object appearance.

Java wrapper classes are the Object representation of eight primitive types in java.

Making Main method Private in Java

To act as the start point in your application, the Main method is not required to be public. If you did decide to make it public, it would be possible for it to be called from other classes or assemblies. Typically you will not need to do this, so you can keep it private. One possible use case for making it public would be to allow automated tests to invoke it.

Linked List and ArrayList

  • If we want to add and remove data from the top or the bottom we use ArrayList ,But if we want to add or remove data in between the list we use Linked List.
  • LinkedList does not care where we add the item in the list, but Array List does.
  • Array List Manages array Internally.

Serialization in Java

Use of serialization is to transfer objects over network. We can write the Java object as byte array in memory, and later again construct the object from byte array in memory,

Countdown Latch vs CyclicBarrier in Java

Both CyclicBarrier and CountDownLatch are used to implement a scenario where one Thread waits for one or more Thread to complete there job before starts processing.Main difference between them is that you can not reuse same CountDownLatch instance once count reaches to zero and latch is open, on the other hand CyclicBarrier can be reused by resetting Barrier, Once barrier is broken.

Source

Prevent an object from getting garbage collected in java

To prevent an Java object from being garbage collected ,we can use a singleton pattern with an static reference to that object .Doing this ,the object won’t be able for garbage collection until the classloader gets garbage collected .

Advantage of Using Generics in Java

Generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods.It allows a class or method to operate on objects of various types while providing compile-time type safety to collection framework and by eliminating casting. This helps in detecting bugs at compile time itself which is easier than fixing bugs in run time . It avoids the ClassCastException at run time.

Code that uses generics has many benefits over non-generic code:

  • Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

  • Elimination of casts. The following code snippet without generics requires casting:

List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);

When re-written to use generics, the code does not require casting:

List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);   // no cast

  • Enables programmers to implement generic algorithms. By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

Reflections in Java

Java Reflection is a process of examining or modifying the behavior of a class at run time.

The java.lang.Class provides many methods that can be used to get metadata, examine and change the run time behavior of a class.

The java.lang and java.lang.reflect packages provide classes for java reflection.

The Reflection API is mainly used in:

  • IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
  • Debugger
  • Test Tools etc.

Copying an Object in Java

The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don’t implement Cloneable interface, clone() method generates CloneNotSupportedException.

Different ways to write Singleton Class

There are at least four ways to implement Singleton pattern in Java

  • Singleton by synchronizing getInstance() method
  • Singleton with public static final field initialized during class loading.
  • Singleton generated by static nested class, also referred as Singleton holder pattern.
  • From Java 5 on-wards using Enums

Static keyword in Java

static members belong to the class instead of a specific instance.

It means that only one instance of a static field exists in the application and will be shared by all instances.

Since static methods also do not belong to a specific instance, they can’t refer to instance members static members can only refer to static members. Instance members can, of course access static members.

Java 1.8 Features

Below are some of the new features that Java 8 provides

  • Lambda expression Adds functional processing capability to Java.

  • Method references Referencing functions by their names instead of invoking them directly. Using functions as parameter.

  • Default method From Java 8 ,Interface allows to have default method implementation.

  • New tools

Java 8 has added new compiler tools and utilities like ‘jdeps’ to figure out dependencies

  • Stream API Java 8 provides a new stream API to handle continuous streams of data.

  • Date Time API Improved date time API.

  • Optional Emphasis on best practices to handle null values properly.

Types of JVM memory available

The JVM memory consists of the following segments:

  • Heap Memory, which is the storage for Java objects
  • Non-Heap Memory, which is used by Java to store loaded classes and other meta-data
  • JVM code itself, JVM internal structures, loaded profiler agent code and data, etc.

Java Class Loader

The Java Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine.

  • Bootstrap Class Loader Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.
  • Extensions Class Loader JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. *Extensions class loader loads classes from this ext folder. Using the system environment properly java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.

  • System Class Loader Java classes that are available in the java classpath are loaded using System class loader.

Data types in Java

Java has two types of data

a. Primitive Data Types: Primitive data types are predefined and pre-named by the language.

Java has 8 primitive data types

  • byte
  • char
  • boolean
  • int
  • short
  • float
  • double
  • long

b. Non-Primitive Data Types: They are not defined by the language but rather are created by the person writing the code.

They are also called as “reference variables” or “object references” as they refer a memory location where data is stored .

Example are Array ,String etc..

Controlling Java heap memory or memory allocation

Memory in Java application can be controlled from the command line and using certain parameters,

-Xmx : maximum heap size

-Xms : Initial Heap Size

-Xss : Sets the Java Thread Size

To check all Java related command line arguments use java -X from command line


[email protected]:~$ java -X
    -Xmixed           mixed mode execution (default)
    -Xint             interpreted mode execution only
    -Xbootclasspath:<directories and zip/jar files separated by :>
                      set search path for bootstrap classes and resources
    -Xbootclasspath/a:<directories and zip/jar files separated by :>
                      append to end of bootstrap class path
    -Xbootclasspath/p:<directories and zip/jar files separated by :>
                      prepend in front of bootstrap class path
    -Xdiag            show additional diagnostic messages
    -Xnoclassgc       disable class garbage collection
    -Xincgc           enable incremental garbage collection
    -Xloggc:<file>    log GC status to a file with time stamps
    -Xbatch           disable background compilation
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    -Xss<size>        set java thread stack size
    -Xprof            output cpu profiling data
    -Xfuture          enable strictest checks, anticipating future default
    -Xrs              reduce use of OS signals by Java/VM (see documentation)
    -Xcheck:jni       perform additional checks for JNI functions
    -Xshare:off       do not attempt to use shared class data
    -Xshare:auto      use shared class data if possible (default)
    -Xshare:on        require using shared class data, otherwise fail.
    -XshowSettings    show all settings and continue
    -XshowSettings:all
                      show all settings and continue
    -XshowSettings:vm show all vm related settings and continue
    -XshowSettings:properties
                      show all property settings and continue
    -XshowSettings:locale
                      show all locale related settings and continue

The -X options are non-standard and subject to change without notice.

[email protected]:~$

JNDI(Java Naming and Directory Interface)

It is an an API to access the directory and naming services in J2EE application.t is defined to be independent of any specific directory service implementation. Thus a variety of directories -new, emerging, and already deployed can be accessed in a common way. It’s used to separate the concerns of the application developer and the application deployer. When you’re writing an application which relies on a database, you shouldn’t need to worry about the user name or password for connecting to that database.

JNDI allows the developer to give a name to a database, and rely on the deployer to map that name to an actual instance of the database.

Overriding Constructors in Java

By rule in Java, a constructor cannot be overridden but a method can be overridden.

It looks as if constructor is overridden but not.

The members of a class are instance variables and methods but not constructors because

a constructor cannot be overridden. a constructor cannot be called with an object but method can be called. To call a constructor, an object must be created. in case of methods, we say, the “subclass method can call super class method”. But it cannot be said with constructors and in turn we should say “subclass constructor can access super class constructor”; here, correct word is “access” and not “call”. It is for the reason, a constructor cannot be overridden. we cannot call a super class constructor with super keyword. For constructors, specially one more term is created by Designers – super(). in method overriding, the super class method and subclass method should be of the same – same name, same return type and same parameter list. In constructors, same name constructor cannot be written in another class; it is compilation error.

Overloading Constructors in Java

It’s common to overload constructors by define multiple constructors which differ in number and/or types of parameters.

public class ConstOverloading{

public String name;
public int age;

public ConstOverloading(String name ,int age){
this.name = name;
this.age = age;
}

public ConstOverloading(String name)
this.name= "Hari";
age = 25;
}

String Buffer vs String Builder in Java

StringBuffer is a mutable and synchronized. It is slower in comparison to String Builder as it is thread safe.

StringBuilder is also mutable but it’s not synchronized. It is faster in compared to String Buffer as not a thread safe.

Reference

[1] Java Interview Questions

[2] Generics in Java

[3]Generics

[4] Object Cloning

[5] Java Singleton

Share: Twitter Facebook Google+ LinkedIn
comments powered by Disqus