Posts

Showing posts with the label Java

Create your own LinkedList in Java

As a Java developer, we need to frequently use the collection framework. Have you ever tried to create your own any of the collection classes in Java? Here we go, we will see how to create our own LinkedList in Java. We will create a very simple class with add and get methods. Also, the LinkedList class of collection framework is doubly LinkedList but we will singly LinkedList. Line 36 to 42, we have created an inner class i.e Node with a generic type T. This class has 2 fields: item field is a generic type that will hold an actual value of LinkedList node. next field is a Node type that holds the address of the next node of the LinkedList. We have also defined a constructor to set value for the item field. In lines 4 and 5, we have created an instance variable of type Node in MyLinkedList class i.e. first and last. The field first will always hold the first node of the LinkedList and the field last will always hold the node of LinkedList. Now the question is, why...

divide by zero in Java

You might be thinking,  divide by zero will throw ArithmeticException. But this is not true for floating point numbers. Divide by zero throws ArithmeticException only when char or integral value are divided by 0. Below two operation throws exception 10/0 'A'/0 If floating point number is divided by 0, output will be Infinity . 10.2/0 -10.3/0 Output: Infinity -Infinity

Data types and Literals in Java

Image
Data types Data types category:   Data types summary: Literals A constant value which can be assigned to variable is called "Literal". Integral Literals All possible value of Integral data type(byte, short, int and long) are called Integral Literals. Default Value: By default every Integral literal is int type. When you assign a value in long data byte and that value is more than 2147483647(Maximum value for int) then compiler will give you error. Ex: long a = 3000000000; Error: The literal 3000000000 of type int is out of range  Even though we have used long data type and value is also within range of long but still compiler gives error because every integral literal is int type. We can resolve this error by specifying long type explicitly. We can specify long type by suffixing l or L . Ex: long a = 3000000000L; Number System: Integral Literal can be represented as Decimal, Octal and Hexadecimal number systems. L...

Identifiers in Java

Image
Any name in Java program is called Identifier. It could be a class name, variable name or method name. Question: Find out list of identifiers in below program- public class App { public static void main(String[] args) { int a = 10; } } Answer:  1. Test 2. main 3. args 4. a Rule: 1. The only allowed characters in Java identifier are:     2. Identifiers can't start with digit. 3.  Java identifiers are case sensitive. Below are 3 different variables- int Number =10; int NumbeR =10; int NUBber =10; 4. There is not length limit for Java identifiers but it is not commanded to take more than 15 length. 5.  Reserved words can't be used as identifier. 6. All predefined Java classes name and interface names can be used as identifier. It is legal but not recommended. We have declared variable names as String and Runnable in below program. It is valid. public class App { public static void main(String[] args) { int String =...

Object Class in Java

Object class is super class of all classes in Java. Every class in Java extends Object class directly or in-directly. There are total 12 methods in Object class. You can call override all non-final, public and protected methods. You can also call all public methods on object of any class(custom or in-built). toString clone equals hashCode notify and notifyAll wait finalize registerNatives getClass

equals() method of Object class in Java

Image
When you compare two object references using == operator, it evaluate to true only when both references refer to same object. public class Person { private Integer id; private String name; public Person(Integer id, String name) { this.id = id; this.name = name; } public static void main(String[] args) { Person p1 = new Person(1, "Prithvi"); Person p2 = p1; Person p3= new Person(1, "Prithvi"); System.out.println(p1==p2); System.out.println(p1==p3); } } Output: true false We have created 3 references of Person class. Object references p1 and p2 both refer to same object so comparison evaluate to true. Comparison of p1 and p3 evaluate to false, even though p3 has same contents as p1 but refer to different object so comparison returns false. Below image explains this - Objects p3 and p1 are meaningfully equal. We must have some way to see their content are same or not. But the question is, How will you compare two different object...

What is difference between Runnable and Thread? What is the best way to create thread?

There are 2 ways of creating thread. First way is by extending Thread class and another is implementing Runnable interface. What are the differences between these 2 ways. This is frequently asked question in Java interviews. 1. Multiple Inheritance: Thread is a class. Once you extend Thread class, you can not extend other class because Java does not support multiple inheritance. Whereas Runnable is interface so you can extend other class while implementing Runnable interface. 2. Worker and Job: Thread is worker which works on job(Runnable). It is always a good practice to separate code of worker and job. If we create thread by extending Thread class, It will combine code of worker and job. So it is good practice to implement Runnable interface. Object of this class(Job) will be passed to thread constructor(Worker). The thread instance will call run method on class which implements Runnable. This is how we can separate Worker and its Job. 3. extends means adding new Feature: Whe...

Clone method of Object class in Java

Image
Let me ask you a question. How will you make copy of one object and assign to another reference variable? If you think, you can use assignment operator(=) then you are wrong. Assignment operator does not copy object to another object instead new reference variable points to same object in memory. Person obj1 = new Person(); Person obj2 = obj1; Here both variable obj1 and obj2 points to same object to memory. Two varibles referring to same object in memory. If you change something in obj1 that will be reflected in obj2 and vice versa Below image explains this - You can use clone method to make copy of object. Here is code snippet of clone method from object class. protected native Object clone() throws CloneNotSupportedException; clone is native:  The clone method is native in Object class. This method works at memory level and create copy of object. It means we don't need to create new object in code manually to make copy. Below way of writing clone method is wr...

toString method of Object class in Java

This is very important method. I have seen in multiple code review where developers call toString method to print content of object. Actually you don't have to call this method explicitly. This method is automatically called when you print object of any class. What I meant for "content of object" is values of instance variable or any meaningful human readable information of an object.  But toString method of object class does not return human readable information about object. It returns name of the class and hexadecimal representation of hashcode.  This information is useless for human. This information does not say anything about an object.  Below is code snippet of toString method from Object class- public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } Let's see how toString method print information of an object by below example - public class Person { private Integer id; private String nam...

Constructor In Java

Constructor is block of code which executed when object of class is created. Constructor is responsible for creating new object. It assigns initial values of object. Syntax of constructor is almost same as method. Constructor has below rule - Name of constructors must be same as class name. Constructors must not have return type. Constructor can not return a value. Types Of Constructor 1. Default Constructor: A constructor without parameters is called as default constructor. When we don't define any constructor in our class then compiler will add default constructor. It means a class will always has constructor either we explicitly define or compiler will add one. Example of default constructor- public class Person { public Person() { System.out.println("In Default Constructor of Person"); } public static void main(String[] args) { Person person = new Person(); } } Output: In Default Constructor of Person If we remove default cons...

Java's Magic: Bytecode

Image
The most powerful feature of java is platform independent.Platform independent is COMPILE ONCE, RUN ANYWHERE. It means you can compile your source code on one platform and run on any platform. The magic behind this feature is Bytecode. When you compile your code using javac command, compiler doesn't generate machine/platform specific code. It generates .class file. This .class file bytecode. You can run this .class file on any platform.

enums in Java

We can use enum to define a group of named constants. By using enum we can define our own data types. enum concept introduced in 1.5v. Java's enum are more powerful than enum in other languages. Declaration enum enum concept is internally implemented using class concept. Syntax of enum declaration are almost same as class declaration. enum keyword is used for declaring enums. //EXAMPLE CODE-1 public enum Month{ JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC; } In above example, We have declared Month as enum and JAN, FEB, MAR ...DEC are constants of type Month. A enum can have instance variables, method and constructor. Instance variables, method and constructor must be declared after enum constants declaration. If there are parameterised constructors in enum then enum constant must have these parameters. //EXAMPLE CODE-2 public enum Day { SUN("Sunday"), MON("Monday"), TUE("Tuesday"), WED("Wednesday"), THU(...

Package

This is encapsulation mechanism to group related classes and interfaces in single module. The main purposes of package are –           To resolved naming conflict           To improve modularity of program           To provide security by preventing access of classes and interface to outside of package  Rules –           If package is available in java file then first non-comment code should be package.           There can be only one package name in java file. Note – As java naming convention, package name should be reverse of internet domain name. eg -  com.icicibank.loan housingloan You can create class which is not in package. But it is always recommended that you should declare a class in package.

Java Interview Questions

What is difference between Hashtable and HashMap classes in Java ? What is CuncurrentMap? What is Fail fast iterator and fail safe iterator? How Fail fast iterator knows that the internal structure of collection is modified? What is priority query? What is annotations? how to create custom annotation and use it? What is dependency injection? What is use of Junit? What is AOP? Explain its terminology? What is design pattern & why should we use them? Explain different type of design patterns. What is file in Java? What is difference between OOP and AOP? What is difference between  application server and web server? What is difference between SOAP and RESTful web services? What are implicit objects of JSP? How to integrate Hibernate with Spring? What is difference between logical and physical transaction? Explain Memory management in Java. Explain memory management of String in java. What is wait() and notify() methods? Explain JVM architecture? What is St...

What is difference between HashMap and Hashtable classs

Synchronization & Thread Safe - All methods in Hashtable are synchronized and thread safe whereas methods in HashMap are not synchronized and it is not thread safe. HashMap is more faster than Hashtable because its methods are not synchronized. Null Key & Null Value - HashMap allows one null key and any number of null values whereas null key and null value is not allowed in Hashtable. Hashtable's put method will throw NullPointerException if null is used as key or value Iterating the values - HashMap uses Iterator to iterate over the values whereas Hashtable uses Enumerator. Super class & Lagacy - Hashtable is subclass of Dictionary class which is now obsolete in JDK1.7. HashMap is sub class of AbstractMap Note :-  It is better of externally synchronize a HashMap or Using concurrentMap implementation. (i.e. ConcurrentHashMap)