Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, 13 June 2018

Difference between == and equals in Java



 The == operator compares two objects to determine if they are the same object in memory i.e.
present in the same memory location. It is possible for two String objects to have the same value,
but located in different areas of memory.

== compares references while .equals compares contents. The method public boolean
equals(Object obj) is provided by the Object class and can be overridden. The default
implementation returns true only if the object is compared with itself, which is equivalent to the
equality operator == being used to compare aliases to the object. String, BitSet, Date, and File
override the equals() method. For two String objects, value equality means that they contain the
same character sequence. For the Wrapper classes, value equality means that the primitive
values are equal.

Sample Program:-


 public class SampleProgram {  
      public static void main(String[] args) {  
           String s1 = "abc";  
           String s2 = s1;  
           String s5 = "abc";  
           String s3 = new String("abc");  
           String s4 = new String("abc");  
           System.out.println("== comparison : " + (s1 == s5));  
           System.out.println("== comparison : " + (s1 == s2));  
           System.out.println("Using equals method : " + s1.equals(s2));  
           System.out.println("== comparison : " + s3 == s4);  
           System.out.println("Using equals method : " + s3.equals(s4));  
      }  
 }  

Output:-


 == comparison : true  
 == comparison : true  
 Using equals method : true  
 false  
 Using equals method : true  

Enjoy Learning.

Monday, 11 June 2018

Fibonacci series using recursion in java


Sample Program:-


 public class SampleProgram {  
      public static void main(String[] args) {  
           int n = 5;  
           System.out.print("Fibonacci Series: 0 1 ");  
           for (int i = 2; i <= n; i++) {  
                System.out.print(fibonacciRecursion(i) + " ");  
           }  
      }  
      private static int fibonacciRecursion(int n) {  
           if (n == 1 || n == 2) {  
                return 1;  
           }  
           return fibonacciRecursion(n - 1) + fibonacciRecursion(n - 2);  
      }  
 }  

Output:-


 Fibonacci Series: 0 1 1 2 3 5   

Enjoy Coding.

Sum of digits in number using recursion in java



Sample Program:-


public class SampleProgram {  
      static int sum = 0;  
      public static void main(String[] args) {  
           int number = 1234;  
           System.out.println("sum of digits : " + sumOfDigits(number));  
      }  
      private static int sumOfDigits(int number) {  
           if (number == 0) {  
                return sum;  
           } else {  
                sum = sum + (number % 10);  
                sumOfDigits(number / 10);  
           }  
           return sum;  
      }  
 }  

Output:-


 sum of digits : 10  

Enjoy Coding.

Tuesday, 29 May 2018

Find index in an array such that sum of left elements is equal to sum of right in Java



Sample Program:-


 public class SampleProgram {  
      public static void main(String[] args) {  
           int ar[] = { 2, 4, 4, 1, 1 };  
           int leftIndex = 0, rightIndex = ar.length - 1;  
           int leftSum = 0, rightSum = 0;  
           while (leftIndex <= rightIndex) {  
                if (leftSum > rightSum)  
                     rightSum = rightSum + ar[rightIndex--];  
                else  
                     leftSum = leftSum + ar[leftIndex++];  
           }  
           if (leftSum == rightSum)  
                System.out.println("Index is:" + (rightIndex + 1));  
           else  
                System.out.println("index Not Found");  
      }  
 }  

Output:-


Index is:2  

Enjoy Coding.

Find two maximum numbers in array



Sample Program:-


public class MaxtwoNumbers {  
      public static void main(String[] args) {  
           int a[] = { 6, 99, 45, 3, 77 };  
           int max1 = 0;  
           int max2 = 0;  
           for (int i = 0; i < a.length; i++) {  
                if (a[i] > max1) {  
                     max2 = max1;  
                     max1 = a[i];  
                } else if (a[i] > max2) {  
                     max2 = a[i];  
                }  
           }  
           System.out.println("Maximum 2 numbers are:" + max1 + " and " + max2);  
      }  
 }  

Output:-


Maximum 2 numbers are:99 and 77  

Enjoy Coding.

Monday, 28 May 2018

Find sum of all even digits in String




Sample Program:-


public class SumOfAllEven {  
      public static void main(String[] args) {  
           String s = "1j2a3v4a0";  
     char ch[] = s.toCharArray();  
     int sum = 0;  
     for (int i = 0; i < ch.length; i++) {  
         try {  
            int x = Integer.valueOf(String.valueOf(ch[i]));  
            if (x % 2 == 0) {  
               sum += x;  
            }  
         } catch (Exception e) {  
         }  
     }  
     System.out.println(sum);  
      }  
 }  



Output:-


 6  


Explanation:-

Suppose we have String s="java232";
Output for this will be 2+2=4

Enjoy Coding.

Find Missing numbers between 1 to 100 in sorted array in java



Sample Program:-


 public class MissingNumber {  
      public static void main(String[] args) {  
           int arr[] = { 2, 11, 55, 77, 88, 99 };  
           System.out.println("Given Array: ");  
           for (int j = 0; j < arr.length; j++)  
                System.out.print(arr[j] + " ");  
           System.out.println("\nNumbers missing between 1 to 100 in array:-");  
           int j = 0;  
           for (int i = 1; i <= 100; i++) {  
                if (j < arr.length && i == arr[j])  
                     j++;  
                else  
                     System.out.print(i + " ");  
           }  
      }  
 }  

Output:-


Given Array:
2 11 55 77 88 99
Numbers missing between 1 to 100 in array:-
1 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 78 79 80 81 82 83 84 85 86 87 89 90 91 92 93 94 95 96 97 98 100

Enjoy Coding.

Difference between Set and List




List
Set
Insertion Order
List maintains insertion order in which element are added.
Most of the Set implementation does not maintains an insertion order.
For ex:HashSet.
LinkedHashSet does maintain insertion order.
TreeSet are sorted by natural order.
Duplicate
Allows to store duplicate elements in java.
Does not allow duplicate elements.
Null Keys
Allow to store any number of null values.
Most of the Set implementation only allow one null values.

Tree Set does not allow any null value.
Implementing Classes
ArrayList,Linkedlist,Vector etc.
HashSet,LinkedHashSet,TreeSet etc.
Structure
List are resizable array.
Set uses map for their internal implementation.
Index based
List are index based structure. Hence element can be retrieved based on index.
Set is not index based collection.


Enjoy Reading.


Java Program to print Reverse pyramid


Pyramid Sample:-

12345
1234
123
12
1

Sample Program:-


public class ReversePyramid {  
      public static void main(String[] args) {  
           for (int i = 5; i > 0; i--) {  
                for (int j = 0; j < i; j++) {  
                     System.out.print(j + 1);  
                }  
                System.out.println("");  
           }  
      }  
 }  

Output:-
 12345  
 1234  
 123  
 12  
 1  

Enjoy Coding.

Java Program to print Pyramid of stars using nested for loops



Pyramid Example:-

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

Sample Program:-


public class JavaPyramid {  
      public static void main(String[] args) {  
           for (int i = 1; i <= 5; i++) {  
                for (int j = 0; j < i; j++) {  
                     System.out.print("*");  
                }  
                System.out.println("");  
           }  
      }  
 }  

Output:-


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

Enjoy Programming.

Java Program to Count all distinct pairs with difference equal to k


Given an integer array and a positive integer k, count all distinct pairs with difference equal to k.

Example:-

arr[]:-{1, 5, 3, 4, 2}, k = 3
Output: 2
2 pairs({1, 4} and {5, 2}) with difference equal to 3.

Sample Program:-

package com.shc.ecom.payment.web.rest;  
 /**  
  * @author sdixit  
  *  
  */  
 public class Example {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int arr[] = { 1, 5, 3, 4, 2 };  
           int k = 3;  
           System.out.println("Count of pairs :-" + countPairsWithDiffK(arr, k));  
      }  
      private static int countPairsWithDiffK(int[] arr, int k) {  
           int count = 0;  
           int n = arr.length;  
           for (int i = 0; i < n; i++) {  
                for (int j = i + 1; j < n; j++)  
                     if (arr[i] - arr[j] == k || arr[j] - arr[i] == k)  
                          count++;  
           }  
           return count;  
      }  
 }  


Sample Output:-
 Count of pairs :-2  

Enjoy Programming.

Tuesday, 29 August 2017

Java program to check unique number


Sample Program:-


 import java.util.*;  
 import java.io.*;  
 /**  
  * Created by Dixit on 29-08-2017.  
  */  
 public class IsUniqueNumber {  
   public static boolean  
   isUniqueUsingHash(String word)  
   {char[] chars = word.toCharArray();  
     Set<Character> set = new HashSet<Character>();  
     for (char c : chars)  
       if (set.contains(c))  
         return false;  
       else {  
         set.add(c);  
       }  
     return true;  
   }  
   public static boolean  
   isUniqueUsingSort(String word)  
   {char[] chars = word.toCharArray();  
     if (chars.length <= 1)  
       return true;  
     Arrays.sort(chars);  
     char temp = chars[0];  
     for (int i = 1; i < chars.length; i++)  
     {if (chars[i] == temp)  
       return false;  
       temp = chars[i];  
     }  
     return true;  
   }  
   public static void main(String[] args)  
       throws IOException  
   {  
     System.out.println(isUniqueUsingHash("1234")? "Unique" : "Not Unique");  
         System.out.println(isUniqueUsingSort("123")? "Unique" : "NotUnique");  
   }  
 }  


Enjoy Coding

Sunday, 20 August 2017

Interesting facts of Java


Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suite various types of platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.
Java is:
  • Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
  • Platform independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.
  • Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java would be easy to master.
  • Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.
  • Architectural-neutral: Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence of Java runtime system.
  • Portable: Being architectural-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary which is a POSIX subset.
  • Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.
  • Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications.
  • Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process.
  • High Performance: With the use of Just-In-Time compilers, Java enables high performance.
  • Distributed: Java is designed for the distributed environment of the internet.
  • Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

Enjoy Learning.

Thursday, 22 June 2017

Log4j

Log4j is a Reliable, Fast and Flexible Logging Framework (APIs) written in Java which is distributed under the Apache Software License. Log4j is highly configurable through external configuration files at runtime. It views the logging process in terms of levels of priorities and offers mechanisms to direct logging information to a great variety of destinations, such as a database, file, console, UNIX Syslog etc.
Log4j has three main components:
  • loggers: Responsible for capturing logging information.
  • appenders : Responsible for publishing logging information to various preferred destinations.
  • layouts: Responsible to format logging information in different styles.
log4j Features:
  • log4j is thread-safe.
  • log4j supports multiple output appenders per logger.
  • log4j supports internationalization.
  • Logging behavior can be set at runtime using a configuration file.
  • log4j is designed to handle Java Exceptions from the start.
  • log4j uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
  • The format of the log output can be easily changed by extending the Layout class.
Logging Methods:
Once we obtain an instance of a named logger, we can use several methods of the logger to log messages. The Logger class has the following methods for printing the logging information.
public void debug(Object message)
This method prints messages with the level Level.DEBUG.
public void error(Object message)
This method prints messages with the level Level.ERROR.
public void fatal(Object message);
This method prints messages with the level Level.FATAL.
public void info(Object message);
This method prints messages with the level Level.INFO.
public void warn(Object message);
This method prints messages with the level Level.WARN.
public void trace(Object message);
This method prints messages with the level Level.TRACE.
All the levels are defined in the org.apache.log4j.Level class and any of the above mentioned method can be called as follows:
import org.apache.log4j.Logger;  
 public class LogClass {  
  private static Logger log = Logger.getLogger(LogClass.class);  
  public static void main(String[] args) {  
   log.trace("Trace Message!");  
   log.debug("Debug Message!");  
   log.info("Info Message!");  
   log.warn("Warn Message!");  
   log.error("Error Message!");  
   log.fatal("Fatal Message!");  
  }  
 }  
When you compile and run LogClass program it would generate following result:

 Debug Message!   
 Info Message!   
 Warn Message!   
 Error Message!   
 Fatal Message!  
log4j - Log Formatting:
Apache log4j provides various Layout objects, each of which can format logging data according to various layouts. It is also possible to create a Layout object that formats logging data in an application-specific way
The Layout Types:
The top-level class in the hierarchy is the abstract class org.apache.log4j.Layout. This is the base class for all other Layout classes in the log4j API.
The Layout class is defined as abstract within an application, we never use this class directly; instead, we work with its subclasses which are as follows:
  • DateLayout
  • HTMLLayout
  • PatternLayout.
  • SimpleLayout
  • XMLLayout
log4j - Sample Program:
Following is a simple configuration file created for our example.It has the following information:
  • The level of the root logger is defined as DEBUG and attaches appender named FILE to it.
  • The appender FILE is defined as org.apache.log4j.FileAppender and writes to a file named "log.out" located in the log directory.
  • The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.
So the content of log4j.properties file would be as follows:
# Define the root logger with appender file  
 log = /usr/home/log4j  
 log4j.rootLogger = DEBUG, FILE  
 # Define the file appender  
 log4j.appender.FILE=org.apache.log4j.FileAppender  
 log4j.appender.FILE.File=${log}/log.out  
 # Define the layout for file appender  
 log4j.appender.FILE.layout=org.apache.log4j.PatternLayout  
 log4j.appender.FILE.layout.conversionPattern=%m%n  
Using log4j in Java Program:
The following Java class is a very simple example that initializes, and then uses, the Log4J logging library for Java applications.
import org.apache.log4j.Logger;  
 import java.io.*;  
 import java.sql.SQLException;  
 import java.util.*;  
 public class log4jExample{  
  /* Get actual class name  to be printed on */  
  static Logger log =  Logger.getLogger(log4jExample.class.getName());  
  public static void main(String[] args) throws IOException,SQLException{  
   log.debug("Hello this is an debug message");  
   log.info("Hello this is an info message");  
  }  
 }  

Enjoy Reading :)

Wednesday, 14 June 2017

ConcurrentHashMap in Java

ConcurrentHashMap

ConcurrentHashMap in Java is introduced as an alternative of Hashtable in Java 1.5 as part of Java concurrency package.  Prior to Java 1.5 if you need a Map implementation, which can be safely used in a concurrent and multi-threaded Java program, then you only have Hashtable or synchronized Map because HashMap is not thread-safe.
With ConcurrentHashMap, not only it can be safely used in concurrent multi-threaded environment but also provides better performance over Hashtable and synchronizedMap. ConcurrentHashMap performs better than earlier two because it only locks a portion of Map, instead of whole Map, which is the case with Hashtable and synchronized Map. ConcurrentHashMap allows concurred read operations and same time, maintains integrity by synchronizing write operations.

How ConcurrentHashMap is implemented in Java

ConcurrentHashMap provided all functions supported by Hashtable with additional feature called "concurrency level", which allows ConcurrentHashMap to partition Map. ConcurrentHashMap allows multiple readers to read concurrently without any blocking. This is achieved by partitioning Map into different parts based on concurrency level and locking only a portion of Map during updates. Default concurrency level is 16. This means, 16 thread can operate on Map simultaneously, until they are operating on different part of Map. This makes ConcurrentHashMap high performance despite keeping thread-safety intact. Though, it comes with warning. Since update operations like put(), remove(), putAll() or clear() is not synchronized, concurrent retrieval may not reflect most recent change on Map.
Another important point to remember is iteration over CHM, Iterator returned by keySet of ConcurrentHashMap are weekly consistent and they only reflect state of ConcurrentHashMap and certain point and may not reflect any recent change. Iterator of ConcurrentHashMap's keySet area also fail-safe and doesn’t throw ConcurrentModificationExceptoin.

ConcurrentHashMap putifAbsent example in Java

Many times we need to insert entry into Map, if it’s not present already, and we wrote following kind of code:

synchronized(map){  
  if (map.get(key) == null){  
    return map.put(key, value);  
  } else{  
    return map.get(key);  
  }  
 }  

Though this code will work fine in HashMap and Hashtable, This won't work in ConcurrentHashMap; because, during put operation whole map is not locked, and while one thread is putting value, other thread's get() call can still return null which result in one thread overriding value inserted by other thread. Of course, you can wrap whole code in synchronized block and make it thread-safe but that will only make your code single threaded. ConcurrentHashMap provides putIfAbsent(key, value) which does same thing but atomically and thus eliminates above race condition.
Eg:
public class ConcurrentHashMapTest implements Runnable {  
     private String name;  
     private static Map<String,String> conpage=new ConcurrentHashMap<String,String>();  
     ConcurrentHashMapTest(String name){  
        conpage.put("1","A");  
        conpage.put("2","B");  
        conpage.put("3","C");  
        this.name=name;  
     }  
     public void run() {  
        try{  
            Iterator<String> it = conpage.keySet().iterator();  
            while(it.hasNext()){  
               String key=it.next();  
               conpage.put("A"+key, "A"+key);  
            }  
            System.out.println(name +" completed.");  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
     }  
     public static void main(String[] args) {  
        ExecutorService executor= Executors.newCachedThreadPool();  
        executor.execute(new ConcurrentHashMapTest("Thread one"));  
        Iterator<String> itt = conpage.keySet().iterator();  
        while(itt.hasNext()){  
            String key=itt.next();  
            System.out.println(conpage.get(key));  
        }  
        executor.execute(new ConcurrentHashMapTest("Thread two"));  
        Iterator<String> it = conpage.keySet().iterator();  
        while(it.hasNext()){  
            String key=it.next();  
            System.out.println(conpage.get(key));  
        }  
        executor.shutdownNow();  
     }     
 }  

Output-  
 A  
 C  
 B  
 Thread one completed.  
 A  
 A2  
 A1  
 A3  
 C  
 B  
 Thread two completed.  

When to use ConcurrentHashMap in Java

  • ConcurrentHashMap is best suited when you have multiple readers and few writers. If writers outnumber reader, or writer is equal to reader, than performance of ConcurrentHashMap effectively reduces to synchronized map or Hashtable.
  • ConcurrentHashMap is a good choice for caches, which can be initialized during application start up and later accessed my many request processing threads.
  • For those who have seen the green-box load jobs written in SpringBatch, many of the one-time populated Maps in beforeJob, whch are always read alone, are all ConcurrentHashMap ‘s.

Enjoy Learning :)

Eclipse and its Features

We work on Eclipse every day, but still we are not aware of all the powerful features of Eclipse. It provides a lot of shortcuts and other features which can help us in coding, debugging and other tasks, eventually delivering the bug free code in a lot lesser time.
Some of them are mentioned below and yet there are a lot more J 
Content Assist, Quick Fix and Class Navigation
Content assist
The content assistant allows you to get input help in an editor. It can be invoked by pressing CTRLSpace For example type syso in the editor of a Java source file and then press CTRLSpace. This will replace syso with System.out.println(""). If you have a reference to an object, for example the object person of the type Person and need to see it's methods, type person. and press CTRL+Space.
Quick Fix
Whenever Eclipse detects a problem, it will underline the problematic text in the editor. Select the underlined text and press CTRL1 to see proposals how to solve this problem. For example type myBoolean = true; If myBoolean is not yet defined, Eclipse will highlight it as an error. Select the variable and press CTRL1, Eclipse will suggest creating a field or local variable.
Quick Fix is extremely powerful. It allows you to create new local variables and fields as well as new methods and new classes. I can put try-catch statements around your exceptions. It can assign a statement to a variable and much more.
Opening a class
You can navigate between the classes in your project via the "Package Explorer" View. In addition you can open any class via positioning the cursor on the class in an editor and pressing F3. Alternatively, you can press CTRLShiftT. This will show a dialog in which you can enter the class name to open it.
Eclipse Shortcuts
Eclipse provides a lot of shortcuts to work efficiently with the IDE.
Table 1.  Navigation

Shortcut
Description
Ctrl + 2 + L
Assign statement to new local variable
Ctrl + 2 + F
Assign statement to new field
Table 4. Coding

Shortcut
Description
ALT + SHIFT + R
Rename
CTRL+2, R
Rename locally (in file), faster then ALT + SHIFT + R
ALT + SHIFT + T
Opens the quick refactoring menu
Table 6.  Handling the editor

Command
Description
F5
Goes to the next step in your program. If the next step is a method / function this command will jump into the associated code.
F6
F6 will step over the call, i.e. it will call a method / function without entering the associated code.
F7
F7 will go to the caller of the method/ function. This will leave the current code and go to the calling code.
F8
Use F8 to go to the next breakpoint. If no further breakpoint is encountered the program will run normally.

More Debugging Tips!!
  • If you want to temporary de-activate all your breakpoints you can press the button "Skip all breakpoints". This button is visible, if you select the "Breakpoints" tab. If you press this button again, your breakpoints will be reactivated.
    • After setting a breakpoint you can select the properties of the breakpoint, via right-click > Breakpoint Properties. You can define a condition that restricts when the breakpoint will become active.
    • watchpoint is a breakpoint set on a field. The debugger will stop whenever that field is read or changed.
    • You can set a watchpoint by double-clicking on the left margin, next to the field declaration. In the properties of a watchpoint you can define if the execution should stop during read access (Field Access) and during write access (Field Modification).
    • You can also set breakpoints which are triggered when exceptioins are thrown. To define an exception breakpoint click on the "Add Java Exception Breakpoint" icon in the "Breakpoints" View toolbar.
    • A method breakpoint is defined by double-clicking in the left margin of the editor next to the method header. You can define if you want to stop the program before entering or after leaving the method.
    • A Class Load Breakpoint will stop when the class is loaded. To set a class load breakpoint, right-click on a class in the Outline View and choose "Toggle Class Load Breakpoint".
For every breakpoint you can define a hit count in it's properties. The application is stopped once the breakpoint is reached the number of times defined in the hit count.

Templates
If you have to frequently type the same code / part of the document, you can create templates which can be activated via autocomplete (Ctrl + Space).
For example, assume that you are frequently creating public void name(){} methods. You could define a template which creates the method body for you.
To create a template for this, select the menu Window > Preferences > Java > Editor > Templates.



Press New. Create the template shown in the following screenshot.


cursor indicates that the cursor should be placed at this position after applying the template.
In this example the name "npm" is your keyword. Now every time you type "npm" in the Java editor and press CTRL+Space the system will allow you to replace your keyword with your template. 
 Automatic placement of semicolon
Eclipse can make typing more efficient by placing semicolons at the correct position in your source code.
In the Preference setting select Java > Editor > Typing. In the section "Automatically insert at correct position”, enable the "Semicolons" checkbox. You can now type a semicolon in the middle of your code and Eclipse will position it at the end of the current statement.



Enjoy Learning :)

Wednesday, 24 May 2017

Java program to create singleton class


Java Singleton design pattern is one of the design patterns that manages the instantiation of an object
This design pattern suggests that only one instance of a Singleton object is created by the JVM.
This pattern is useful when exactly one object is needed to coordinate actions across the system.

For example, you can use it to create a connection pool. It’s not good to create a new connection every time a program needs to write something to a database; instead, a connection
or a set of connections that are already a pool can be instantiated using the Singleton pattern.

Example Class that follows Singleton Pattern.

public class SingletonExample {  
   private static SingletonExample INSTANCE = new SingletonExample ();  
   //Marking default constructor private;  
   //to avoid direct instantiation.  
   private SingletonExample () {  
   }  
   //Get instance for class SingletonExample  
   public static SingletonExample getInstance() {  
    return INSTANCE;  
   }  
 }  

In above code snippet, we have declared a static object reference to SingletonExample class called INSTANCE and is returned every time getInstance() is called.

  • In in a multi-threaded environment ,sometimes when two or more threads enter the method getInstance() at the same time before Singleton instance is not created, will result into simultaneous creation of two objects.

Such problems can be avoided by defining getInstance() method synchronized.

public static synchronized SingletonExample getInstance() { }  


Enjoy Learning.

Important SDET(Software Development Engineer Testing) Interview Question

                  Important SDET(Software Development Engineer Testing) Interview Question

QA
  1. Explain life cycle of a bug
  2. What is regression testing? How is it different from functional testing?
  3. Difference between whitebox and black box testing
  4. What is A/B testing?
  5. What is smoke testing? Difference with Sanity testing?
  6. How can we perform credit card authorization testing?
  7. How do we test a multi channel application? Especially when the integration points are not in place with downstream systems?
  8. What is end to end testing?
  9. How can we test a webservice?
  10. How can we form a request in Jmeter, hit a service and read the response?
  11. Difference between unit, integration and QA testing
  12. What is included in a test plan?
  13. what is boundary analysis with an example
  14. What is negative testing? Create 5 negative  test cases for email validation
  15. What is backend testing?
  16. How do you perform XML validation?
  17. What are the basic elements you put down while reporting a bug?
  18. Create 5 test cases for placing an order in an ecommerce website using PayPal as payment type
  19. Write 5 P1 test cases for shopping cart on an ecom website.
  20. Write 5 P1 testcases for a user profile page on an ecom website.
  21. Write 5 P1 test cases for a Ship confirmation email sent from an ecom website to a customer
Mobile
  1. What are the different types of apps ?
  2. What is the difference between Native and Hybrid app
  3. How can app be installed on IOS devices?
  4. What are the app formats for IOS and Android
  5. What is the difference between Desktop and mobile testing
  6. How to install local IOS and Android builds to device
  7. Mention what are the common bugs found while mobile testing
  8. What is the approach to test different screen size
  9. What is the approach to test different device/OS version
DB (Exact queries are not needed in answers. A high level approach will do)
  1. In an EMPLOYEE table having EMPLOYEE ID and DEPT ID, find department with max employees
  2. CASE..WHEN..THEN statement in SQL
  3. Write a query to find salary of an employee using join between EMPLOYEE and SALARY tables
  4. Difference between innerjoin and outerjoin
  5. PL/SQL – high level
  6. Explain trigger and its difference between a PL/SQL
  7. Nosql vs RDBMS, with an example
  8. Is it possible to have primary key and foreign key in mongo db
  9. How to find data in a mongodb collection
  10. Find state with max stores in a STORES table (with the columns - store id, storename, city, state, zip)
  11. How to ensure that child records are deleted when parent with foreign key constraint is deleted
  12. Difference between truncating and deleting a table
  13. Query to find number of records in a table
  14. Possible to have more than one column as primary key?
  15. Difference between WHERE and HAVING clauses
  16. What is difference between count(1) and count(*).
  17. Find number of non-null records in a column
  18. Find number of null records in a column

UNIX (exact syntaxes are not required. Keywords would be enough)
  1. Unix commands for :
    1. changing directories
    2. listing files
    3. finding keywords in a file
    4. changing file permissions
    5. tailing
    6. Create a shell script to display a menu to a user
    7. Get current directory
    8. Find keyword in a file
    9. List files starting with the word Sears in a directory
    10. Find wordcount in a file
    11. Schedule a shell script to run every 30 seconds
    12. How to connect to a unix server from another unix server
    13. Difference between ftp and scp
    14. How to find a string from a set of files?
    15. How to find files which are modified 15 mins before?
    16. How to list all running processes in a server and stop it?
    17. Finding file names which start with the letter A in a directory
JAVA
  1. How to convert json to a hashmap
  2. Explain how to implement multi-threading
  3. Explain race condition and how to avoid it
  4. Diff between string, string buffer and string builder
  5. Difference between hashmap, hashtable, concurrent hashmap and treemap
  6. Possible to have duplicate key in a hashmap? Explain
  7. Execute a query and get the results of the query into a hashmap with column names as the keys and column values as the values
  8. Explain class casting
  9. Explain polymorphism and encapsulaiton
  10. Sort an arraylist
  11. Sort a map with integer as keys and string as values based on length of its values
  12. Difference between abstract class and interface
  13. Difference between final, finalize and finally
  14. What happens when a line of code in finally block has an exception?
  15. What is an iterator? Where can it be used?
  16. What is a Set? How is it different from arraylist?
  17. Mail contents of a file using java
  18. How is hashmap different from an array list?
  19. Difference between hashmap and treemap?
  20. How would you read a file and write to a new file?
  21. Explain try-catch logic?
  22. What is Finally block? You are executing a try block, with no exceptions. Will it go to finally?
  23. Why do we need getters and setters?
  24. How to iterate through a hashmap
  25. How to find common elements between 2 array lists

SELENIUM
  1. How to handle popups in selenium?
  2. What is Page Object Model (POM) & Page Factory in Selenium?
  3. What are the differenttypes of wait and when to use what?
  4. What are the operating systems and browsers supported by Selenium?
  5. What is the default port for Selenium and can it be customized?
  6. What is the use of Capabilities class?
  7. What is the difference between Remote Webdriver and Webdriver?
  8. How to use JavaScript with Selenium WebDriver using Java?
  9. What is the diffrence between assert and verify?
  10. What are the different types of locators in Selenium and which one is preferred?
PROBLEM SOLVING 
  1. Open file containing alphanumeric phone numbers, convert them to numbers ((eg: 1-800-GO-PIZZA to 18004674992)and write them to a different text file
  2. Find difference between two text files which have data similar in structure
  3. You have Order Items table and orders table. Orderitems table could have many records for an order. How to find the orders that have exactly 2 items in them? OrderId is the foreign key in orderitems table.
  4. Find duplicate numbers in a Textfile with 20000 six digit numbers. On finding duplicates, write them in another textfile with number of occurances.
  5. Find missing number from an array that is supposed to contain 1-100 numbers
MISC 
  1. Difference between RESTful service and SOAP service
  2. Schedule an executable jar to run every 30 seconds in a Windows server
  3. Using regular expession, find $ amount in a string which appears after the $ character
  4. What is continuous integration?
  5. Convert xml to json?