Posts

Showing posts from September, 2018

Difference between JDK, JRE and JVM

In this blog post, I am going to explain the JVM, JRE and JDK and how they differ from each other. JVM JVM stands for Java Virtual Machine . It provides the environment to execute the Java byte code. As you probably know, Java is platform independent i.e. the same Java class file can be run on any operating system. It is the JVM which makes Java platform independent. When you compile code written in other programming languages, it creates files that are operating system specific. When you compile Java code, it is compiled into platform independent bytecode which is present in the .class file created after compilation. The JVM understands and executes this bytecode. So the JVM its on top of the operating system and runs the bytecode making Java platform independent. JRE JRE stands for Java Runtime Environment . JVM executes the bytecode from the .class file. However, in addition to the JVM, some additional libraries or jar files are required. So the JRE consists of these libraries and

Singleton class Explained

Singleton is a design pattern. A singleton class is a class for which only one object can be created. You can create a singleton class by using a private constructor. The following code snippet demonstrates this: private static Singleton singletonInstance;private Singleton(){}public static Singleton getInstance(){if (singletonInstance == null){singletonInstance = new Singleton();}return singletonInstance;} Here, we have a private constructor and a public getInstance method. The getInstance checks if an instance already exists. If an instance does not exist, it creates one using the private constructor. If an instance exists, it just returns it. So this method ensures that there is only one instance of the Singleton class. Any external class that needs an instance of the Singleton class, should invoke the getInstance method.

Difference between Break and Continue statement

Both the break and continue statements are used to change the fliw of executionin Java loops. However they differ in the way they work. What is a break statement? A break statement is used to terminate a loop. So the moment a break statement is encountered, control is transferred outside the loop even if condition part of the loop is true. Consider the following code snippet: for(int i = 0; i < 50;i++){if(i == 10)break;System.out.println("i="+i);}System.out.println("Outside loop"); This will print the following output: i=0i=1i=2i=3i=4i=5i=6i=7i=8i=9Outside loop So the loop executes till i reaches 10. Once the value of i is 10, the loop is exited. In addition a break statement is also used in a switch block to skip further case statements the moment a match is encountered. What is a continue statement? Continue statement is used when you want to stop processing the remaining code in the body of a loop for a particular iteration but continue the loop for the next i

Method Overloading Vs Method overridding

  In this blog post, I will be explaining the difference between method overloading and method overidding. What is method overloading? In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. The following code demonstrates this: public class AddDemo {public int add(int a,int b){return a+b;}public double add(double a,double b){return a+b;}} So here this class has two methods with the name “ add “. The first version accepts two integer values and returns an int, whereas the second version accepts two double values and returns a double. So both these methods have the same name i.e. add , but accept different types of parameters. Overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return typ

How to read input from the user in Java

This blog post demonstrates how to read a user’s input in Java.  You can use the following code snippet: public class ReadInput {public static void main(String args[]){Scanner scanner = new Scanner(System.in);System.out.println("Enter your input:");int num = scanner.nextInt();System.out.println("The number entered is "+num);}}   This code uses the Scanner class. This class has a method called nextInt which is used to read an integer input. In addition to this method, it has several other methods like nextDouble , nextFloat  ,etc which can be used to read other data types.  In addition, it also has a method called next , which can be used to read String data.

System.out.println explained

In this blog post, I will be explaining the System.out.println statement which is the first statement you will come across when you start learning Java programming.   System System is a final class in the java.lang package. It has several useful classes and methods. In addition to supporting standard input and output, it has methods to access external properties, method for initiating garbage collection, etc.  It supports input/output by providing static variables corresponding to the input/output streams.   Out Out is a static variable in the System class. It is of the type PrintStream .  Since it is a static variable, it is instantiated at start up. It is mapped to the standard output which is the console. This stream is already open and ready to accept output data.   Println Println is a method within the PrintStream  class.  There are several overloaded versions of this method that accepts different types of data like String, integer, double, etc.  Each method prints the data pa

Static keyword explained

In this blog post, I will be explaining Java’s static keyword. What is the static keyword? There will be times when you will want to define a class member i.e. either method or field independent of any object of that class. To create such a member, we need to precede its declaration with the   static keyword .  When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object, i.e. it can be accessed directly with the class name. You can declare both methods and variables to be static.   What is a Static Variable? A variable preceded with the static keyword is a static variable.  It can be accessed irrespective of any member directly using the class name. Variables declared as static are essentially, global variables. When objects of a class are created, no copy of a static variable is made. Instead, all objects of the class share the same static variable.   Static method A method preceded with the static keyword is a

How to add two numbers in Java

This blog posts shows how to add two numbers in Java:   public class Demo {public static void main(String args[]){int a = 10;int b = 20;int result = add(a,b);System.out.println("Result is "+result);}private static int add(int a,int b){int result = a+b;return result;}}   Here, we are using the method add to add two numbers. It accepts 2 integer values, adds them and returns the result. You can change the data type/ return value to anything else like long,short, float, double, etc. If you run the code, the following output will get printed to the console:   Result is 30

Difference between an abstract class and interface in Java

Another commonly asked interview question is to explain the difference between an abstract class and an interface. So in this blog post, I will give you a detailed explanation. What is an Abstract Class? An abstract class is a class that has one or more abstract method. An abstract method is a method that has the “abstract” keyword specified in the method definition. It does not have any method body, it is up to the subclass of the abstract class to provide an implementation for the abstract method. So why is an abstract class useful? Sometimes, you will want to create a super class that defines a method that all its sub classes must implement, but it leaves the exact implementation to the sub class. For ex. suppose you have a class called Shape, you can define an abstract method called draw. You can then have sub-classes for various shapes like Rectangle, Triangle, etc which provide implementations for the draw method. So while the “draw” method makes no sense for the Shape class, it

What is the final keyword in Java?

A very common interview question is to ask about the final keyword and what it means when it is used with different constructs like field, method, etc. So in this blog post I’m going to explain the final keyword in detail. Final Variable A variable can have the  final keyword specified.   Final keyword for a variable means that you cannot modify the contents of the variable after you declare it. So you cannot assign a value to a final variable, doing so will result in a compilation error. So you must initialize a final variable when you declare it. A final variable is generally used to define a constant in Java. It is a common coding convention to choose all uppercase identifiers for final variables. Final Method A method can have the final keyword specified. Final keyword for a method means that you cannot override the method. So if a sub-class tries to override a final method,  there will be a compilation error.  Although you cannot override a final method, a subclass still inheri

Java Access specifiers explained

Java provides a mechanism to precisely control access to the various members of a class via access specifiers. In this blog post, I will be explaining Java’s access specifiers i.e. private, protected, public and default. Private When a member of a class is specified as private then that member can only be accessed only by other members of its class. However, it will not accessible outside of the class via the dot operator. All private fields need to have getter and setter methods to retrieve and set their values. Otherwise, they will not be accessible outside of the class.. Public When a member of a class is modified by the public specifier, then that member can be accessed by any other code. It is not generally recommend to have this access specifiers for fields of a class. All fields of a class should have private access specifiers and public getter and setter methods to access them. Default access Specifier The default access specifier comes into play when no other access specifie

How to remove duplicate elements from a List

In this blog post, I will demonstrate how to remove the duplicates from a List. There are several ways to do this.   Looping throw the List and creating new List The following code snippet demonstrates this approach: public static List<String> removeDuplicates1(List<String> list){List<String> newList = new ArrayList<String>();for(String s:list){if(!newList.contains(s))newList.add(s);}return newList;}   A new List is created. A for loop is used to iterate throw the input List. An if condition is used to check if the new List has each element in the input List and if not, it is added to the new List.   Using a Set The following code snippet demonstrates this approach: public static List<String> removeDuplicates2(List<String> list){Set<String> set = new HashSet<String>();set.addAll(list);List<String> newList = new ArrayList<String>();newList.addAll(set);return newList;} Here, a Set is created. This is added all the elements in th

Exception handling keywords explained

I know many of you are confused between the difference between throw and throws or would like to know when a finally statement should be used or have some other questions related to Java’s exception handling mechanism. So, in this blog post, I’m going to try and explain each keyword used in Java’s exception handling mechanism. Try The try keyword is used to specify the code that you want to monitor for exceptions. Code should be enclosed within curly brackets i.e. {} after the try keyword. It is known as the try block. Catch Immediately following the try block, you need to specify a catch clause . The catch block is the exception handler code i.e. code that can process the exception.  In the catch block, you need to specify the exception type that you wish to catch and the code that you want to be executed when an error occurs. Finally When an exception is thrown, the normal flow of execution is altered and so some code may be skipped. However, sometimes there is some code that we