Posts

Showing posts with the label java-tutorial

Java instanceof Operator Example

Image
The instanceof operator also known as type comparison operator, and it's very useful to compare the type of object. It compares an object to a specified type. One can use instanceof operator to test if an object is an instance of class,sub-class or interface, just like checking of serializable interface after implementation of serializable. In this post, I am going to show you few examples of how to use instanceof operator in your code. Example 1: We know that, String class by default implement the Serializable interface,lets check this. package com.javamakeuse.poc.bd; import java.io.Serializable; public class InstanceOfOp { public static void main(String[] args) { String str = "implemented serializable"; if (str instanceof Serializable) { System.out.println("String by default implement Serializable"); } } } Output: String by default implement Serializable Example 2: package com.javamakeuse.poc.bd; public class InstanceOfOp { public s...

Dynamic Method Dispatch in Java

Image
One of the important concept of core java inheritance module. Dynamic method dispatch is also known as late binding or runtime polymorphism. In this tutorial, I am going to explain what is dynamic method dispatch and how to use them in practically with simple example. This topic is very popular in java,j2ee interview like why String is immutable in java What is Dynamic method dispatch? Dynamic method dispatch, it's very clear from the statement itself dynamic(runtime) method dispatch(which method to call), it determines which methods needs to be called at runtime and it's a part of inheritance relationship, that's it nothing more than that just determines which method needs to be called at runtime . Example, package com.javamakeuse.dmd; public class IPhone { public String getSpecifications() { return "135g, 2MP, 3.5 Inc"; } public static void main(String[] args) { IPhone iPhone3 = new IPhone3(); IPhone iPhone4 = new IPhone4(); printIPhoneS...

Hello World Program in Java

Image
To learn any programming language we start with Hello World program. After completion of my Hibernate tutorial series now planing to start series of java tutorial, and in this tutorial, I will show you how to create your first hello world program in java. I am using eclipse to create this basic program, you just need to follow the below steps. Open your IDE Go to File->New->Java Project(provide the project name) Right click on created project->New->Class(give the name of class) It will open an editor, where you can write your code. Below is the complete Hello World program. HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!!!"); } } To run, right click on the class and select run as java application or click on run symbol on the menu bar. Here , I have explained each part of the main method.

Java Anonymous Class Tutorial

Image
One of the important feature of java, most of the developer are avoid to using the anonymous classes and for beginners, It's difficult to understand the concept of anonymous class and their use at-least for me when I was doing the java classes. What is Anonymous class A class having no name is known as Anonymous class, Anonymous classes are expression, which means one can declare and instantiate a class at the same time. When to use Anonymous class? Use to keep you code short and simple. Use them, if you want to use them only once. For quick and dirty task. How to use Anonymous class searchBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // do search. } }); Example package com.javamakeuse.anonymous; public class AnonymousExample { abstract class Flyable { abstract void fly(); } public static void main(String[] args) { AnonymousExample an = new AnonymousExample(); Flyable flyableObj = an.new Flyab...

How to install JDK in Ubuntu

Image
In this tutorial, I am going to show you how to install Java on Linux machine. To learn Java of-course first thing you need to install Jdk, so lets start the installation. Steps to install JDK on Linux Step 1. Go to the Oracle official site ( http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html ) accept the license and download the appropriate product from the above link. Step 2. Extract the tar file downloaded from the above link, below is the syntax to extract the tar file tar -xzf jdk-8u65-linux-x64.tar.gz Step 3. Set the JAVA_HOME environment variable using below command type the below syntax on terminal. export JAVA_HOME=/home/ubuntu/Softwares/jdk1.8.0_65(installed jdk path) export PATH=${PATH}:${JAVA_HOME}/bin or Open .bashrc and .profile file and set the JAVA_HOME with below commands on terminal- i. Type vi ~/.bashrc it will open a vi editor, of-course you can open in any editor like gedit,nano etc. ii. Place this export J...

Java new features

Image
In this post, I am sharing the popular java features by their released versions. This will help you to revised the latest features of JDK by their version and started with latest released. Java 8 Features Lambda Expressions Default Methods Type Annotations Streams Date Time API Nashhorn JavaScript Engine Performance Improvement for HashMaps with Key Collisions Removal of PermGen. TLS 1.2 Java 7 Features String in switch Try-with-resources statement Underscores in numeric literals Binary literals Multiple exception catching Improved Type Inference for Generic Instance Creation SafeVarargs NIO 2.0 Here is detail example of java 7 features. Popular Java 6 Features JDBC 4.0 Java Compiler API Kerberos and LDAP support. JAXB 2.0 Common Annotations XML Binding Java 5 Features Annotations Autoboxing/Unboxing Enhanced for Loop Generics Typesafe Enums Static Import Varargs Most of the time interviewer, asked you to list the new features of JDK, the above points ...

ClassNotFoundException vs NoClassDefFoundError

Image
This is again one of the popular java interview question, like which collections is better to store 10 millions of record between ArrayList and LinkedList , and almost every interviewer ask this question. Although, I have already listed Top 20 core java interview questions  and in this post going to list the key differences between ClassNotFoundException and NoClassDefFoundError both are sub class of java.lang.Throwable. ClassNotFoundException - This exception is thrown when an application tries to load a class through its String name using any of the below methods, and no class definition is found with specified name. forName("class name"); findSystemClass("class name"); loadClass("class name"); The ClassNotFoundException is a checked exception, below is the example to generate the ClassNotFoundException, you can read more about Checked Exception public static void main(String[] args) throws ClassNotFoundException { Class.forName("a...

How to Create Custom Exception in java

Image
In this tutorial, I will show you how to create custom exception. Although I have already posted about Exception in my previous Exception Tutorial post. And we all know Exception is very important and actively used feature in daily programming practice. Sometimes interviewer also asked you about custom exception in java, and ask to write an example of custom exception, so this tutorial is important in both purpose to use or to be in java interview, this question is popular in java interview as like as Why String is immutable in java . Although I have already posted Top 20 Exception Handling interview questions and 15 core java written interview questions How to create custom Exception You can create custom exception by either extending - java.lang.Exception ( Checked Exception ) java.lang.RuntimeException ( Unchecked Exception ) But before creating any custom exception think twice, Is it really required custom exception, are built in exceptions will not helping anymore f...

Error in java example

Image
In java exception is very powerful feature and we have already seen about the Exception in our Exception Tutorial . And in this tutorial, I will try to explain about one of the sub class of Exception called java.lang.Error, and after completion of this tutorial, you will be able to answer what is Error in java? and few examples of Error sub-classes. What is java.lang.Error in java? The java.lang.Error is another sub class of java.lang.Throwable class, which indicates serious problems and application cannot recover from this Error unlike Checked Exceptions . And also a better design of Exception handling is to not handling the Error because handling of error will does not make any sense, so no need to catch or throw  Error or any sub class of Error. The java.lang.Error including it's sub classes also know as UN-checked exception like Runtime Exceptions The common reason of occurring this error in your application is possible that due no space in stack and trying to alloca...

Java Runtime Exception Tutorial

Image
In my previous post we have seen, what is Checked Exception and in this post, I shall try to explain what is Runtime exception and list few runtime exceptions. Runtime exception is also known as un-checked exception, so un-checked exception is also very popular topic in core java interview like How to balance the parenthesis and java program to find missing number . What is Runtime Exception ? The Runtime exceptions are basically a bug in your code. It's developer's fault/mistake, you can easily prevent the run time exception in your code no rocket science is required you just need to do code in a smart way. We will see later in this tutorial "How to prevent the runtime exception" , but before that, I strongly suggest you to must read What is Exception in java The java.lang.RuntimeException is a sub-class of java.lang.Exception class and all the sub-class of java.lang.RuntimeException is treated as runtime exception and application cannot recover from these...

Checked Exception in java

Image
In this tutorial, I shall try to explain What is Checked Exception? and Example using Checked Exception . This topic is also  popular in java interview question for freshers as well as below 5 years of experienced profile like Why String is immutable and What is Serialization in java What is Checked Exception? Checked Exceptions are those exception which are forced by java compiler to catch it or throws it otherwise program will not compile. All exceptions are checked exceptions, except for the sub classes of java.lang.Error and java.lang.Runtime class. You can read more about What is Exception in java and Exception Hierarchy from my previous post. Example of Checked Exception - Trying to reading a file from your hard disk, but somehow file is not in placed, than you will get java.io.FileNotFoundException , That's why compiler forced you to catch the FileNotFoundException or throws it otherwise program will not compile. Code without handling Checked Exception - pub...

Java Exception Tutorial

Image
After completion of BlockingQueue Tutorial and Hibernate Tutorial now starting with very popular topic of core java called Exception. And in this tutorial, I will try to explain what is Exception and What are the different types of Exceptions in java including your own custom exception, and how to use them. What is Exception in java? An exception is an exceptional event, which occurs during the execution of program and interrupt the normal flow of the running program. Like celebrating new year night with dancing on a floor and suddenly audio woofer stopped working. As soon as an error occurs in your method, it' will create an object of Exception class and throwing that exception to the Run-time system. The Run-time system, who will find the appropriate handler(block of code to handle the exception) for the exception from the call stack of the method. The Run-time system will scan all the method in call stack until an appropriate handler is found, once appropriate except...

Java DelayQueue Tutorial

Image
In our previous tutorial, we have learned What is SynchronousQueue and How to use Synchronous Queue here . In this tutorial, I will try to explain you What is DelayQueue? and How to use DelayQueue with solving producer and consumer problem using java.util.concurrent.DelayQueue . What is DelayQueue? The java.util.concurrent.DelayQueue is an implementation class of BlockingQueue, so before reading the DelayQueue, I strongly suggest you to read about BlockingQueue from any source, we have also posted tutorial on BlockingQueue, so you can follow that tutorial too BlockingQueue Tutorial . The DelayQueue is an un-bounded BlockingQueue for delayed elements unlike ArrayBlockingQueue . You can put element into the queue, but element can be taken from the queue only if the delay has expired for the element. It works on First-In-First-Out data structure. It also does not allow null element. If no delay expired for the elements and trying to accessing through poll() method, it will return...

SynchronousQueue Tutorial

Image
In my previous post, I have posted about LinkedBlockingQueue in java. And in this tutorial, I will try to explain you about SynchronousQueue. After completion of this tutorial, you will be able to answer these questions What is SynchronousQueue? How to use SynchronousQueue and able to solve a producer consumer problem using SynchronousQueue. What is SynchronousQueue? The SynchronousQueue is an implementation of BlockingQueue interface, which extends Queue and Queue extends Collection interface. The SynchronousQueue is totally different implementation of BlockingQueue unlike other implementations of BlockingQueue. The SynchronousQueue was introduced in java 1.5 under java.util.concurrency package, it is a special queue, it has no capacity to hold any element into the queue, even not a single element, calling peek() method will return null, because it has no capacity to hold any element into the queue.  The queue where each insert operation must wait for a corresponding re...

What are the new features in java 7

Image
Still popular java interview question, yesterday I was appeared in one of the world's largest investment banking company's interview and interviewer asked me to list down the new features of java 7 I thought it was java 8 but when, I re-confirm then interviewer replied yes you have to list down the new features of java7. So, I decided to post a topic on new features of java 7, In this post I am going to list down all the new features of java7 with code example. The java 7 features are still on demand not only in real time use but in interview also like java program to balanced parentheses Below are the list of new features of java 7 String in switch Try-with-resources statement Underscores in numeric literals Binary literals Multiple exception catching Improved Type Inference for Generic Instance Creation SafeVarargs String in switch: Now you can use Strings in switch statements. public static void stringInSwitch(String months) { final String JAN = "...

Explain Different parts of the main() method in java

Image
Very interesting java interview question specially for freshers, here is 20 core java interview question for freshers . Sometimes interviewer asked you a very basic interview question to check your concept regarding java API. And start with question like what is static in java? , why main is public static etc. and sometimes to explain the different parts of main method. So in this post, I am going to explain the very simple steps and you just need to at least remember these points. Nowadays, only theory is not enough to crack an interview you have to also solve some logical question like How to balanced the parentheses?   with o(n) time and space complexity, program to remove duplicate characters from a String , Java program to find missing number etc. These types of question must needs solve. Explain different parts of the main() method in java I would suggest, before answering this question you should write a simple signature of the main method, and than pick one by one...

How to convert char to ascii value in java

Sometimes we may need to convert a Character or String to ASCII value or vice versa, So here I am going to show you a simple example to convert Character to ASCII and ASCII to Character . Also converting String to byte array and byte array to int array. In our previous post we have balanced parenthesis(very popular java coding interview) with o(n) time complexity here . How to convert Character to ASCII private static int charToASCII(char ch) { return (int) ch; } How to convert ASCII to Character private static char asciiToChar(int ascii) { return (char) ascii; } How to convert String to ASCII byte Array private static byte[] stringToByteArray(String value) { return value.getBytes(StandardCharsets.US_ASCII); } How to convert String to byte Array to int Array private static int[] byteArrayToIntArray(byte[] byteArray) { int[] intArray = new int[byteArray.length]; for (int i = 0; i < byteArray.length; i++) { intArray[i] = byteArray[i]; } return intAr...

What is LinkedHashMap in java with example

In this post we are going to show you, What is LinkedHashMap? When to use LinkedHashMap? and How to use LinkedHashMap? . In our previous post we have already seen an example of HashMap and Hashtable with running sample java program. What is LinkedHashMap? Well LinkedHashMap is an implementation of java.util.Map interface and also extends HashMap class. The LinkedHashMap allows all the optional operations of Map interface and behaves same as HashMap. The implementation of LinkedHashMap is based on doubly-linked-list, So the insertion order is maintained in LinkedHashMap unlike HashMap. The LinkedHashMap allows null as a key and any number of null values unlike Hashtable. It provides basic operations(add, contains and remove) performance on constant time. Of course, it takes more memory space as compared to HashMap, due to it's doubly-linked-list implementation. Iteration on LinkedHashMap provides time proportional to the size of the map. For performance point of view Link...

How to sort HashMap in java example

So we have learned how to use HashMap and Hashtable now it's time to process them, I mean, although we have already seen How many ways to iterate HashMap here . In this post, I am going to show you how to sort a map. Sometimes we required to sort a map, of course based on different requirements you may need to sort HashMap or Hashtable based on key or values. But here I will show you a simple java program to sort map based on their keys. Of course TreeMap is Sorted Map and LinkedHashMap is Ordered Map, but yes they both have high payee Map implementation regarding space. Note: HashMap and Hashtable both are UN-Sorted and UN-Ordered Map implementation. Java Program to Sort HashMap or Hashtable package com.javamakeuse.poc; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.TreeMap; public class HashTableExample { public static void main(String[] args) { HashMap<Character, S...

What is Hashtable in java with code example

Hashtable is again an implementation of java.util.Map interface, In our previous post we have seen an example of HashMap implementation . In this post we are going to show you a very simple example of Hashtable What is Hashtable Hashtable is an implementation of java.util.Map interface and also extends Dictionary class. It is again works on Hashing principal and allows you to store the elements in the form of key and value pair. Hashtable is of course roughly equivalent to HashMap except that Hashtable is synchronized and does not allow null as a key or value. To store the element into the Hashtable uses put() method and to retrieve back the element from the Hashtable get() method is used. To make this put and get method works successfully, the key used inside the Hashtable must implement the hashCode() and equals() method of java.lang.Object class. See why String is best key for HashMap or Hashtable here Of course key used in Hashtable or HashMap must be unique otherwise v...