Saturday, 28 June 2014

What is Dependency Injection in Spring ? Explain types and advantages with examples

             Spring uses inversion of control to satisfy dependencies between objects. Traditional approach before Spring framework was to hard code the dependencies and this creates tightly coupled code and there was no easy way to change that. People used to minimize this tight coupling, by resorting to ” programming to an interface and not to an implementation”, but even with that approach, the actual creation of the dependent object was the responsibility of the calling piece of code. Of course there were custom frameworks being developed by various individuals to create some form of  inversion of control to achieve dependency injection ( DI). 

            The basic concept of the Inversion of Control pattern  is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. In a typical IOC scenario, the container creates all the objects, wires them together by setting the necessary properties, and determines when methods will be invoked.  
    
        There are two types of DI,

  • Setter Injection
  • Constructor Injection                                                                 

Setter Injection:-

    Spring framework will inject the dependency via a setter method.
XML configuration for setter Dependency Injection is below.

  <bean id="classBean" class="com.adnjava.ClassBean">
     <!-- setter injection using the nested <ref/> element -->
       <property name="studentBean"><ref bean="studentBean"/></property>
  </bean>
  <bean id="studentBean" class="com.adnjava.StudentBean"/> 

         The ClassBean java POJO class is as below,

 package com.adnjava;

  public class ClassBean {

       private StudentBean studentBean;

       public void setStudentBean(StudentBean studentBean){
           this.studentBean=studentBean;
       }

       public void getStudentBean(){
             return studentBean;
       }
 }

             

 Constructor Injection:-


          Here Spring uses the  Constructor and the arguments passed to it to determine the dependency. Rest all is same as setter injection.
     
      XML configuration for
Constructor Dependency Injection is below.


  <bean id="classBean" class="com.adnjava.ClassBean">
       <constructor-arg><ref bean="studentBean"/></constructor-arg>
      <!--OR you can use <constructor-arg ref="yetAnotherBean"/>-->
  </bean>
  <bean id="studentBean" class="com.adnjava.StudentBean"/>  

         The ClassBean java POJO class is as below,

 package com.adnjava;
  
  public class ClassBean {

         private StudentBean studentBean;

         public ClassBean(StudentBean studentBean){
              this.studentBean=studentBean;
         }

         public void getStudentBean(){
               return studentBean;
         }
  }


              Interface Injection:

             This is not implemented in Spring currently, but by Avalon. It’s a different type of DI that involves mapping items to inject to specific interfaces.

                    

Advantages Of Dependency Injection:

  • Loosely couple code
  • Separation of responsibility
  • Configuration and code is separate.
  • Using configuration, you can provide implemented code  without changing the dependent code.
  • Testing can be performed using mock objects.

Related Post:--
Spring MVC workflow with example  
Spring MVC with Hibernate CRUD Example  
Spring Annotations  

Friday, 27 June 2014

Explain bean life cycle in Spring

            Spring framework is based on IOC(Inversion Of Control) so we call it as IOC container also Spring beans reside inside the IOC container. Spring beans are nothing but Plain Old Java Object (POJO).

Following steps explain their life cycle inside the container.
    
1)  Container will look the bean definition inside configuration file (e.g. bean.xml).
     
2)  Using Reflection API container will create the object and if any property is defined inside the bean definition then it will also be set.
   
3 If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.

4 If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.


5 If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called before the properties for the Bean are set.

    
6 If an init() method is specified for the bean, it will be called.

7 If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the bean reference.

     
8 If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in the Bean class will be called.

Sunday, 22 June 2014

Why Map interface doesn't extend Collection interface?

          In previous post, discussed about collection hierarchy and what are the collection framework interfaces and classes. In the current post, will have discussion about why map interface doesn't inherits Collection interface as we know that map is also a part of Collection framework.     

As we know that Map is key and value pair, but collection is a "group of elements". In Map doesn't have elements, instead of elements it has key and value pair. It doesn't fit in to Collection concept.    

Map interface and it’s implementations are part of Collections Framework, Map are not collections and collections are not Map. Hence it doesn’t make sense for Map to extend Collection or vice versa.



Related Posts:--
1) How HashMap works internally in Java?
2) Internal Implementation of TreeMap in Java
3) Internal implementation of ArrayList in Java
4) Collection Interview Questions and Answers in Java
5) Internal Implementation of LinkedList in Java
6) Collection Hierarchy in Java

Saturday, 21 June 2014

Singleton Design Pattern in java with example

        In this post, we will learn about Singleton design pattern principles, different ways to implement Singleton and some of the best practices for it’s usage.

       Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. 

       Singleton pattern is used for logging, drivers objects, caching and thread pool. Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc.

   To implement the Singleton Design Pattern,you do the following the things,
  1) private constructor - no other class can instantiate a new object.
  2) private reference - no external modification.
  3) public static method is the only place that can get an object.

 Below are the different approaches of Singleton pattern implementation and design.

Eager initialization

           In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client application might not be using it.

Here is the implementation of static initialization singleton class.    

  public class EagerInitializer{
        
        private static final EagerInitializer instance = new EagerInitializer();

        //private constructor to avoid client applications to use constructor.
        private  EagerInitializer(){
        }
        public static EagerInitializer getInstance(){
              return instance;
        }
  }

           If your singleton class is not using a lot of resources, this is the approach to use. But in most of the scenarios, Singleton classes are created for resources such as File System, Database connections etc and we should avoid the instantiation until unless client calls the getInstance method. Also this method doesn’t provide any options for exception handling.

Static block initialization

           Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling

 public class StaticInitializer {
        private static StaticInitializer instance ;
        //private constructor to avoid client applications to use constructor.
        private  StaticInitializer() {
        }
        static {
             try {
                 instance = new StaticInitializer();
             } catch(Exception e) {
                     throw new RuntimeException("Exception in static block");
             }
        }
        public static StaticInitializer getInstance() {
               return instance;
        }
 }

         Both eager initialization and static block initialization creates the instance even before it’s being used and that is not the best practice to use. So in further sections, we will learn how to create Singleton class that supports lazy initialization.

Lazy Initialization

           Lazy initialization method to implement Singleton pattern creates the instance in the global access method. Here is the sample code for creating Singleton class with this approach.


  public class LazyInitializer{

        private static LazyInitializer instance;

        //private constructor to avoid client applications to use constructor.
        private  LazyInitializer(){
        }
        public static LazyInitializer getInstance(){
              if(instance == null){
                       instance = new LazyInitializer();
              }
              return instance;
        }
  }

       The above implementation works fine incase of single threaded environment but when it comes to multithreaded systems, it can cause issues if multiple threads are inside the if loop at the same time. It will destroy the singleton pattern and both threads will get the different instances of singleton class. In next section, we will see different ways to create a thread-safe singleton class.

Thread Safe Singleton

       The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class.


  public class ThreadSafe{

        private static ThreadSafe instance ;
                        
        //private constructor to avoid client applications to use constructor.
        private  ThreadSafe(){
        }

        public static synchronized ThreadSafe getInstance(){
               if(instance == null){
                     instance = new ThreadSafe();
               }
               return instance;
         }
  }

        Above implementation works fine and provides thread-safety but it reduces the performance because of cost associated with the synchronized method, although we need it only for the first few threads who might create the separate instances (Read: Java Synchronization). To avoid this extra overhead every time, double checked locking principle is used. In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of singleton class is created.

           Below code snippet provides the double checked locking implementation

                 public static ThreadSafe getInstance(){
                          if(instance == null){
                                    synchonized(ThreadSafe.class){
                                             if(instance == null ){
                                                      instance = new ThreadSafe();
                                             }
                                     }
                           }
                           return instance;
                 }

                      Real time Examples for Singleton Design Pattern:---

JDBC Example using Singleton Design pattern:--

         We write a class (ConnectionFactory) which implements singleton pattern defining database connection configuration statements and methods to make connection to the database. Reason for making this class as singleton is, we can create one object of this class and can create many Connection objects (one factory, many objects).
package com.adnjavainterview;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {
           //static reference to itself
         private static ConnectionFactory instance = new ConnectionFactory();
         public static final String URL = "jdbc:mysql://localhost/jdbcdb";
         public static final String USER = "YOUR_DATABASE_USERNAME";
         public static final String PASSWORD = " YOUR_DATABASE_PASSWORD";
         public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
              //private constructor
         private ConnectionFactory() {
                 try {
                        Class.forName(DRIVER_CLASS);
                  }
                  catch (ClassNotFoundException e) {
                        e.printStackTrace();
                  }
         }
    
         private Connection createConnection() {
                   Connection connection = null;
                   try {
                          connection = DriverManager.getConnection(URL, USER, PASSWORD);
                   }
                   catch (SQLException e) {
                           System.out.println("ERROR: Unable to Connect to Database.");
                   }
                   return connection;
         } 
    
         public static Connection getConnection() {
                 return instance.createConnection();
         }
 }

Thank you for visiting blog..

Related Post:--

Thursday, 19 June 2014

Why set interface doesn't allows duplicates in java?

       If you are having 3+ yrs Of experience then some interviewer will ask this question. Actually interviewer will test for how set internally works in java.
    
       Internally SET store element using HashMap . HashMap is a structure of Key value pairs, but in set there is no key and value pair. Here what the values passed by the Set is treated as Keys of HashMap Internally. As we know that keys are unique cannot be duplicated. HashMap value as constant every time. That is the reason if you pass any duplicate value it return false and does not added to the Set.
       If the adding element return true it will added into Set Else it return False, that why it won't give any compilation or run time error and it wont be added to Set




Related Posts:--
1) How HashMap works internally in Java?
2) Internal Implementation of TreeMap in Java
3) Internal implementation of ArrayList in Java
4) Collection Interview Questions and Answers in Java
5) Internal Implementation of LinkedList in Java
6) Collection Hierarchy in Java

Wednesday, 18 June 2014

What is difference between web-server and application server?

1.Application server may contain Webserver but webserver does not contain Application Server.

2. Webserver deals with HTTP and HTTPS protocals,but Application Server deals any type of protocals.

3.Webserver receives request and sends back response as HTML pages, where as Application Server manages enterprise java objects whether they are servlets, JMS listeners and EJB objects.

Monday, 16 June 2014

What is marker interface in Java? Why need marker interface?

           Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface. Example of marker interface is Serializable, Cloneable and Remote interface. Now if marker interface doesn't have any field or method or behavior then why would Java needs  it?



      Why Marker or Tag interface do in Java:--


1) Looking carefully on marker interface in Java e.g Serializable,Cloneable and Remote, it looks they are used to indicate something to compiler or JVM.
           So if JVM sees a Class is Serializable it done some special operation on it, similar way if JVM sees one Class is implement Cloneable it performs some operation to support cloning. Same is true for RMI and Remote interface. So in short, Marker interface indicate signal or a command to Compiler or JVM.
          This is pretty standard answer of question about marker interface and once you give this answer most of the time interviewee definitely asked "Why this indication can not be done using flag inside a class?" this make sense right? Yes this can be done by using a boolean flag or a String but doesn't marking a class like Serializable or Cloneable makes it more readable and it also allows to take advantage of Polymorphism in Java.


   Where Should I use Marker interface in Java :--


           Apart from using built in marker interface for making a class Serializable or Cloneable. One can also develop his own marker interface. Marker interface is a good way to classify code. You can create marker interface to logically divide your code and if you have your own tool than you can perform some pre-processing operation on those classes. Particularly useful for developing API and framework like Spring or Struts.
         After introduction of Annotation on Java5, Annotation is better choice than marker interface and JUnit is a perfect example of using Annotation e.g @Test for specifying a Test class. Same can also be achieved by using Test marker interface.


      Another use Of Marker Interface in Java:


           One more use of marker interface in Java can be commenting. A marker interface called Thread Safe can be used to communicate other developers that classes implementing this marker interface thread-safe guarantee and any modification should not violate that.  Marker interface can also code coverage or code review tool to find bugs based on specified behavior of marker interfaces. Again Annotations  are better choice @ThreadSafe looks lot better than implementing ThreadSafe marker interface.

A common question asked very frequently is about Runnable interface being marker or not.?

       Runnable interface is not marker because Runnable interface has the public void run() method declared inside it.

   One common question asked is if we can create a marker interface or not and the answer is yes because of following reason:
           We can't create marker interface similar to Serializable or Cloneable but we can simulate the functionality by writing extra code around the custom marker interface.

            In summary marker interface in Java is used to indicate something to compiler, JVM or any other tool but Annotation is better way of doing same thing.

Why character array is preffered to store Password than String?


        Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. Since any one who has access to memory dump can find the password in clear text and that's another reason you should always used an encrypted password than plain text. Since Strings are immutable there is no way contents of Strings can be changed because any change will produce new String, while if you char[] you can still set all his element as blank or zero. So Storing password in character array clearly mitigates security risk of stealing password.

        With Strings there is always a risk of printing plain text in a log file or console  but if use Array you won't print contents of the array instead its memory location get printed, though not a real reason but make but still make sense.
      For Example,
                            class PassCharArrEx {
                                   public static void main(String args[]) {
                                           String pass = "password_of_blog";
                                           System.out.println("String="+pass);
                                           char chpass[] = "password_of_blog".toCharArray();
                                           System.out.println("Character="+chpass);
                                    }
                            }
Output :
                    String=password_of_blog
                    Character=$%(Q($_#(QQ#


How HashMap works internally in Java?

                One of the most important question of the core java interviewers is How hash map works in java or internal.implementation of hashmap. Most of the candidates rejection chances increases if the candidate do not give the satisfactory explanation . This question shows that candidate has good knowledge of Collection . So this question should be in your to do list before appearing for the interview .
                 HashMap works on the principle of Hashing .  To understand Hashing , we should understand the three terms first   i.e  Hash Function , Hash Value and Bucket .

     What is Hash Function , Hash Value  and Bucket ?


         The hashCode() function  which returns an integer value is the Hash function. The important point to note that ,  this method is present in Object class ( Mother of all class ) .
       
        This is the code for the hash function(also known as hashCode method) in Object Class :

    public native int hashCode();

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

      What is bucket ?

           
          A bucket is used to store key value pairs . A bucket can have multiple key-value pairs . In hash map, bucket used simple linked list to store objects .
           
          Before start with internal working of HashMap,first you should know this thing,

  1. Two unequal object may return same hashcode.
  2.  When two objects are equal by equals(), then they must have same hashcode.  

      There are two main  methods used for storing and retrieving values from HashMap.

1) .put() method to put /store values in HashMap
2) .get() method to retrieve data/values from HashMap

1) How put(Key key, Value v) method works internally?


 Lets see implementation of put method:

public V put(K key, V value) {
      if (key == null)
         Nreturn putForNullKey(value);
                   
      int hash = hash(key.hashCode());
      int i = indexFor(hash, table.length);
      for (Entry<k , V> e = table[i]; e != null; e = e.next) {
                Object k;
                if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                       V oldValue = e.value;
                       e.value = value;
                       e.recordAccess(this);
                       return oldValue;
                 }
        }
        modCount++;
        addEntry(hash, key, value, i);
        return null;
 }

Let us understand above code step by step,

1) Key object is checked for null. If key is null then it will be stored at table[0] because hashcode for
    null is always 0.
2) Key object’s hashcode() method is called and hash code is calculated. This hashcode is used to find
    index of array for storing Entry object. It may happen sometimes that, this hashcode function is
   poorly written so JDK designer has put another function called hash() which takes above calculated
    hash value as argument.
3) indexFor(hash,table.length)  is used to calculate exact index in table array for storing the Entry
    object.
      The indexFor will return the index of table array, the index calculation is based on hashcode of key and length of table array. This will do the and operation as ,
 
 static int indexFor(int h, int length) {
    return h & (length-1);
 }
 
4) If two key objects have same hashcode(which is known as collision) then it will be stored in form
    of linkedlist.So here, we will iterate through our linkedlist.


  2) How get(Key key) method works internally?

        
       Here are the steps, which happens, when you call get() method with key object to retrieve corresponding value from hash based collection.
     
    Let's see code,

public V get(Object key) {

        if (key == null)
           return getForNullKey();

        int hash = hash(key.hashCode());
        for (Entry<k , V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
               Object k;
               if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
                   return e.value;
         }
         return null;
 }

1) Key object is checked for null. If key is null then value of Object resides at table[0] will be returned.
2) Key object’s hashcode() method is called and hash code is calculated.
3) indexFor(hash,table.length)  is used to calculate exact index in table array using generated hashcode for getting the Entry object.
4) After getting index in table array, it will iterate through linkedlist and check for key equality by calling equals() method and if it returns true then it returns the value of Entry object else returns null.

What happens if two keys has same hashCode?


           If multiple keys has same hashCode, then during put() operation collision had occured, which means multiple Entry object stored in a bucket location. Each Entry keep track of another Entry, forming a linked list data structure. Now , if we need to retrieve value object in this situation, following steps will be followed :

1) Call hashCode() method of key to find bucket location.
2) Traverse  through linked list, comparing keys in each entries using keys.equals() until it return true. So, we use equals() method of key object to find correct entry and then return value from that.
       

Key Notes:--

1) Data structure to store Entry objects is an array named table of type Entry.

2) A particular index location in array is referred as bucket, because it can hold the first element of a LinkedList of Entry objects.

3) Key object’s hashCode() is required to calculate the index location of Entry object.

4) Key object’s equals() method is used to maintain uniqueness of Keys in map.

5) Value object’s hashCode() and equals() method are not used in HashMap’s get() and put() methods.

6) Hash code for null keys is always zero, and such Entry object is always stored in zero index in Entry[].



Related Posts:-- 
1) Internal Implementation of TreeMap in Java  
2) How to iterate the TreeMap in reverse order in Java  
3) Java Program to Count Occurrence of Word in a Sentence  
4) Internal implementation of ArrayList in Java  
5) String Interview Questions and Answers
6) Exception Handling Interview questions and answers

Why String is immutable or final in java?

            This is an old yet still popular question. There are multiple reasons that String is designed to be immutable in Java. A good answer depends on good understanding of memory, synchronization, data structures, etc. In the following, I will summarize some answers.

  • Requirement of String Pool

             String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
The following code will create only one string object in the heap.
                   
            String s1="nrk infotech";
            String s2="nrk infotech";

           If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

  • Allow String to Cache its Hashcode

               The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same, so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.

             String s1="one";
             HashMap<String,Integer>  map =  new HashMap<String,Integer>();
             map.put(s1,new Integer(1));
             s1.concat("two");
             System.out.println(map.get(s1));

    Immutable objects are much better suited to be Hashtable keys.

For example,
                                    
    
In the above code,s1 value won't change whenever you are calling map.get(s1) so it will work properly.
 
 For Example ,in case of StringBuffer,

                 StringBuffer s1=new StringBuffer("one");
              HashMap<String,Integer>  map =  new HashMap<String,Integer>();
              map.put(s1,new Integer(1));
              s1.append("two");
              System.out.println(map.get(s1));     //here s1=onetwo

 In the above code it will return null.
                 
  •  Security

           String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.

  • Thread Safety

                 Immutable objects are thread-safe. Two threads can both work on an immutable object at the same time without any possibility of conflict. No external synchronization is required.
 

Related Post:--
1) What are the immutable classes in java?&how to create immutable class& what are the conditions?
2) String Related interview questions & Answers

Saturday, 14 June 2014

String Interview Questions and Answers

 I have shared some String interview questions with answers so it can help for the job seekers.

1) Is String data type in Java?

    No, String is a class, not data type.


2) How many ways to create a String object?

There are two ways to create the String object in java,
  • String literal
  • Using new Operator


3) What is difference between creating String as new and literal?

            When we create string with new() Operator, it’s created in heap and not added into   
 string pool while String created using literal are created in String pool itself which exists 
 in PermGen area of heap.
         
  
4) What would be the output?

  String s1="nrk";
    String s2="nrk";
    String s3=new String("nrk");

    if(s1==s2){                          
           System.out.println("s1 & s2 equal");
    } else{                             
           System.out.println("s1 & s2 not equal"); 
    }

    if(s2==s3){                             
           System.out.println("s2 & s3 equal");
    } else{                             
           System.out.println("s2 & s3 not equal");
    }

Output:  s1 & s2 equal
               s2 & s3 not equal



5) See below two variables what is difference?

  String a="hcl technology";

   final String a="hcl technology";

     Here both are immutable but in first variable reassignment of variable  is  possible but in case of final it is not possible. It will give compile-time  error.
       
 e.g          String a="hcl";
                a=a.concat("b");            //no error,compile & run normally
         
in case of final,  
                      final String a="hcl";
                      a=a.concat("b");             //give compile time error,reassignment not possible.


6)    
What would be the output for above two lines?


    System.out.println(2+3+"4");
        System.out.println("2"+3+4);

Output:--    54
                   234



7) What is the output of the given code?
 public class A{
      public static void main(String [] args) {
            String s1 = null;
            String s2 = s1+"java";
            System.out.println(s2);
      }
 }

Output: nulljava


8) What is the output of the given code?

    public class A {

         public static void main(String [] args){

            String s1 = null;

            System.out.println(s1.length());
 
       }

  }

Output:--java.lang.NullPointerException

9) What is the output of the given code?

    public class A {

         public static void main(String [] args){

            String s1 = null;

            System.out.println(s1);
 
       }

  }
Output:--null


10) What is the output of the given code?
    public class A {

         public static void main(String [] args){

            System.out.println(null);
 
       }

  }
Output:--Compile Time Error.



11) Write a program to swap two String variables without using the third variable .


  public class StringSwap {   
      
       public static void main(String[] args) {

            String a="var1";

            String b="var2";

            a= a+b;

            b = a.substring(0,(a.length()-b.length()));

            a = a.substring(b.length(),(a.length()));

            System.out.println("a = "+a+" b="+b);   //a=var2 b=var1
   
      }
  
  }



12) Write a program to replace particular character with another character  from the given string without using Java API's.


 public class ReplaceCh {
      
       public static void main(String[] args) {

            String a="Software";

            String[] a1=a.split("");

            String ch="";
 
            for(int i=0;i<a1.length;i++){

                if(a1[i].equals("w")){
                   
                    ch=ch+"g";
              
                } else{

                    ch=ch+a1[i];
                                                   
               }
                                           
          }
          System.out.println(ch);
     } 
 }

it will print Softgare.


13) What would be the output?
  public class StrEx {

       public static void main(String[] args) {

            StrEx g=new StrEx();

            g.m(null);

      }

      public void m(String a){

           System.out.println(a);

      }

  }
Output:-- null.


14) null method overloading example

public class StrEx {

     public static void main(String[] args) {                                        
          m(null);
     }
                                        
     public static void m(String a){                              
          System.out.println("String");
     }
                                       
     public static void m(int a){                                   
          System.out.println("int");
     }

     public static void m(Object o) {                                               
          System.out.println("Object");
     }

}
What would be the output?

Output:- String.


15) null method overloading example--

public class StrEx {

     public static void main(String[] args) {                                        
          m(null);
     }
                                        
     public static void m(String a){                              
          System.out.println("String");
     }
                                       
     public static void m(int a){                                   
          System.out.println("int");
     }

     public static void m(Object o) {                                               
          System.out.println("Object");
     }

     public static void m(Integer i){                                                
          System.out.println("Integer");
     }

}
What would be the output?

Output:--Compile-time error at m(null)



16) Write a method  int Summation(String s). It will return summation of  integers from  the   given string.
          e.g  String s1="12 3 4 some text 3";
                 output should be summation of 12,3,4 & 3=22.

public int Summation(String s1) {                                    
      String[] s1 = a.split(" ");
      int sum = 0;
      for(int i = 0; i<s1.length; i++) {                                 
          if(s1[i].matches("[0-9]+")) {
              sum = sum + Integer.parseInt(s1[i]);
          }
     }
     return sum;
}


17) Write a program to find the length of the String without using the String method length.

 public class Slength {
                                
       public int length(String s) {                                          
            int i=0;                                                   
            try {                                              
                for(i=0;i>=0;i++) {                                                 
                     s.charAt(i);                                          
                }                                                     
           }                                           
           catch(Exception e){                                                             
                 System.out.println("The length of the string ---");                                                      
           }                                           
           return i;                                   
      }

      public static void main(String[] args {                                             
            Slength h = new Slength();                                               
            int len = h.length("ghhjnnm");                                               
            System.out.println(len);                                     
      }                                
 }



18) Write a program to count the letters from the given String.


 public class CountLetter {

      public static void countLetter(String s) {                                      
           if(s==null) {
                return;
           }                                         
           int counter=0;                                      
           for(int i=0;i<s.length();i++) {
               if (Character.isLetter(s.charAt(i))) {                                                      
                  counter++;
               }
           }                                      
           System.out.println(counter);
      }

      public static void main(String[] args) {                                          
          CountLetter.countLetter("ggg999");
      }
 }
      



19) Write a program to check the given string is palindrome or not.


import java.util.Scanner;
public class palindrome {
       public static void main(String[] args) {
                                    
             Scanner sc=new Scanner(System.in);
             System.out.println("Enter a string");
             String str=sc.nextLine();
             int l=str.length();
             String reverse="";
             for(int i=l-1;i>=0;i--) { 
                   reverse = reverse + str.charAt(i);
             }                             
             if(str.equals(reverse)) {
                   System.out.println("Palindrome");
             }
             else{
                 System.out.println("Not palindrome");
             }
       }
}



20) What is output?


 public class test {
       public static void main(String [] args) {
             int x = 3;
             int y = 1;
             if (x = y) {
                  System.out.println("Not equal");
             } else {
                  System.out.println("Equal");
             }
       }
 }

Output:- Compile Time Error at if (x = y).



21) Does String is thread safe in java?

          Strings are immutable, so we can’t change it’s value in program.  Hence it’s thread-safe and can be safely used in multi-threaded environment.



22)  Can we use String in switch case? 

        This is a tricky question used to check your knowledge of current Java developments. Java 7 extended the capability of switch case to use Strings also, earlier java versions doesn’t support this.
         If you are implementing conditional flow for Strings, you can use if-else conditions and you can use switch case if you are using Java 7 or higher versions.



23) Why String is immutable or final in Java?

    In previous post already explained this, Please go through this link why string is immutable in Java



Related Posts:--
1) Why String is immutable or final in java?
2) Java program to print the first n prime numbers
3) Java Program to check the given number is a palindrome or not
4) Java Program to find the Missing Number in an Array
5) How to Remove duplicates from ArrayList in Java
6) Java Program to Perform Matrix Multiplication