Sunday, March 13, 2022

Shallow and deep cloning

Shallow Copy:

When we do a copy of some entity to create two or more than two entities such that changes in one entity are reflected in the other entities as well, then we can say we have done a shallow copy. In shallow copy, new memory allocation never happens for the other entities, and the only reference is copied to the other entities

Deep Copy:

When we do a copy of some entity to create two or more than two entities such that changes in one entity are not reflected in the other entities, then we can say we have done a deep copy. In the deep copy, a new memory allocation happens for the other entities, and reference is not copied to the other entities. Each entity has its own independent reference. 

How will you print numbers from 1 to 100 without using loop?

Solution: Use recursive to print numbers without loop.

public class PrintNumbers {

public static void main(String args[]) {

printnumbers(5);

}

public static void printnumbers(int n) {

if(n>0) {

System.out.println(n);

printnumbers(n-1);

}

}

}

Saturday, March 12, 2022

Check if string is a palindrome after removing one character.

public class Program2 {

    public static boolean makePalindrome(String mjono) {

        StringBuilder sb = new StringBuilder(mjono);

        for (int i = 0; i < mjono.length(); i++) {

            sb.deleteCharAt(i);

            if(isPalindrome(sb.toString())){

                return true;

            } else {

                sb.insert(i, mjono.charAt(i));

            }

        }

        return false;

    }

    private static boolean isPalindrome(String str) {

        return str.equals(new StringBuilder(str).reverse().toString());

    }

    public static void main(String[] args) {

        System.out.println(makePalindrome("ABCBXA"));

        System.out.println(makePalindrome("ABCBAX"));

        System.out.println(makePalindrome("ABCXBA"));

        System.out.println(makePalindrome("ABCDE"));

        System.out.println(makePalindrome("BAAAAC"));

    }

}

Friday, March 11, 2022

If we try to insert duplicate values in a Set, What will happen?

 Just it wont add, It wont give compile time error and run time error.

Two arrays common numbers with minimum complexity

public void findCommon(in[] a, int[] b){

    Set<Integer> s = new HashSet(Arrays.stream(a).boxed().collect(Collectors.toList()));

    s.retainAll(Arrays.stream(b).boxed().collect(Collectors.toList()))

   System.out.println("Find common number:"+s)

}


Monday, April 27, 2015

write a program for charector count..

import java.util.HashMap;
import java.util.Map;

public class Test123 {

    public static void main(String args[]) {
        String s = "ravikiran ravikiran ravikiran";
        Map<Character, Integer> charf = new HashMap<Character, Integer>();
        if (s != null) {
            for (Character c : s.toCharArray()) {
              if(c.isSpaceChar(c)){
                continue;
              }
                Integer count = charf.get(c);
                int newCount = (count == null ? 1 : count + 1);
                charf.put(c, newCount);
            }
        }

        for (Map.Entry<Character, Integer> entry : charf.entrySet()) {
            System.out.println(entry.getKey() + "/" + entry.getValue());
        }

    }

}

Tuesday, December 2, 2014

Write a program for deadlock


class Resource1 extends Thread {
  public void run() {
    System.out.println("Resource1" + getName());
    synchronized (Resource1.class) {
      try {
        Thread.sleep(10);
      }
      catch (InterruptedException e) {
        e.printStackTrace();
      }
      synchronized (Resource2.class) {
      }
    }
  }
}
class Resource2 extends Thread {
  public void run() {
    System.out.println("Resource2" + getName());
    synchronized (Resource2.class) {
      try {
        Thread.sleep(10);
      }
      catch (InterruptedException e) {
        e.printStackTrace();
      }
      synchronized (Resource1.class) {
      }
    }
  }
}
public class Deadlock_example {
  public static void main(String[] args) {
    Resource1 r1 = new Resource1();
    Resource2 r2 = new Resource2();
    r1.start();
    r2.start();
  }
}

Count the number of chars in string..

public class Countnumber {
  public static void main(String args[]){
    String s = "aabbbccccdddddeeeeeeffffffffff";
    Map<Character, Integer> m =new HashMap<Character, Integer>();
    char c;
   
    int count = 1;
    for(int i= 0;i<s.length();i++){
     
      c = s.charAt(i);
      if(m.containsKey(c)){
        count = (int) m.get(c);
        count++;
      }else{
        count = 1;
      }
      m.put(c, count);
    }
    Iterator it = m.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
    }
    for(Map.Entry<Character, Integer> entry : m.entrySet()){
      System.out.println(entry.getKey() + " = " + entry.getValue());
    }
  }
}
O/p  ::
f = 10
d = 5
e = 6
b = 3
c = 4
a = 2

Green Vs Native Threads

Green threads Will function on systems that don't support OS level threads.

Another advantage of native threads is that multiple processes would execute in parallel in a multi-core machine.
On the other hand, green threads are executed on a single core the entire time and it is the VM that gives a multi-threading notion.
So actually there is only singe executing in case of green threads.

Native threads uses OS scheduling algorithm. Modern day OSes support pre-emptive scheduling.
Green threads can use any kind of scheduling algorithm

Native threads usually have complicated synchronization and resource sharing. Multiple processes would require kernel level locks for synchronization.
Synchronizations are pretty easier in case of green threads.

For purely sequential code, green threads are slightly faster than native threads.

For multithreaded code that involves frequent synchronization, green threads are likely to be faster than native threads.
Methods such as Object.notify() are much faster for green threads as compared to native threads.

Green threads Cannot support multi-processor machines

Green threads are generally a bit more "lightweight" than native threads

Green threads are scales to large numbers of threads than native threads.

Future Methods

A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time. 

To define a future method, simply annotate it with the future annotation, as follows.
global class FutureClass
{
    @future
    public static void myFutureMethod()
    {   
         // Perform some operations
    }
}

The difference between the Runnable and Callable interfaces in Java..

  • A Callable needs to implement call() method while a Runnable needs to implement run() method.
  • A Callable can return a value but a Runnable cannot.
  • A Callable can throw checked exception but a Runnable cannot.
  • A Callable can be used with ExecutorService#invokeXXX methods but a Runnable cannot be.
    public interface Runnable {
        void run();
    }
    
    public interface Callable<V> {
        V call() throws Exception;
    }
     
    NOTE : Inside your class you can make the calls to Callable and Runnable
     on a single thread executor, making this mechanism similar to a serial 
    dispatch queue. So as long as the caller calls your Runnable wrapped 
    methods the calling thread will execute really fast without blocking. As
     soon as it calls a Callable wrapped in Future method it will have to 
    block till all the other queued items are executed. Only then the method
     will return with values. This is a synchronization mechanism. 

Monday, October 20, 2014

Hashing :How hash map works in java or How get() method works internally


How Hashmap works in Java

HashMap works on the principle of Hashing .  To understand Hashing , we should understand the three terms first   i.e  Hash Function , Hash Value and Bucket .

What is Hash Function , Hash Value  and Bucket ?

hashCode() function  which returns an integer value is the Hash function. The important point to note that ,  this method is present in Object class ( Mother of all class ) .

This is the code for the hash function(also known as hashCode method) in Object Class :

    public native int hashCode();

The most important point to note from the above line :  hashCode method return  int value .
So the Hash value is the int value returned by the hash function .


    So summarize the terms in the diagram below :
                  


how hash  map works in java









What is bucket ?
A bucket is used to store key value pairs . A bucket can have multiple key-value pairs . In hash map, bucket used simple linked list to store objects .

After understanding the terms we are ready to move next step , How hash map works in java or How get() works internally in java .



Code inside Java Api (HashMap class internal implementation) for HashMap get(Obejct key) method

1.  Public  V get(Object key)
   {
2.     if (key ==null)
3.     //Some code
    
4.     int hash = hash(key.hashCode());
    
5.     // if key found in hash table then  return value
6.     //    else return null
   }

Hash map works on the principle of hashing 

HashMap get(Key k) method calls hashCode method on the key object and applies returned hashValue to its own static hash function to find a bucket location(backing array) where keys and values are stored in form of a nested class called Entry (Map.Entry) . So you have concluded that from the previous line that Both key and value is stored in the bucket as a form of  Entry object . So thinking that Only value is stored  in the bucket is not correct and will not give a good impression on the interviewer .

* Whenever we call get( Key k )  method on the HashMap object . First it checks that whether key is null or not .  Note that there can only be one null key in HashMap .  

If key is null , then Null keys always map to hash 0, thus index 0.

If key is not null then , it will call hashfunction on the key object , see line 4 in above method i.e. key.hashCode()  ,so after key.hashCode() returns hashValue , line 4 looks like

4.                int hash = hash(hashValue)

 , and now ,it applies returned hashValue into its own hashing function .

We might wonder why we are calculating the hashvalue again using hash(hashValue). Answer is ,It defends against poor quality hash functions.

Now step 4 final  hashvalue is used to find the bucket location at which the Entry object is stored . Entry object stores in the bucket like this (hash,key,value,bucketindex) .  

Interviewer:    What if  when two different keys have the same hashcode ?

Solution, equals() method comes to rescue.Here candidate gets puzzled. Since bucket is one and we have two objects with the same hashcode .Candidate usually forgets that bucket is a simple linked list.

The bucket is the linked list effectively . Its not a LinkedList as in a java.util.LinkedList - It's a separate (simpler) implementation just for the map .

So we traverse through linked list , comparing keys in each entries using keys.equals() until it return true.  Then the corresponding entry object Value is returned .


how hashmap works internally in java







One of  our readers Jammy  asked a very good  question 

When the functions 'equals' traverses through the linked list does it traverses from start to end one by one...in other words brute method. Or the linked list is sorted based on key and then it traverses?

Answer is when an element is added/retrieved, same procedure follows:


a. Using key.hashCode() [ see above step 4],determine initial hashvalue for the key

b. Pass intial hashvalue as hashValue  in    hash(hashValue) function, to calculate the final hashvalue.

c. Final hash value is then passed as a first parameter in the indexFor(int ,int )method .
    The second parameter is length which is a constant in HashMap Java Api , represented by                             DEFAULT_INITIAL_CAPACITY

    The default  value of DEFAULT_INITIAL_CAPACITY is 16 in HashMap Java Api .

 indexFor(int,int) method  returns the first entry in the appropriate bucket. The linked list in the bucket is then iterated over - (the end is found and the element is added or the key is matched and the value is returned )


Explanation about indexFor(int,int) is below :

/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
    return h & (length-1);
}


The above function indexFor() works because Java HashMaps always have a capacity, i.e. number of buckets, as a power of 2.
 Let's work with a capacity of 256,which is 0x100, but it could work with any power of 2. Subtracting 1
from a power of 2 yields the exact bit mask needed to bitwise-and with the hash to get the proper bucket index, of range 0 to length - 1.
256 - 1 = 255
0x100 - 0x1 = 0xFF
E.g. a hash of 257 (0x101) gets bitwise-anded with 0xFF to yield a bucket number of 1.



Interviewer:    What if  when two  keys are same and have the same hashcode ?
If key needs to be inserted and already inserted hashkey's hashcodes are same, and keys are also same(via reference or using equals() method)  then override the previous key value pair with the current key value pair.

The other important point to note is that in Map ,Any class(String etc.) can serve as a key if and only if it overrides the equals() and hashCode() method .


Interviewer:  How will you measure the performance of HashMap?

According to Oracle Java docs,  

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. 

The capacity is the number of buckets in the hash table( HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.), and the initial capacity is simply the capacity at the time the hash table is created. 


The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

In HashMap class, the default value of load factor is (.75) .

Find the Missing Number 1 to n

You are given a list of n-1 integers and these integers are in the range of 1 to n. There are no duplicates in list. One of the integers is missing in the list. Write an efficient code to find the missing integer.

Example:
I/P    [1, 2, 4, ,6, 3, 7, 8]
O/P    5


METHOD 1(Use sum formula)

Algorithm:
1. Get the sum of numbers 
       total = n*(n+1)/2
2  Subtract all the numbers from sum and
   you will get the missing number.
 
Example::
 
total = n*(n+1)/2 = 8*9/2 = 36
sum = 31
 
Missing number = total - sum =  36-31 = 5

Count of repetable words from a string

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class test {
public static void main(String[] args)
{
String s = "i an Apples is an an Apple";

String ar[] = s.split(" ");
List<String> valuesList = Arrays.asList(ar);

Map<String, Integer> unique = new HashMap<String, Integer>();

for (String string : valuesList) {
if(unique.get(string) == null)
unique.put(string, 1);
else
unique.put(string, unique.get(string) + 1);
}
System.out.println("Values = " + unique);

}

Monday, June 30, 2014

Can you serialize static fields of a class?

Since static fields are not part of object state, 
they are part of class, serialization ignores the static fields.

Friday, June 27, 2014

what happens when visibility of public method is reduced in subclass (public to private)?

public class Test1 {
  public static void main(String[] args) {
  }
   public void add(){
   }
}

class Test2 extends Test1 {
    private void add(){
    }
}

Compile time error :

Cannot reduce the visibility of the inherited method from Test1

String literal pool

There are slight differences between the various methods of creating a String object. String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals/objects to increase performance and decrease memory overhead. To cut down the number of String objects created, JVM maintains a special memory called “String literal pool” or “String constant pool”.
Each time your code creates a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string does not exist in the pool, a new String object is created and placed in the pool. JVM keeps at most one object of any String in this pool. String literals always refer to an object in the string pool.
For example,

Direct Method of creating String object

1
String s1 = "iByteCode";
How this works?
  • JVM checks the String constant pool first and if the string does not exist, it creates a new String object “iByteCode” and a reference is maintained in the pool. The variable ‘s1′ also refers the same object.
  • This statement creates one String object “iByteCode”.
  • Now, let’s see what happens if we have a statement like this:
  • 1
    String s2 = "iByteCode";
  • JVM checks the String constant pool first and since the string already exists, a reference to the pooled instance is returned to s2.
  • This statement does not create any String object in the memory and ‘s2′ refers the same object as ‘s1′.
  • To check this, you can compare two String references using == operator to check whether two references are referring to the same String object in the memory.
1
2
3
4
String s1 = "iByteCode";
String s2 = "iByteCode";
if(s1 == s2)
    System.out.println("s1 and s2 referring to the same object.");
s1 and s2 referring to the same object.


Java can make this optimization since strings are immutable and can be shared without fear of data corruption. For example, if several reference variables refer to the same String object then it would be bad if any of them changes the String’s value. This is the reason for making String objects as immutable.

Creating String using constructor

1
String s = new String("iByteCode");
In this case, because we used ‘new’ keyword a String object is created in the heap memory even if an equal string object already exists in the pool and ‘s’ will refer to the newly created one.
1
2
3
String str1 = "iByteCode";
String str2 = new String("iByteCode");
System.out.println(str1 == str2);
false
String objects created with the new operator do not refer to objects in the string pool but can be made to using String’s intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String literal pool. If the String is not already in the global String literal pool, then it will be added. For example,
1
2
3
4
String s1 = new String("iByteCode");
String s2 = s1.intern();
String s3 = "iByteCode";
System.out.println(s2 == s3);
true



In the above example, if the change the statement 2 as,
1
String s2 = s1;
Reference variable ‘s2′ will refer to the string object in the heap instead of string literal pool and s1 == s2 will print true.

An object is eligible for garbage collection when it is no longer referenced from an active part of the application. In the case of String literals, they always have a reference to them from the String Literal Pool and are, therefore, not eligible for garbage collection.
All the string literals are created and their references are placed in the pool while JVM loads the class. So, even before a statement like this String s1 = new String(“iByteCode”); is executed, the string literal pool contains a reference to “iByteCode”.

Wednesday, June 11, 2014

1) Why String is immutable in java?

Two reasons:
1) String pool requires string to be immutable otherwise shared reference can be changed from anywhere.
2) security because string is shared on different area like file system, networking connection, database connection , having immutable string allows you to be secure and safe because no one can change reference of string once it gets created. if string had been mutable anyone can surpass the security be logging in someone else name and then later modifying file belongs to other.

how to crate thread class without extending Thread or implementing Runnable interface

7. Threads pools with the Executor Framework


Tip

You find this examples in the source section in Java project called de.vogella.concurrency.threadpools.

Thread pools manage a pool of worker threads. The thread pools contains a work queue which holds tasks waiting to get executed.
A thread pool can be described as a collection of Runnable objects (work queue) and a connections of running threads. These threads are constantly running and are checking the work query for new work. If there is new work to be done they execute this Runnable. The Thread class itself provides a method, e.g. execute(Runnable r) to add a new Runnable object to the work queue.
The Executor framework provides example implementation of the java.util.concurrent.Executor interface, e.g. Executors.newFixedThreadPool(int n) which will create n worker threads. The ExecutorService adds life cycle methods to the Executor, which allows to shutdown the Executor and to wait for termination.

Tip

If you want to use one thread pool with one thread which executes several runnables you can use the Executors.newSingleThreadExecutor() method.

Create again the Runnable.

package de.vogella.concurrency.threadpools;

/** * MyRunnable will count the sum of the number from 1 to the parameter * countUntil and then write the result to the console. * <p> * MyRunnable is the task which will be performed * * @author Lars Vogel * */
public class MyRunnable implements Runnable { private final long countUntil; MyRunnable(long countUntil) { this.countUntil = countUntil; } @Override public void run() { long sum = 0; for (long i = 1; i < countUntil; i++) { sum += i; } System.out.println(sum); } }

Now you run your runnables with the executor framework.

package de.vogella.concurrency.threadpools;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
  private static final int NTHREDS = 10;

  public static void main(String[] args) {
    ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
    for (int i = 0; i < 500; i++) {
      Runnable worker = new MyRunnable(10000000L + i);
      executor.execute(worker);
    }
    // This will make the executor accept no new threads
    // and finish all existing threads in the queue
    executor.shutdown();
    // Wait until all threads are finish
    executor.awaitTermination();
    System.out.println("Finished all threads");
  }
} 

Monday, June 9, 2014

User defined Checked and User defined unchecked exceptions in java with examples

 You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes:
  1. All exceptions must be a child of Throwable.
  2. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  3. If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below:
class MyException extends Exception{ 
 }

You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.

Example:

 // File Name InsufficientFundsException.java
 import java.io.*;

 public class InsufficientFundsException extends Exception 
 {
   private double amount;
   public InsufficientFundsException(double amount)
   {
      this.amount = amount;
   } 
   public double getAmount()
   {
      return amount;
   }
 }

To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException.

 // File Name CheckingAccount.java
 import java.io.*;

 public class CheckingAccount
 {
   private double balance;
   private int number;
   public CheckingAccount(int number)
   {
      this.number = number;
   }
   public void deposit(double amount)
   {
      balance += amount;
   }
   public void withdraw(double amount) throws InsufficientFundsException 
   {
      if(amount <= balance)
      {
         balance -= amount;
      }
      else
      {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs); 
      }
   }
   public double getBalance()
   {
      return balance;
   }
   public int getNumber()
   {
      return number;
   }
 }

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount.

 // File Name BankDemo.java
 public class BankDemo
 {
   public static void main(String [] args)
   {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println("Depositing $500...");
      c.deposit(500.00);
      try
      {
         System.out.println("\nWithdrawing $100..."); 
         c.withdraw(100.00);
         System.out.println("\nWithdrawing $600...");
         c.withdraw(600.00);
      }catch(InsufficientFundsException e)
      {
         System.out.println("Sorry, but you are short $"
                                  + e.getAmount());
         e.printStackTrace();
      }
    }
 }