Tuesday, 31 May 2016

How to display pyramid patterns in Java - Part2

In the first part How to display pyramid patterns in Java - Part1 we have already seen how to display pyramid patterns. In this post java programs are provided for some of the other patterns.

Pattern -1

1
12
123
1234
12345
123456
12345
1234
123
12
1

For this types of patterns it is simpler to have to separate for loops. One for the increasing part and another for the decreasing part. In each of these loops there will be a nested for loop also.

import java.util.Scanner;

public class PatternsDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter highest number for the pattern (1-9) - ");
 
        int noOfRows = sc.nextInt();
        // calling method
        printPattern(noOfRows);

    }
    
    private static void printPattern(int num){
        for(int i = 1; i <= num; i++){
            for(int j = 1; j <= i; j++){
                System.out.print(j);
            }
            
            System.out.println();
            
        }
        for(int i = num; i >= 1; i--){
            for(int j = 1; j < i; j++){
                System.out.print(j);
            }
            System.out.println();
        }                               
    }
}

Pattern -2

1
22
333
4444
55555
666666
55555
4444
333
22
1
import java.util.Scanner;

public class PatternsDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter highest number for the pattern (1-9) - ");
 
        int noOfRows = sc.nextInt();
        // calling method
        printPattern(noOfRows);

    }
    
    private static void printPattern(int num){
        for(int i = 1; i <= num; i++){
            for(int j = 1; j <= i; j++){
                System.out.print(i);
            }
            
            System.out.println();
            
        }
        for(int i = num ; i >= 1; i--){
            for(int j = 1; j < i; j++){
                System.out.print(i -1);
            }
            System.out.println();
        }                    
            
    }

}

Pattern -3

999999999
88888888
7777777
666666
55555
4444
333
22
1
1
22
333
4444
55555
666666
7777777
88888888
999999999
import java.util.Scanner;

public class PatternsDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter highest number for the pattern (1-9) - ");
 
        int noOfRows = sc.nextInt();
        // calling method
        printPattern(noOfRows);

    }
    
    private static void printPattern(int num){
        for(int i = num; i >= 1; i--){
            for(int j = 1; j <= i; j++){
                System.out.print(i);
            }
            
            System.out.println();
            
        }
        for(int i = 1 ; i <=num ; i++){
            for(int j = 1; j <= i; j++){
                System.out.print(i);
            }
            System.out.println();
        }                                
    }
}

That's all for this topic How to display pyramid patterns in Java - Part2. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Armstrong number
  2. Producer-Consumer Java program using ArrayBlockingQueue
  3. How to format date in Java using SimpleDateFormat
  4. Check whether a given String/Number is a palindrome or not
  5. Count total number of times each character appears in a String

You may also like -

>>>Go to Java Programs page

How to display pyramid patterns in Java - Part1

Writing a program to display a pyramid of given pattern is a good way to learn about nested loops. The pattern may contain numbers or any special symbol. So let's see some of the patterns and how to write a program in Java to display those patterns.

If you have noticed in most of the patterns one common thing is; it narrows down at the top (or bottom in case of reverse pyramid) for that you have to print that much spaces before printing the number(s).

Pattern 1

    1
   2 2
  3 3 3
 4 4 4 4
5 5 5 5 5

In this pattern diplay count of a number is equal to the number in that row.

Logic is to have a loop that will itearte depending on the rows that are needed. Then there is a nested loop to display spaces. There is another nested loop to dispaly the number.

import java.util.Scanner;

public class PatternsDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows in the pyramid (1-9) - ");
 
        int noOfRows = sc.nextInt();
        // calling method
        printPattern(noOfRows);

    }
    
    private static void printPattern(int num){
        for(int i = 1; i <= num; i++){
            // this loop will print the spaces after which the
            // number has to be printed
            for(int j = 0; j < num - i; j++){
                System.out.print(" ");
            }
            // this loop will print the number
            for(int k = 0; k < i; k++){
                System.out.print(i + " ");
            }
            System.out.println();
            
        }
            
    }

}

Pattern 2

     *
    * *
   * * *
  * * * *
 * * * * *
* * * * * *

The logic for this pattern is same as above, only change is instead of number asterisk (*) has to be displayed.

import java.util.Scanner;

public class PatternsDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows in the pyramid (1-9) - ");
 
        int noOfRows = sc.nextInt();
        // calling method
        printPattern(noOfRows);

    }
    
    private static void printPattern(int num){
        for(int i = 1; i <= num; i++){
            // this loop will print the spaces after which the
            // number has to be printed
            for(int j = 0; j < num - i; j++){
                System.out.print(" ");
            }
            // this loop will print the number
            for(int k = 0; k < i; k++){
                System.out.print("* ");
            }
            System.out.println();
            
        }
            
    }

}

Pattern -3

     1
    1 2
   1 2 3
  1 2 3 4
 1 2 3 4 5
1 2 3 4 5 6

In this pattern instead of displaying the same number, numbers are displayed in ascending order in each row starting from 1.

import java.util.Scanner;

public class PatternsDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows in the pyramid (1-9) - ");
 
        int noOfRows = sc.nextInt();
        // calling method
        printPattern(noOfRows);

    }
    
    private static void printPattern(int num){
        for(int i = 1; i <= num; i++){
            // this loop will print the spaces after which the
            // number has to be printed
            for(int j = 0; j < num - i; j++){
                System.out.print(" ");
            }
            // this loop will print the number
            for(int k = 1; k < i; k++){
                System.out.print(k + " ");
            }
            System.out.println();
            
        }            
    }
}

Pattern-4

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9

This pattern is same as the pattern above minus the spaces. So the loop that prints the spaces is not needed.

import java.util.Scanner;

public class PatternsDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows in the pyramid (1-9) - ");
 
        int noOfRows = sc.nextInt();
        // calling method
        printPattern(noOfRows);

    }
    
    private static void printPattern(int num){
        for(int i = 1; i <= num; i++){
            
            // this loop will print the number
            for(int j = 1; j <= i; j++){
                System.out.print(j + " ");
            }
            System.out.println();
            
        }            
    }
}

Pattern - 5

        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321

Here rather than same number or in ascending order numbers are displayed in each row in both ascending and then descending order. That is why there is one more nested loop.

import java.util.Scanner;

public class PatternsDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows in the pyramid (1-9) - ");
 
        int noOfRows = sc.nextInt();
        // calling method
        printPattern(noOfRows);

    }
    
    private static void printPattern(int num){
        for(int i = 1; i <= num; i++){
            // this loop will print the spaces after which the
            // number has to be printed
            for(int j = 0; j < num - i; j++){
                System.out.print(" ");
            }
            // this loop will print the number ascending part
            for(int k = 1; k < i; k++){
                System.out.print(k);
            }
            // this loop will print the number descending part
            for(int l = i; l >=1; l--){
                System.out.print(l);
            }
            System.out.println();            
        }           
    }
}

Pattern - 6

12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1

This is the reverse pyramid which follows the same pattern as above but upside down.

import java.util.Scanner;

public class PatternsDemo {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of rows in the pyramid (1-9) - ");
 
        int noOfRows = sc.nextInt();
        // calling method
        printPattern(noOfRows);

    }
    
    private static void printPattern(int num){
        for(int i = num; i >= 1; i--){
            // this loop will print the spaces after which the
            // number has to be printed
            for(int j = 1; j <= num - i; j++){
                System.out.print(" ");
            }
            // this loop will print the number ascending part
            for(int k = 1; k < i; k++){
                System.out.print(k);
            }
            // this loop will print the number descending part
            for(int l = i; l >=1; l--){
                System.out.print(l);
            }            
            System.out.println();           
        }            
    }
}

That's all for this topic How to display pyramid patterns in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Armstrong number
  2. Count total number of times each character appears in a String
  3. Count number of words in a String
  4. Print odd-even numbers using threads and wait-notify
  5. How to reverse a string in Java

You may also like -

>>>Go to Java Programs page

Monday, 30 May 2016

Lock Striping in Java Concurrency

In case you have only one lock for the whole data structure like Array or Map and you are synchronizing it and using it in a multi-threaded environment. Then, effectively any given time only one thread can manipulate the map, as there is only a single lock. All the other threads would be waiting to get the monitor.

If you have to visualize a HashTable or a synchronized HashMap it can be depicted like the following image.

If there are 6 threads only one can get the lock and enter the synchronized collection. Even if the keys these threads want to get (or manipulate the values) are in different buckets as in the image if two threads want to access keys in bucket 0, two threads want to access keys in bucket 1 and two threads want to access keys in bucket n-3, any given time only one thread will get access.

Single lock for whole collection
Single lock for the whole collection

As expected this seriously degrades the performance, now think if there can be separate locks for separate buckets. Then the thread contention won't be at the whole data structure level but at the bucket level. That's the concept of lock striping. Having separate locks for a portion of a data structure where each lock is locking on a variable sized set of independent objects.

That's how ConcurrentHashMap in Java provides synchronization. By default ConcurrentHashMap has 16 buckets and each bucket has its own lock so there are 16 locks too. So the threads which are accessing keys in separate buckets can access them simultaneously.

If you have to visualize it then following image would give you an idea how lock striping for a ConcurrentHashMap will look like.

Here two threads want to access keys in bucket 0 so one of them can enter, again two threads want to access keys in bucket 1 so one of them can enter. Same with bucket n-3. So, with lock striping out of 6 3 threads can work on the data structure.

Lock Striping in ConcurrentHashMap
Lock Striping in ConcurrentHashMap

Drawback of lock striping

One of the downside of lockstriping as mentioned in "Java Concurrency in practice" is that it is more difficult and costly, if you need to lock the collection for exclusive access than with a single lock.

That's all for this topic Lock Striping in Java Concurrency. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. ConcurrentHashMap in Java
  2. Difference between HashMap and ConcurrentHashMap in Java
  3. CountDownLatch in Java concurrency
  4. Synchronization in Java multithreading
  5. ReentrantReadWriteLock in Java

You may also like -

Sunday, 29 May 2016

Java Concurrency interview questions

  1. What is CountDownLatch in Java concurrency?

    CountDownLatch can be visualized as a latch that is released only after the given number of events occur. CountDownLatch is initialized with that count (given number of events).

    Each time one of those events occur count is decremented, for that countdown() method is used. Thread(s) that are waiting for the latch to release (current count reaches zero due to invocations of the countDown()method) are blocked using await() method.

    It is useful in the scenario when you want one or more threads to wait until one or more events being performed in other threads complete.

    Read more about CountDownLatch here.
  2. What is CyclicBarrier in Java concurrency?

    CyclicBarrier is useful in scenarios where you want set of threads to wait for each other to reach a common barrier point. When each thread reaches the barrier (common point) you need to call await() method on the CyclicBarrier object. This will suspend the thread until all the thread also call the await() method on the same CyclicBarrier object.

    Once all the specified threads have called await() method that will trip the barrier and all threads can resume operation.

    The barrier is called cyclic because it can be re-used after the waiting threads are released.

    Read more about CyclicBarrier here.
  3. What is the difference between a CountDownLatch and CyclicBarrier?

    • When you are using a CountDownLatch, you specify the number of calls to the countdown() method when creating a CountDownLatch object. What this means is you can use CountDownLatch with only a single thread and using countdown() to decrement as and when the specified even occur.
      When you are using CyclicBarrier you specify the number of threads that should call await() method in order to trip the barrier. That means if you have a CyclicBarrier initialized to 3 that means you should have at least 3 threads to call await().
    • CountDownLatch can't be reused, when count reaches zero it cannot be reset.
      CyclicBarrier can be reused after the waiting threads are released.
    Read more differences and explanation here.
  4. If a CountDownLatch is initialized with some count let's say 3 (new CountDownLatch(3)). Do we need to have 3 threads for countdown in that case?

    No. Same number of threads are not required. A CountDownLatch initialized to N can be used to make one thread wait until N threads have completed some action, or some action has been completed N times.

    Read more about CountDownLatch here.
  5. What is Phaser in Java concurrency?

    Phaser is more suitable for use where it is required to synchronize threads over one or more phases of activity. Though Phaser can be used to synchronize a single phase, in that case it acts more like a CyclicBarrier.

    Phaser is reusable (like CyclicBarrier) and more flexible in usage.

    The number of parties registered to synchronize on a phaser may vary over time. Tasks may be registered at any time (using methods register(), bulkRegister(int), or by specifying initial number of parties in the constructor). Tasks may also be optionally deregistered upon any arrival (using arriveAndDeregister()).

    Read more about Phaser here.
  6. What is Exchanger in Java concurrency?

    Exchanger makes it easy for two threads to exchange data between themselves.

    Exchanger provides a synchronization point at which two threads can pair and swap elements. Exchanger waits until two separate threads call its exchange() method. When two threads have called the exchange() method, Exchanger will swap the objects presented by the threads.

    Read more about Exchanger here.
  7. What is Semaphore in Java concurrency?

    The Semaphore class present in java.util.concurrent package is a counting semaphore in which a semaphore, conceptually, maintains a set of permits. Thread that wants to access the shared resource tries to acquire a permit using acquire() method. At that time if the Semaphore's count is greater than zero thread will acquire a permit and Semaphore's count will be decremented by one. If Semaphore's count is zero, when thread calls acquire() method, then the thread will be blocked until a permit is available. When thread is done with the shared resource access, it can call the release() method to release the permit. That results in the Semaphore's count incremented by one.

    Read more about Semaphore here.
  8. Write a Java program to print odd/even numbers using semaphore?

    See the program with explanation here -

    Print odd/even numbers using semaphore
  9. What is ReentrantLock in Java?

    ReentrantLock is a concrete implementation of the Lock interface which is present in java.util.concurrent.locks package.

    Every object created in Java has one mutually exclusive lock associated with it. When you are using synchronized you are using that lock implicitly (with no other feature) whereas when you are using any of the lock implementation (like Reentrant lock) you are using that lock explicitly. Which means there are methods like lock() to acquire the lock and unlock() to release the lock. Along with that ReentrantLock provides many other features like fairness, ability to interrupt and a thread waiting for a lock only for a specified period.

    Read more about ReentrantLock here.
  10. What is the Difference between ReentrantLock and Synchronized?

    • When you use a synchronized block or method you just need to write synchronized keyword (and provide associated object) acquiring lock and releasing it is done implicitly.

      With ReentrantLock acquiring and releasing lock is done by user using lock() and unlock() methods.

    • Synchronized forces all lock acquisition and release to occur in a block-structured way which means when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired.

      ReentrantLock provides more flexibility, it allows a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.

    • ReentrantLock provides additional functionality over the use of synchronized methods and statements by providing an option for fairness, providing a non-blocking attempt to acquire a lock (tryLock()), an attempt to acquire the lock that can be interrupted (lockInterruptibly(), and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)).
    Read more differences between ReentrantLock and Synchronized here.
  11. Why is it named ReentrantLock?

    It is called ReentrantLock as there is an acquisition count associated with the lock which means when you use lock() method to acquire a lock and you get it then the acquisition count is 1.

    A Reentrant lock will also allow the lock holder to enter another block of code with the same lock object as thread already owned it. In that case, if a thread that holds the lock acquires it again, the acquisition count is incremented and the lock then needs to be released twice to truly release the lock.

    Read more about ReentrantLock here.
  12. What is ReadWriteLock in Java?

    In a multi-threading application multiple reads can occur simultaneously for a shared resource. It is only when multiple writes happen simultaneously or intermix of read and write that there is a chance of writing the wrong value or reading the wrong value.

    ReadWriteLock uses the same idea in order to boost the performance by having separate pair of locks. A ReadWriteLock maintains a pair of associated locks -

    • One for read-only operations;
    • and
    • One for writing.

    The read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.


  13. What is ReentrantReadWriteLock in Java concurrency?

    ReentrantReadWriteLock is an implementation of the ReadWriteLock interface which provides a pair of read-write lock.
    • To get a read lock you need to use - rw.readLock().lock();
    • To get a write lock you need to use - rw.writeLock().lock();
    Where rw is an object of ReentrantReadWriteLock class.

    ReentrantReadWriteLock also allows downgrading from the write lock to a read lock. You can first acquire a write lock, then the read lock and then release the write lock.

    Read more about ReentrantReadWriteLock here.
  14. How ReadWritelock can help in reducing contention among multiple threads? OR
    What is benefit of using ReadWriteLock in Java?

    ReadWriteLock provides separate set of locks for reading and writing operations. Where read lock may be held simultaneously by multiple reader threads, so long as there are no writers. The write lock is exclusive.

    So read operations are not mutually exclusive. It exploits the fact that while only a single thread at a time (a writer thread) can modify the shared data, in many cases any number of threads can concurrently read the data (hence reader threads).

    Thus in the applications where reads are more than writes or duration of reads is more the thread contention will be less as read lock is shared by many thread rather than being mutually exclusive. So you won't have a situation where only one thread is reading and other threads are waiting.

    Read more about ReentrantReadWriteLock here.
  15. What is ConcurrentHashMap in Java?

    ConcurrentHashMap is also a hash based map like HashMap, how it differs is the locking strategy used by ConcurrentHashMap. Unlike HashTable (or synchronized HashMap) it doesn't synchronize every method on a common lock. ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map.

    That way ConcurrentHashMap depite being a thread safe alternative to HashTable gives much better performance.

    Read more about ConcurrentHashMap here.
  16. What is lock striping in concurrent programming?

    The concept of lock striping is to have separate locks for a portion of a data structure where each lock is locking on a variable sized set of independent objects.

    That's how ConcurrentHashMap in Java provides synchronization. By default ConcurrentHashMap has 16 buckets and each bucket has its own lock so there are 16 locks too. So the threads which are accessing keys in separate buckets can access them simultaneously.

    Read more about lock striping here.
  17. What is the Difference between HashMap and ConcurrentHashMap in Java?

    • ConcurrentHashMap is thread safe and fit for use in a multi-threaded environment whereas HashMap is not thread safe.
    • HashMap can be synchronized using the Collections.synchronizedMap() method but that synchronizes all the methods of the HashMap and effectively reduces it to a data structure where one thread can enter at a time.
      In ConcurrentHashMap synchronization is done a little differently. Rather than locking every method on a common lock, ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map.
    Read more difference here here.
  18. Why ConcurrentHashMap is faster than Hashtable in Java?

    In HashTable each method is synchronized on a single lock which means at any given time only one thread can enter any method.
    ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map. By default there are 16 buckets and also separate locks for separate buckets. So the default concurrency level is 16. Thus theoretically at any given time 16 threads can access separate buckets without blocking which improves the performance of the ConcurrentHashMap.

    In ConcurrentHashMap performance is further improved by providing read access concurrently without any blocking. Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove).

    Read more about ConcurrentHashMap here.
  19. What is CopyOnWriteArrayList in Java?

    CopyOnWriteArrayList is also an implementation of the List interface but it is a thread safe variant. This thread safety is achieved by making a fresh copy of the underlying array with every mutative operations (add, set, and so on).

    Using CopyOnWriteArrayList provides better performance in scenarios where there are more iterations of the list than mutations.

    Read more about CopyOnWriteArrayList here.
  20. What is the Difference between ArrayList and CopyOnWriteArrayList in Java?

    ArrayList is not thread-safe whereas CopyOnWriteArrayList is thread-safe and fit for use in multi-threaded environment.

    Iterator returned by ArrayList is fail-fast. Iterator returned by CopyOnWriteArrayList is fail-safe.

    Performance wise ArrayList is faster as it is not synchronized and there is no added burden of thread-safety. CopyOnWriteArrayList is comparatively slower and if there are lots of writes by various threads that will degrade the performance of the CopyOnwriteArrayList as there will be copies made per mutation.

    Read more differences and explanation here.
  21. What is CopyOnWriteArraySet in Java?

    CopyOnWriteArraySet is a thread-safe collection and it internally uses CopyOnWriteArrayList for all of its operations.

    Since it uses CopyOnWriteArrayList internally so thread-safety is achieved in the same way in CopyOnwriteArraySet as in CopyOnWriteArrayList - all mutative operations (add, set, and so on) are implemented by making a fresh copy of the underlying array.

    The iterator returned by CopyOnwriteArraySet is fail-safe which means any structural modification made to the CopyOnwriteArraySet won't throw ConcurrentModificationException.

    Read more about CopyOnWriteArraySet here.
  22. What is ConcurrentSkipListMap in Java?

    ConcurrentSkipListMap implements ConcurrentNavigableMap and it is a sorted map just like TreeMap with the added feature of being concurrent.
    ConcurrentSkipListMap is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

    Read more about ConcurrentSkipListMap here.
  23. What is ConcurrentSkipListSet in Java?

    ConcurrentSkipListSet implements NavigableSet and it is a sorted set just like TreeSet with added feature of being concurrent.
    The elements of the set are kept sorted according to their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

    Read more about ConcurrentSkipListSet here.
  24. What is ConcurrentLinkedQueue in Java?

    ConcurrentLinkedQueue is an unbounded thread-safe queue which stores its elements as linked nodes. This queue orders elements FIFO (first-in-first-out).
    It doesn't block operations as it is done in the implementations of BlockingQueue interface like ArrayBlockingQueue.

    Read more about ConcurrentLinkedQueue here.
  25. What is ConcurrentLinkedDequeue in Java?

    ConcurrentLinkedDeque is an unbounded thread-safeDeque which stores its elements as linked nodes. Since it implements deque interface ConcurrentLinkedDequesupports element insertion and removal at both ends.

    ConcurrentLinkedDequeue is thread safe and it doesn't block operations.

    Read more about ConcurrentLinkedDequeue here.
  26. What do you mean by non-blocking algorithm/data structure?

    An algorithm is called non-blocking if it doesn't block threads in such a way that only one thread has access to the data structure and all the other threads are waiting. Same way failure of any thread in a non-blocking algorithm doesn't mean failure or suspension of other threads.

    Implementation of non-blocking data structures in Java like atomic variables or ConcurrentLinkedQueue use an atomic read-modify-write kind of instruction based on compare-and-swap.

    Read more about non-blocking algorithm here.
  27. What is Busy Spinning? When will you use Busy Spinning as waiting strategy?

    Busy spinning or busy wait in a multi-threaded environment is a technique where other threads loop continuously waiting for a thread to complete its task and signal them to start.

    Busy spinning is wasteful of CPU cycles as thread just keep running in a loop unless the condition given in the loop satisfies. Busy spinning may give some advantage in multi-core processors. If a thread relinquishes CPU, the CPU cache for the thread where the thread state, data are stored will also be lost, if the thread resumes its operation on another CPU. In that case it has to rebuild the cache again.

    Read more about Busy Spinning here.
  28. What is BlockingQueue in Java Concurrency?

    BlockingQueueinterface is added in Java 5 with in the java.util.concurrent package.

    BlockingQueue is a queue that can block the operations. Which means BlockingQueue supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.

    BlockingQueue provides following blocking methods -
    • put(E e) - Inserts the specified element into this queue, waiting if necessary for space to become available.
    • take() - Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.
    Read more about BlockingQueue here.
  29. Write a Java program to code producer consumer design using blocking queue.

    Please refer Producer-Consumer Java program using ArrayBlockingQueue for the Java program to code producer consumer design using blocking queue.
  30. What is blocking method in Java?

    Methods which want to execute the task assigned without relinquishing control to other thread are called blocking methods.

    A very relevant example of blocking methods, which most of you would have encountered is read() method of theInputStream class. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.

    Read more about blocking method here.
  31. What is ArrayBlockingQueue in Java Concurrency?

    ArrayBlockingQueue is an implementation of the BlockingQueue interface. ArrayBlockingQueue is a bounded blocking queue which internally uses an array to store elements.

    Since ArrayBlockingQueue is bounded it means it has to be created with some initial capacity and that capacity cannot be changed later. Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block.

    Read more about ArrayBlockingQueue here.
  32. What is LinkedBlockingQueue in Java Concurrency?

    LinkedBlockingQueue is an implementation of BlockingQueue interface.

    LinkedBlockingQueue internally uses linked nodes to store elements. It is optionally bounded and that's where it differs from ArrayBlockingQueue which is bounded.

    Read more about LinkedBlockingQueue here.
  33. What is PriorityBlockingQueue in Java Concurrency?

    PriorityBlockingQueue class implements the BlockingQueue interface. The elements of the PriorityBlockingQueue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which of the following constructor is used.

    • PriorityBlockingQueue() - Creates a PriorityBlockingQueue with the default initial capacity (11) that orders its elements according to their natural ordering.
    • PriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator) - Creates a PriorityBlockingQueue with the specified initial capacity that orders its elements according to the specified comparator.
    PriorityBlockingQueue class does not permit null elements. Read more about PriorityBlockingQueue here.
  34. What is SynchronousQueue in Java?

    SynchronousQueue is an implementation of the BlockingQueue interface. SynchronousQueue does not have any internal capacity, not even a capacity of one. In SynchronousQueue each insert operation must wait for a corresponding remove operation by another thread, and vice versa.

    If you put an element in SynchronousQueue using put() method it will wait for another thread to receive it, you can't put any other element in the SynchronousQueue as it is blocked.

    Read more about SynchronousQueue here.
  35. What is DelayQueue in Java Concurrency?

    DelayQueue is an unbounded implementation of BlockingQueue interface. DelayQueue can store elements of type Delayed only and an element can only be retrieved from DelayQueue when its delay has expired.

    When you implement Delayed interface two methods have to be implemented getDelay(TimeUnit unit) and compareTo(T o).

    getDelay(TimeUnit unit) - Returns the remaining delay associated with this object, in the given time unit.

    Read more about DelayQueue here.
  36. What is TransferQueue in Java?

    TransferQueue interface, added in Java 7, extends BlockingQueue interface. The extra functionality provided by TransferQueue interface is that it provides blocking method which will wait until other thread receives your element.

    That's how it differs from BlockingQueue where you can only put element into queue or retrieve element from queue and block if queue is full (while you are putting elements) or block if queue is empty (while you are retrieving elements).

    TransferQueue has a blocking method transfer(E e) which will ensure that the element is transferred to the consumer, it will wait if required to do so.

    Read more about TransferQueue here.
  37. What is LinkedTransferQueue in Java?

    LinkedTransferQueue, is an implementation of the TransferQueue. It is an unbounded queue and stores elements as linked nodes.

    Read more about TransferQueue here.
  38. What is BlockingDeque in Java Concurrency?

    BlockingDeque interface (added in Java 6) is a Deque that provides additional support for blocking operations. Blocking methods of BlockingDeque interface come in four forms.

    • Throw exception - Methods falling in this category will throw exception if blocked.
    • Return special value - This type of methods will return some value if need to wait, like false.
    • Blocks - This type of methods will wait if necessary for space to become available.
    • Times out - This type of methods will block for only a given maximum time limit before giving up.

    BlockingDeque is thread safe, does not permit null elements, and may (or may not) be capacity-constrained.

    Read more about BlockingDeque here.
  39. What is LinkedBlockingDeque in Java?

    LinkedBlockingDeque is an implementation of the BlockingDeque interface and it was added in Java 6. LinkedBlockingDeque is an optionally bounded deque and it stores its elements as linked nodes.

    Read more about LinkedBlockingDeque here.

  40. What is Executor in Java concurrency?

    The concurrent API has a feature called executors that provides an alternative to managing threads through the Thread class. At the core of the executors is the Executor interface - An object of type Executor can execute runnable tasks. An Executor is normally used instead of explicitly creating threads.
    For example If r is a Runnable object, and e is an Executor object you can replace

    (new Thread(r)).start();
    
    with
    e.execute(r);
    
    The Executor interface provides a single method, execute -
    void execute(Runnable command)
    

    Read more about Executor here.

  41. What is ExecutorService in Java concurrency?

    ExecutorService interface extends Executor interface and provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.
    ExecutorService has more versatile submit method. Like execute, submit accepts Runnable objects, but also accepts Callable objects, which allow the task to return a value. The submit method returns a Future object, which is used to retrieve the Callable return value and to manage the status of both Callable and Runnable tasks.

    Read more about ExecutorService here.

  42. Name any class that implements Executor or ExecutorService interface?

    In the Java concurrency there are three pre defined executor classes that implement the Executor and ExecutorService interface.

    • ThreadPoolExecutor - Implements the Executor and ExecutorService interfaces and executes the submitted task using one of the pooled thread.
    • ScheduledThreadPoolExecutor - It extends ThreadPoolExecutor and also implements the ScheduledExecutorService. This class schedule commands to run after a given delay, or to execute periodically.
    • ForkJoinPool - It implements the Executor and ExecutorService interfaces and is used by the Fork/Join Framework.
    Read more about ExecutorService here.

  43. What is difference between submit() and execute() method of Executor and ExecutorService in Java?

    • execute() method is provided by Executor interface where as submit() method is provided by ExecutorService.
    • execute() method only takes Runnable as argument - execute(Runnable command) and does not return any value.
    • ExecutorService has more versatile submit() method. submit() method is overloaded and accepts both Runnable objects and Callable objects, submit also allows the task to return a value (an object of type Future). The Future's get method will return the given result upon successful completion.

  44. How can I immediately block a thread even if I am using submit method and using a callable object?

    If you would like to immediately block waiting for a task, you can use constructions of the form

    result = exec.submit(aCallable).get();
    

  45. What will happen if submit method can’t schedule a task for execution?

    It will throw RejectedExecutionException.


  46. How to shut down an ExecutorService?

    An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService.
    The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted.

    Read more about ExecutorService here.
  47. What is a ScheduledExecutorService?

    ScheduledExecutorService extends ExecutorService and provides methods that can schedule commands to run after a given delay, or to execute periodically.
    It has methods that execute a Runnable or Callable task after a specified delay.

    • schedule(Callable<V> callable, long delay, TimeUnit unit) - Creates and executes a ScheduledFuture that becomes enabled after the given delay.
    • schedule(Runnable command, long delay, TimeUnit unit) - Creates and executes a one-shot action that becomes enabled after the given delay.

    Read more about ScheduledExecutorService here.
  48. What is Executors class?

    Executors class provide factory and utility methods for Executors framework classes like Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable.
    Though you can use ThreadPoolExecutor and ScheduledThreadPoolExecutor directly, but the best way to get an executor is to use one of the static factory methods provided by the Executors utility class.
    Some of the factory methods -

    • static ExecutorService newCachedThreadPool() - Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.
    • static ExecutorService newFixedThreadPool(int numThreads) - Creates a thread pool that reuses a fixed number of threads.
    • static ScheduledExecutorService newScheduledThreadPool(int numThreads) - Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
    • newSingleThreadExecutor() - Creates an Executor that uses a single worker thread operating off an unbounded queue.
    As example -
    ExecutorService ex = Executors.newFixedThreadPool(2);
    


  49. What is threadpool in Java?

    In a large scale application if each task uses its own thread then allocating and deallocating many thread objects creates a significant memory management overhead.
    Thread pool as the name suggests provides a set of threads, any task which has to be executed get a thread from this pool.

    // creating executor with pool of 2 threads
      ExecutorService ex = Executors.newFixedThreadPool(2);
      // running 6 tasks
      ex.execute(new Task());
      ex.execute(new Task());
      ex.execute(new Task());
      ex.execute(new Task());
      ex.execute(new Task());
      ex.execute(new Task());
      //shutting down the executor service
      ex.shutdown();
    
    Even if we are running 6 tasks here, all these tasks would be run using the 2 threads from the pool.


  50. How to construct a thread pool with 2 threads that executes some tasks that return a value?

    You can create a fixed thread pool using the newFixedThreadPool() method of the Executors class.

    // creating executor with pool of 2 threads
      ExecutorService ex = Executors.newFixedThreadPool(2);
      // running tasks
      Future f1 = ex.submit(new Task());
      Future f2 = ex.submit(new Task());
      try {
       // getting the future value
       System.out.println("Future f1 " + f1.get());
       System.out.println("Future f1 " + f1.get());
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      } catch (ExecutionException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      ex.shutdown();
    


  51. What is Callable and Future in Java concurrency?

    Callable, an interface, was added in Java 5. It allows you to define a task to be completed by a thread asynchronously. The Callable interface has a call() method, since it is a generic interface so it can return any value (Object, String, Integer etc.) based on how it is initialized. Main feature of the call() method provided by Callable interface is that it can return value.
    Future interface - A Future represents the result of an asynchronous computation. When you submit a callable task using the submit() method of the ExecutorService, Future object is returned.
    Future provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.
    get() - get() method retrieves the result of the computation, blocking if necessary for the computation to complete.

    Read more about Callable and Future here.
  52. What is atomic variable in Java?

    In Java concurrency classes like AtomicInteger, AtomicLong are provided with a int, long value respectively that may be updated atomically.
    These atomic variable classes in Java concurrency like AtomicInteger, AtomicLong uses non-blocking algorithm. These non-blocking algorithms use low-level atomic machine instructions such as compare-and-swap instead of locks to ensure data integrity under concurrent access.

    Read more about AtomicInteger here.

Related Topics

  1. Java OOP interview questions
  2. Core Java basics interview questions
  3. Java String interview questions
  4. Java Exception Handling interview questions
  5. Java Multi-threading interview questions
  6. Java Collections interview questions

Friday, 27 May 2016

Bean definition inheritance in Spring

In object-oriented programming there is a parent-child relationship among classes where child class inherits properties and methods of the parent class through inheritance. Same concept of inheritance is provided in Spring also where bean definition is inherited.

A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name and so on. A child bean definition inherits configuration data from a parent definition.

That way common things can be moved to one bean and other beans can use it by inheriting that parent bean. In addition to that child definition can override some values, or add others, as needed.

Bean definition inheritance configuration

In XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute.

A child bean definition uses the bean class from the parent definition if none is specified, but can also override it. In the latter case, the child bean class must be compatible with the parent, that is, it must accept the parent's property values.

A child bean definition inherits scope, constructor argument values, property values, and method overrides from the parent, with the option to add new values. Any scope, initialization method, destroy method, and/or static factory method settings that you specify will override the corresponding parent settings.

The remaining settings are always taken from the child definition: depends on, autowire mode, dependency check, singleton, lazy init.

Example Code

Let's see an example where we have a Payment class with two fields in it paymentType and amount. If you want to have a configuration where by default paymentType is "cash" then it can be done using bean definition inheritance.

Payment class

public class Payment {
    private String paymentType;
    private double amount;
    public String getPaymentType() {
        return paymentType;
    }
    public void setPaymentType(String paymentType) {
        this.paymentType = paymentType;
    }
    public double getAmount() {
        return amount;
    }
    public void setAmount(double amount) {
        this.amount = amount;
    }
    
    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("Payment Type ").append(getPaymentType());
        sb.append(" Amount ").append(getAmount());
        return sb.toString();
    }
}

XML Configuration

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
 
<!--  <context:component-scan base-package="org.netjs.prog" /> --> 

    <bean id="basePaymentBean" class="org.netjs.prog.Payment">
        <property name="paymentType" value="cash"/>
    </bean> 
    
    <bean id="paymentBean" parent="basePaymentBean">
        <property name="amount" value="50.15" />
        <!-- paymentType value will be inherited from parent -->
    </bean>
 
</beans>

You can run it using the following program.

import org.netjs.prog.Payment;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {

 public static void main(String[] args) {
  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
        Payment bean = (Payment) context.getBean("paymentBean");
        System.out.println("Values " + bean);
        context.close();
 }
}

Output

Values Payment Type cash Amount 50.15

Overriding the value

As already stated child bean definition can override the properties inherited from the parent bean. As example if you want to override the default option of "cash" provided through parent bean definition and have the value as "credit card" for the paymentType then it can be done as shown in below XML configuration.

<bean id="basePaymentBean" class="org.netjs.prog.Payment" abstract="true">
    <property name="paymentType" value="cash"/>
</bean> 
    
<bean id="paymentBean" parent="basePaymentBean">
    <property name="paymentType" value="credit card"/>
    <property name="amount" value="50.15" />
</bean>

Output

Values Payment Type credit card Amount 50.15

If you have observed in the XML configuration the parent class has an attribute "abstract" as true. Marking the bean as abstract means that it can't be instantiated.

Actually that's how inheritance with in the bean definition must be used. Parent class must be defined with common property values and the child beans should define values for the other values.

Since parent definition has values for common values so it is more of a template which should be inherited and then values for the other values should be provided by the child bean. In that case it doesn't make sense to instantiate the parent class itself as it is just a template.

In fact parent bean can be defined as a pure template itself let's see how it can be done.

Using parent bean as Template

If you want to use parent bean as a template then you don't need to have a class defined for the parent bean and it has to have abstract attribute as true. In that case XML configuration will look like this -

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="basePaymentBean" abstract="true">
        <property name="paymentType" value="cash"/>
    </bean> 
    
    <bean id="ccPaymentBean" parent="basePaymentBean" class="org.netjs.prog.CCPayment">
        <property name="paymentType" value="credit card"/>
        <property name="amount" value="50.15" />
    </bean>
 
</beans>

CCPayment class

public class CCPayment {
 private String paymentType;
 private double amount;
 public String getPaymentType() {
  return paymentType;
 }
 public void setPaymentType(String paymentType) {
  this.paymentType = paymentType;
 }
 public double getAmount() {
  return amount;
 }
 public void setAmount(double amount) {
  this.amount = amount;
 }
 
 @Override
 public String toString() {
  StringBuffer sb = new StringBuffer();
  sb.append("Payment Type ").append(getPaymentType());
  sb.append(" Amount ").append(getAmount());
  return sb.toString();
 }
}

You can run it using the following class -

public class App {

 public static void main(String[] args) {
  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
  CCPayment bean = (CCPayment) context.getBean("ccPaymentBean");
        System.out.println("Values " + bean);
        context.close();

 }

}

Output

Values Payment Type credit card Amount 50.15

That's all for this topic Bean definition inheritance in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Spring bean life cycle
  2. Different bean scopes in Spring
  3. Autowiring using XML configuration in Spring
  4. Autowiring using annotations in Spring
  5. Difference between component-scan and annotation-config in Spring

You may also like -

>>>Go to Spring tutorial page

Sunday, 22 May 2016

What are JVM, JRE and JDK in Java

JVM

JVM meaning Java Virtual Machine is an abstract layer between a Java program and the platform that Java Program is running on. JVM is platform dependent and different implementations of JVMs are available for specific platforms.
A Java program can run on a specific platform only when -

  • JVM has been implemented for a platform.
  • JVM has been installed on a platform.

The JVM doesn't understand Java program as we write it, it understands the ".class" file which we get by compiling the .java file. This ".class" file contain the bytecode understandable by the JVM. It is because of JVM that Java is called a "portable language" (write once, run anywhere)

JRE

JRE meaning Java Runtime Environment provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language.
The compiled bytecode doesn't run on CPU directly, JVM sits in between and interpret the bytecode into readable machine language for the CPU. It is actually the JRE that enables Java bytecode to run on any platform. Bytecodes, which are interpreted by the JVM, simply call classes found in the JRE when they need to perform actions they cannot do by themselves

JDK

JDK meaning Java Development Kit is a superset of the JRE, and contains everything that is in the JRE, plus development tools such as the compilers and debuggers necessary for developing applets and applications.

That's all for this topic JVM, JRE and JDK in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Why main method static in Java
  2. Why file name and class name should be same in Java
  3. Java pass by value or pass by reference
  4. static in Java
  5. Core Java basics interview questions

You may also like -

>>>Go to Java Basics page

Wednesday, 18 May 2016

Difference between ArrayList and LinkedList in Java

In Java collections framework ArrayList and LinkedList are two different implementations of List interface (LinkedList also implement Deque interface though).

LinkedList is implemented using a doubly linked list concept where as ArrayList internally uses an array of Objects which can be resized dynamically. In most of the cases we do use ArrayList and it works very well but there are some use cases where use of the linked list may be a better choice. So let's see some of the difference between ArrayList and LinkedList, it will help you in making an informed choice when to use ArrayList and when a LinkedList.

ArrayList class provides a constructor ArrayList(int initialCapacity) even if the default constructor ArrayList() is used an empty list is constructed with an initial capacity of ten. Where as LinkedList just provides one constructor LinkedList() which constructs an empty list. Note that in LinkedList there is no provision of initial capacity or default capacity.

What it means is that if elements are added at the last every time and capacity is not breached then ArrayList will work faster because it already has an initial capacity and just need to add that element at the index in the underlying array. Where as in LinkedList a new node has to be created and references for Next and Prev are to be adjusted to accommodate the new Node.

The above mentioned case for add is something we do most of the time while using arraylist or use get(int index) which also is faster in arraylist and that's why we normally use ArrayList, even JavaDocs advocate the same thing -
https://docs.oracle.com/javase/tutorial/collections/implementations/list.html

Let's go through some of the operations to see which implementation of list shines where -

  • Adding an element - If you are frequently adding element at the beginning of the list then LinkedList may be a better choice because in case of arraylist adding at the beginning every time will result in shuffling all the existing elements within the underlying array by one index to create space for the new element.
    Even in the case of adding at the last ArrayList may give O(n) performance in the worst case. That will happen if you add more elements than the capacity of the underlying array, as in that case a new array (1.5 times the last size) is created, and the old array is copied to the new one.
    So for LinkedList add(e Element) is always O(1) where as for ArrayList add(e Element) operation runs in amortized constant time, that is, adding n elements requires O(n) time.
  • Retrieving an element - Retrieving an element from the list using get(int index) is faster in ArrayList than in LinkedList. Since ArrayList internally uses an array to store elements so get(int index) means going to that index directly in the array. In Linked list get(int index) will mean traversing through the linked list nodes.
    So for LinkedList get(int index) is O(n) where as for ArrayList get(int index) is O(1).
  • Removing an element - If you are removing using the remove(int index) method then for LinkedList class it will be O(n) as list has to be traversed to get to that index and then the element removed. Though the LinkedList provides methods like removeFirst() and removeLast() to remove the first or last element and in that case it will be O(1).
    In case of ArrayList getting to that index is fast but removing will mean shuffling the remaining elements to fill the gap created by the removed element with in the underlying array. It ranges from O(1) for removing the last element to O(n). Thus it can be said remove(int index) operation is O(n - index) for the arraylist.
  • Removing an element while iterating - if you are iterating the list and removing element using iterator.remove() then for LinkedList it is O(1) as the iterator is already at the element that has to be removed so removing it means just adjusting the Next and Prev references. Where as for ArrayList it is again O(n - index) because of an overhead of shuffling the remaining elements to fill the gap created by the removed elements.
  • One more difference is that LinkedList implementation provides a descendingIterator() which comes from implementing the Deque interface. descendingIterator() returns an iterator over the elements in this deque in reverse sequence.
    In ArrayList there is no such iterator.

That's all for this topic Difference between ArrayList and LinkedList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference between Array and ArrayList in Java
  2. Difference between ArrayList and Vector in Java
  3. Difference between HashMap and ConcurrentHashMap in Java
  4. HashSet Vs LinkedHashSet Vs TreeSet in Java
  5. How to sort arraylist of custom objects in Java
  6. Java Collections interview questions

You may also like -

How to reverse a string in Java

Reversing a string using a recursive method or using iteration is one Java interview coding question asked quite frequently along with some other popular questions like How to find the longest palindrome in the given String, How to find all the permutations of the given String.

Though StringBuilder class has a reverse() method which can do the reversal of the string but generally in the interviews it will be asked to write the iterative or recursive logic or both so in this post both ways are given.

Reversing a string - Non-recursive

Non-recursive solution follows the logic of starting from the end of the string and keep moving back character by character and keep appending those characters to form a new string which is reverse of the given String.

Reversing a string - Recursive

In recursive solution in each recursive call to the method you take the first character (index 0) and call the method with the rest of the string (excluding the first char) and add the first char of the passed string at the end.

Java Code

public class ReverseDemo {

    public static void main(String[] args) {
        
        String reversed = reverseString("Bharat");
        System.out.println("reverse (recursion) - " + reversed);
        
        String reverseItr = reverseItr("India is my country");
        System.out.println("reverse (non recursive) - " + reverseItr);
    }
    
    // Using recursion
    private static String reverseString(String str){
        // validation & base case
        if((str == null) || (str.length() <= 1)){
            return str;
        }
        // recursive call
        return reverseString(str.substring(1)) + str.charAt(0);    
    }
    
    
    // Using iteration - Non Recursive
    private static String reverseItr(String str){
        // validation
        if((str == null) || (str.length() <= 1)){
            return str;
        }
        
        StringBuilder sb = new StringBuilder();
        for(int i = str.length() - 1; i >= 0; i--){
            sb.append(str.charAt(i));
        }
        return sb.toString();
    }
}

Output

reverse (recursion) - tarahB
reverse (non recursive) - yrtnuoc ym si aidnI

Explanation

I guess the explanation for the iteration logic provided above should suffice for that code. Recursive is a little hard to visualize so let's see how recursive calls will actually stack up.

reverseString("Bharat")
(reverseString("harat")) + "B"
((reverseString("arat")) + "h") + "B"
(((reverseString("rat")) + "a") + "h") + "B"
((((reverseString("at")) + "r") + "a") + "h") + "B"
// This will trigger the base condition
(((((reverseString("t")) + "a") + "r") + "a") + "h") + "B"

"tarahB"

That's all for this topic How to reverse a String - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Count total number of times each character appears in a String
  2. How to find the longest palindrome in the given String
  3. How to find all the permutations of the given String
  4. Check if given strings are anagram or not
  5. How to format date in Java using SimpleDateFormat

You may also like -

>>>Go to Java Programs page

Tuesday, 17 May 2016

Formatting date in Java using SimpleDateFormat

If you want to create your own customized formats for formatting the date, you can use the SimpleDateFormat class.

When you create a SimpleDateFormat object, you specify a pattern String. The contents of the pattern String determine the format of the date and time.

Java Code

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatDate {

 public static void main(String[] args) {
  FormatDate fd = new FormatDate();
  
  // For date like Wed, Jun 8, '16
  fd.getFormattedDate("EEE, MMM d, ''yy");
  // For date like Wednesday, June 08, 2016
  fd.getFormattedDate("EEEE, MMMM dd, yyyy");
  // For date like 05/08/2016
  fd.getFormattedDate("MM/dd/yyyy");
  // For date like 08/05/2016
  fd.getFormattedDate("dd/MM/yyyy");
  // For date like 2016-05-08 AD at 09:42:54 IST
  // with era designator (AD in this case) and 
  // timezone info (IST in this case)
  fd.getFormattedDate("yyyy-MM-dd G 'at' hh:mm:ss z");
  //For date like 08/May/2016 AD 21:47:28:889 PM
  //with AM/PM marker, time in 24 Hr fmt, miliseconds
  // also included
  fd.getFormattedDate("dd/MMMMM/yyyy GGG HH:mm:ss:SSS a");
  // Only time like 21:52:14:096 PM
  // in 24 hr format, with mili seconds and AM/PM marker
  fd.getFormattedDate("HH:mm:ss:SSS a");

 }
 
 public void getFormattedDate(String pattern){
  Date today;
  String result;
  SimpleDateFormat formatter;
  // Creating the date format using the given pattern
  formatter = new SimpleDateFormat(pattern);
  // Getting the date instance
  today = new Date();
  // formatting the date
  result = formatter.format(today);
  System.out.println("Pattern: " + pattern + 
    " Formatted Date - " + result);
 }

}

Output

Pattern: EEE, MMM d, ''yy Formatted Date - Sun, May 8, '16
Pattern: EEEE, MMMM dd, yyyy Formatted Date - Sunday, May 08, 2016
Pattern: MM/dd/yyyy Formatted Date - 05/08/2016
Pattern: dd/MM/yyyy Formatted Date - 08/05/2016
Pattern: yyyy-MM-dd G 'at' hh:mm:ss z Formatted Date - 2016-05-08 AD at 10:13:46 IST
Pattern: dd/MMMMM/yyyy GGG HH:mm:ss:SSS a Formatted Date - 08/May/2016 AD 22:13:46:090 PM
Pattern: HH:mm:ss:SSS a Formatted Date - 22:13:46:092 PM

Symbols used for creating the pattern

Symbol Meaning Presentation Example
G era designator Text AD
y year Number 2009
M month in year Text & Number July & 07
d day in month Number 10
h hour in am/pm (1-12) Number 12
H hour in day (0-23) Number 0
m minute in hour Number 30
s second in minute Number 55
S millisecond Number 978
E day in week Text Tuesday
D day in year Number 189
F day of week in month Number 2 (2nd Wed in July)
w week in year Number 27
W week in month Number 2
a am/pm marker Text PM
k hour in day (1-24) Number 24
K hour in am/pm (0-11) Number 0
z time zone Text Pacific Standard Time
' escape for text Delimiter (none)
' single quote Literal '

Date Format Pattern Syntax

The number of symbol letters you specify also determines the format.

As exp. symbol for which the presentation style is text if length is 1-3 then abbreviated form is used if length is >= 4 then full form is used. In the above code it can be seen when 'EEE' is given it shows SUN as the day of the week, when 'EEEE' is given then Sunday is displayed.

Same way for month for which presentation style is text/number if length is 1-2 then number form is used when length is 3 (or more) then text form is used.

Source : https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html

That's all for this topic How to format date in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to find last modified date of a file in Java
  2. Reading file in Java using BufferedReader
  3. How to sort arraylist of custom objects in Java
  4. How to Sort elements in different order in TreeSet using Comparator
  5. How to read file from the last line in Java

You may also like -

>>>Go to Java Programs page