Java Tutorial | Groovy Tutorial | Java Interivew Questions | Automation Testing | data structures and algorithms in java tutorial

Monday, 19 June 2017

Java- How hash map works in java or How get() and put() method works internally

Hash Map in Java- Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map interface. it store value in key, value pair format. HashMap is known as HashMap because one ot it's technique i.e hashing.

HashMap
HashMap Example-
import java.util.*;class TestCollection13{
public static void main(String args[]){
 HashMap<Integer,String> hm=new HashMap<Integer, String>();  //line 4
hm.put(“ajay”,123456789);  //line 5
hm.put(“abhishek”,987654321);//line 6
hm.put(“abhinav”,234156748);//line 7
for(Map.Entry m:hm.entrySet()){
            System.out.println(m.getKey()+" "+m.getValue());
        }
    }
}  
Internal Implementation of HashMap-
Hashing- Hashing is a technique which convert large string into fixed length value it is alpha numeric value.
Example-
public class HelloWorld{
    public static void main(String []args){
        String s="abc";
        System.out.println(s.hashCode());
    }
}
In object class java has given equals method which says objects that are equal must have the same hash code within a running process here hashcode of string abc is 96354 this value might be different in your system.
To learn how to override equals and hascode method in java Click Here

If you check the above diagram HashMap internally implements hashtable and each index of and hastable has it’s own linked list implementation because there is a possibility object class hashcode method may return duplicate hashcode.

HashMap has an inner class Entry, which looks like this:

static class Entry<K ,V> implements Map.Entry<K ,V>
{
    final K key;
    V value;
    Entry<K ,V> next;
    final int hash;
    //Some code here
}

How put operation work in java- Using above algorithm we will understand how put() method internally work in HashMap.
Before inserting values in the array index there are some check which is performed by java program internally.
  • First of all, key object is checked for null. If key is null, value is stored in table[0] position. Because hash code for null is always 0.
  • Then on next step, a hash value is calculated using key’s hash code by calling its hashCode() method. This hash value is used to calculate index in array for storing Entry object. 
  • Now index for function is called to calculate exact index position for storing the Entry object.
  • Here comes the important concept two object can have same hash code value and these value will store in same array location because of each  index has it’s own linked list implementation. 
Note:-  Java HashMap allows null key, which always goes to index 0 as hash of 'null' is zero.

How get operation work in java:- In get operation we will call get('varun') then we will find hash of the key after that we will calculate index and check in which index value exist we will compare both hashcode and key at particular index once this is verified value will be returned.
Java Hash Map Design Diagram


Hope you have like this blog kindly suggest on the comment box for any other query contact me Here


Read More

Sunday, 18 June 2017

Abstract class in Java

A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).

In project somtimes we don't implement all the methods/interface in subclass we implement only the methods which has logic common for next coming all sub-classes and we will leave remaining methods of interface as abstract as it is because these method logic is specific to individual subclass.


Example- 

interface A {
        void m1();
        void m2();
        }

abstract class B implements A {
    public void m1() {
        System.out.print("B MEHTOD M1 ");
    }
}
class  C extends  B {
    public void m2() {
        System.out.print( "C METHOD M2");
    }
}

class D extends B {
    public void m2() {
        System.out.print("D METHOD M2");
    }
}
Read More

Saturday, 17 June 2017

How to set path in Java

The path is required to be set for using tools such as javac, java etc.
If you are saving the java source file inside the jdk/bin directory, path is not required to be set because all the tools will be available in the current directory.
But If you are having your java file outside the jdk/bin folder, it is necessary to set path of JDK.
There are 2 ways to set java path:
  1. temporary
  2. permanent

1) How to set Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow following steps:
  • Open command prompt
  • Copy the path of jdk/bin directory
  • Write in command prompt: set path=copied_path

Example:

set path=C:\Program Files\Java\jdk1.6.0_23\bin

2) How to set Permanent Path of JDK in Windows
For setting the permanent path of JDK, you need to follow these steps:
  • Go to MyComputer properties -> advanced tab -> environment variables -> new tab of user variable -> write path in variable name -> write path of bin folder in variable value -> ok -> ok -> ok

Example:

  1. Go to Start Menu > Right Click on Computer > Click Properties.
    java path
  2. Click on Advanced Setting > System Properties promt window will appear.
    System Properties
  3. Click on Environment Variables.
    Environment Variables
  4. Click on New button under System variables enter Variable Name as JAVA_HOME and in Varialble value you have to give your jdk path.
    Set Variable
Now your permanent path is set.You can now execute any program of java from any drive.
Read More

Wednesday, 14 June 2017

Multithreading in Java-Thread Class Constructor And Method

Below constructor are used when thread is created by extending from Thread class
  • Thread() - Creates thread with default name Thread, it is called using super() , it executes run method from current object of start() method.
  • Thread(String name) - Creates thread with given name called it via super(name)
Below two constructor are used when thread is created implementing from Runnable interface
  • Thread(Runnable target) - Creates thread with default name Thread<index>, Thread class object is created explicitly using this constructor, it executes run method from the passed argument Runnable object.
  • Thread(Runnable target, String name) - Creates thread with given name.
Thread class important mehtods
  1. public syncronized void start() 
  2. public void run()
  3. public static native void sleep(long millis) throws InterruptedException
Thread Class Important methods 
  • public syncronized void start()
   Causes this thread to begin execution, the java virtual machine calls the run method of this thread. The result is that threads are running concurrently, thre current thread.
 Rule: It is never legal to call start method more than once on a same thread object. In practical a thread may not be restarted once it has completed execution. It leads to exception "java.lang.IllegalThereadStateException"/
  • public void run()
         It is the initial point of custome thread execution.
  • public static native void sleep(long millis) throws IntrupttedException               public static native void sleep(long millis, int nanos) throws IntrupttedException
         Causes the currently executing thread to sleep for the specified number of                              milliseconds plus the specified number of nanosecounds.

Rule #1: The value of millis should not be negative or the value of nanos is should be in the range of 0-999999 else it leads to exception "java.lang.IllegalArgumentException".


Rule #2: InterruptedException is a checked exception so the sleep method caller should handle or report this exception else it leads to CE: unreported exception must be caught or declared to be thrown.

Answer below questions 

Q) Can we call run method directly from main method ?
Yes, we can call run method direclty. if we call it directly, user defined thead in Java Stacks Area is not be created. it is executed in main thread.

Q) How we can create multiple user defined thread in Java Stack Area ?
There are two ways to create more than one user defined thread in Java Stacks Area

  1. Create multiple thread subclass objects and call start method on each thread object.
  2. Create multiple thread subclasses from Thread class, create its object and call start method.
In first aporoch all threads execution execute same run method logic, because all its thread objects are created from same class. This approch is recommended only to execute same logic concurrenlty with different object state.

In secound approch all threads execute run method with different logic, because thread objects are create from different classes. This is the actual approch used in projects to develop multithreading.

Q) Can we override start() method ?
Yes, we can override start method as it is non-final method. Below is the valid code No Compile Time Error and No Runtime Error.


class MyThread extends  Thread {
    public void run() {
        System.out.println("Rum method");
    }
        public void start() {
            System.out.println("Start method");
        }
    }
}
Q) If we override start() method is custome thread created ?
No, custome thread is not created.
Q) Why Thread class developer not declared start() method as final ?
It is project requirement before starting this thread execution if we want to do some validation
and calculation to update current custom thread object state. we should override start
method in subclass with this validation logic and then we should start custom thread.
This is the reason Thread class developer leaving start as non-final method.
Q) How we can start custom thread from overriding method ?
We must place super.start() at end of overriding start() method.
Example-

class MyThread extends Thread {
    public void run() {
        System.out.println("run ");
    }
    public void start() {
        System.out.println("start");
    }
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.start();
        System.out.println("main ")
    }
}
Read More

Tuesday, 13 June 2017

Multithreading in Java - Thread Definition

Sequetial execution vs Concurrent execution - Sequential execution means single thread execution it takes more time to complete all method execution. Whereas concurrent execution means multithreaded execution it takes less time to complete all mehtods execution. To have concurrent execution developer must create user defined thread in program.

Definition of Thread - 
  • A thread is an independent sequential flow of execution/path.
  • A thread is a stack created in Java Stack Area.
  • It executes methods in sequence one after one.
Definition of Multithreading -
It is the process of creating multiple threads in JSA for executing multiple tasks concurrently to finish their execution in short time by using Processor ideal time effectively.

When multithreading programming is suitable -
To complete independent multiple tasks execution in short time we should develop multithreading in multithreading bases programming CPU ideal time is utilized effectively.

How can we create user defined thread in JVM?
In JVM user defined thread is created and can start its execution - by creating Thread class object and by calling its method start.

Introduction to run method -
  1. It is initial point of user defined thread execution.
  2. It is actually defined in Runnable interface and is implemented in Thread class.
  3. It is implemented as empty mehtod in Thread class.
  4. To excute out logic in user defined thread we must override run method.
Different ways to create custome threads in java
In java we can create user defined threads in two ways

/* Custom thread extending from Thread */
class MyThread extends Thread {
    public void run() {
        System.out.println("run") 
    }
    
    public static void main(String[] args) {
        System.out.print("main");
        MyThread mt = new MyThread();
        mt.start();
    }
}
/* Custom thread implementing from Runnable EOD */

class MyThread implements Runnable {
    public void run() {
        System.out.println("run") 
    }
    
    public static void main(String[] args) {
        System.out.print("main");
        MyThread mt = new MyThread();
        Thead t1 = new Thread(mt);
        t1.start();
    }
}
In the first approch when we create subclass object, Thread class object is also created by using its no-arg constructor. Them when start method is called using subclass object custom thread is created in Java Stack Area, and its execution is started by executing run() method from subclass based on processor busy.

In the second approch when we create subclass object Thread class object is not created because it is not a subclass of Thread. So to call start method we should create Thread class object explicitly by using Runnable parameter constructor, then using this Thread class object we should call start method. Then custom thread is created in Java Stacks Area, and its execution is started by executing run() mehtod from Runnable interface subclass based on processor busy.

For more Multithreading Concept click Next
Read More

Tuesday, 6 June 2017

Multithreading in java

Hi Guys, Before understanding multithreading let us quickly review multitasking.

Multitasking and types of multitasking -
Executing multiple tasks at a time is called multitasking.
Ex: while typing we can download a file, we can listen to music. It is called multitasking

Multitasking is of two types -
  1. Process based multitasking
  2. Thread based multitasking
Process based multitasking 
Executing multiple tasks simultaneously is called process based multitasking here each task is a separate independent process.

Thread based multitasking
Executing multiple tasks concurrently is called thread based multitasking here each task is a seperate independent part of a single process. That part is called thread.

Advantage of multitasking
it is a process based or thread based multitasking the advantage of multitasking is to imporove the performance of the system be decreasing the response time.

The difference between multitasking and multithreading
Multitasking is a heavy weight because switching between contexts is slow because each process is stored at seperate address 

Multithreading is a light weight because switching between contexts is fast because each thread is stored in same address.

Overview on Java threads
We can consider JVM is also a process, when JVM is created in its Java stacks area by default two threads are created with names

  1. main - to execute Java methods.
  2. garbase collector - to destroy unreferenced objects.
So by default Java is multithreaded programming language.
All methods are executed in main thread in sequence in the order they are called from main method as shown below
Multithreading Object Diagram

For more multithreading concept click Next
Read More

Saturday, 3 June 2017

Java- How To Use A Constructor in Java

A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created. Here are the key differences between a constructor and a method:

A constructor doesn’t have a return type.

The name of the constructor must be the same as the name of the class.

Unlike methods, constructors are not considered members of a class.

A constructor is called automatically when a new instance of an object is created.

Here’s the basic format for coding a constructor:

public ClassName (parameter-list) [throws exception...]
{
    statements...
}

The public keyword indicates that other classes can access the constructor. ClassName must be the same as the name of the class that contains the constructor. You code the parameter list the same way that you code it for a method.

Notice also that a constructor can throw exceptions if it encounters situations that it can’t recover from.

A constructor allows you to provide initial values for class fields when you create the object. Suppose that you have a class named Actor that has fields named firstName and lastName. You can create a constructor for the Actor class:

public Actor(String first, String last)
{
    firstName = first;
    lastName = last;
}
Then you create an instance of the Actor class by calling this constructor:
Actor a = new Actor("Arnold", " Schwarzenegger");
A new Actor object for Arnold Schwarzenegger is created.

Like methods, constructors can be overloaded. In other words, you can provide more than one constructor for a class if each constructor has a unique signature. Here’s another constructor for the Actor class:
public Actor(String first, String last, boolean good)
{
    firstName = first;
    lastName = last;
    goodActor = good;
}

This constructor lets you create an Actor object with information besides the actor’s name:
Actor a = new Actor("Arnold", "Schwarzenegger", false);
If you do not provide a constructor for a class, Java will automatically create a default constructor that has no parameters and doesn’t initialize any fields. This default constructor is called if you specify the new keyword without passing parameters. For example:
Ball b = new Ball(); 
Here, a variable of type Ball is created by using the default constructor for the Ball class.

If you explicitly declare any constructors for a class, Java does not create a default constructor for the class. As a result, if you declare a constructor that accepts parameters and still want to have an empty constructor (with no parameters and no body), you must explicitly declare an empty constructor for the class.
Read More
© 2014 JavaTechWorld. Designed by Bloggertheme9
Powered by Blogger.