Pass user input from command line in java

There is a various way, you can pass parameter from a console . Using BufferdReader,InputStream but the easiest way to do it with Scanner class it took Inputstream(System.in) as parameter from we can get user given value

Let see an example



package com.example.userInput;

import java.util.Scanner;

public class UserInput {

    public void add(int i,int j)
    {
        int result = i+j;
        System.out.println("sum is " + result);
    }

    public void multiply(int i,int j)
    {
        int result = i*j;
        System.out.println("
Multiplication  is " + result);
   
    }

    public static void main(String[] args) {
   
        Scanner sc= new Scanner(System.in);
        System.out.println("Enter Choice either a or m");
        System.out.println("Enter First Operend");
        int op1 = sc.nextInt();
        System.out.println("Enter Second Operend");
        int op2 = sc.nextInt();
        System.out.println("Enter Choice");
        String choice = sc.next();
   
   
        UserInput input = new UserInput();
        if("a".equalsIgnoreCase(choice))
        {
            input.add(op1, op2);
        }
        else if("m".equalsIgnoreCase(choice))
        {
            input.multiply(op1, op2);
       
        }
        else
        {
            System.out.println("Wrong choice Entered");
        }


Spring framework download and integration with eclipse step by step.

In this tutorial we will learn how we can download spring framework jars for eclipse and integrate the downloaded spring framework with eclipse . Then we create a basic Spring example to check our setup is successful or not.

Here are the steps to configure Spring core with eclipse IDE

1. Install JDK and eclipse
2. create a java project in eclipse called SpringTest
3. create a folder  lib under SpringTest\lib
4. Download commonLoggin1.2.jar from here http://commons.apache.org/proper/commons-logging/download_logging.cgi

5. extract it and put jars into lib folder earlier created.
6. Download spring from here
http://repo.spring.io/release/org/springframework/spring/4.1.6.RELEASE/
7. extract it and put all jars into the lib folder .
8. Right click on SpringTest ->properties->java build path
9. click on add external   jar and add all jars under lib folder
10.  Create a  folder called configFiles under SpringTest/ src folder.
11. create beans.xml file in configFiles

Add following lines

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="helloWorld" class="com.example.HelloWorld">
       <property name="greet" value="Hello World! Welcome to Spring"/>
   </bean>

</beans>


12 Create a package com.example under
SpringTest\src

13. create a java file HelloWorld.java under the package
com.example

14. Write following in HelloWorld


package com.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloWorld {
   
    private String greet;

    public String getGreet() {
        return greet;
    }

    public void setGreet(String greet) {
        this.greet = greet;
    }
   
   
    public static void main(String[] args) {
       
        ApplicationContext ctx = new ClassPathXmlApplicationContext("configFiles/beans.xml");
       
        HelloWorld bean =(HelloWorld) ctx.getBean("helloWorld");
        System.out.println(bean.getGreet());
       
       
    }
   
   

}
15. Run as java application output will be
Hello World! Welcome to Spring

multiple inheritance in java?

Java directly does  not support multiple inheritance , but by interface it supports the same.

To understand why java does not support multiple inheritance  first we need to understand the Diamond problem

Diamond problem says

Suppose we have Parent class Color it has a method cal displayColor().

Now it has two children  Yellow and Blue by invoking displayColor(). they return yellow and blue respectively.

Let assume java supports multiple inheritance
So if I create a child say Green which inherits Yellow as well as Blue then which displayColor() color it inherits? It creates an ambiguous  situation so for this reason java does not support multiple inheritance directly but we can solve this problem by the interface. An interface is a contract only methods are declared in  interface no definition so if Green implements yellow and blue ,
Green class easily override displayColor() , and define the same, there will be no problem as only concrete implementation only in Green class.

Example:
public class Color
{
public void displayColor()
{
System.out.println("white");
}
}


public class Yellow extends Color
{
public void displayColor()
{
System.out.println("yellow");
}

}


public class Blue extends Color
{
public void displayColor()
{
System.out.println("blue");
}
}




interface color
{
  void displayColor();
}

interface yellow extends color
{
  void displayColor();
}

interface blue extends color
{
  void displayColor();
}


Class Green implements blue,yellow
{
  public void displayColor()
{
System.out.println("Green")
}

}







Does Java support multiple inheritance?

Java directly does  not support multiple inheritance , but by interface it supports the same.

To understand why java does not support multiple inheritance  first we need to understand the Diamond problem

Diamond problem says

Suppose we have Parent class Color it has a method cal displayColor().

Now it has two children  Yellow and Blue by invoking displayColor(). they return yellow and blue respectively.

Let assume java supports multiple inheritance
So if I create a child say Green which inherits Yellow as well as Blue then which displayColor() color it inherits? It creates an ambiguous  situation so for this reason java does not support multiple inheritance directly but we can solve this problem by the interface. An interface is a contract only methods are declared in  interface no definition so if Green implements yellow and blue ,
Green class easily override displayColor() , and define the same, there will be no problem as only concrete implementation only in Green class.

Example:
public class Color
{
public void displayColor()
{
System.out.println("white");
}
}


public class Yellow extends Color
{
public void displayColor()
{
System.out.println("yellow");
}

}


public class Blue extends Color
{
public void displayColor()
{
System.out.println("blue");
}
}




interface color
{
  void displayColor();
}

interface yellow extends color
{
  void displayColor();
}

interface blue extends color
{
  void displayColor();
}


Class Green implements blue,yellow
{
  public void displayColor()
{
System.out.println("Green")
}

}







Does runtime polymorphism can be acheived by data memebrs?

No Overriding can not be performed on properties/data members it always call the reference class properties value

Let take an example

Public class Father
{

  public  int age=60;

}

Public class Child extends Father
{

  public  int age=30;

}


Now if Father f = new Child();
f.age print 60;

How does Map work in Java?

HashMap in Java works on hashing principle. The Map is a data structure which allows us to store object with a key and retrieve same by the same key. Hash functions are used to link key and value in HashMap. Objects are stored by calling put(key, value) method of HashMap and retrieved by calling get(key) method.

 When we call put method,internally  hashcode() method of the key object is called so that hash function of the map can find a bucket location to store value object, which is actually an index of the internal LinkedList. If we dig down the structure we found HashMap internally stores mapping in the form of Map.Entry object which contains both key and value object. When you want to retrieve the object, you call the get() method with  a key object. get() method again generate  key object hash code and eventually ended up with same  bucket location. and returns the value.

Few important things to remember , If you want to use your custom object as a Key of Map

1. It has to be immutable .unless  some one can  change the state.of the object
2. Must override hashcode. As good hashing algorithm, distribution of objects in bucket will be as good
.3. Must override equals method so in  the time of get operation  map  can fetch the key which is identically equal.

public final class CustomKey{
private final String name = "Shamik";
public final String setName(String name)
{
this.name=name;
}
public final String getName(String name){
return name;
}
public int hascode()
{
return name.hascode()*1245/7;
}
public boolean equals(Object obj)
{
if(obj instanceof CustomKey)
{
return this.name.equals(obj.name);
}
return false;
}
}

Here  name is not final so following scenario can occur
CustomKey refKey= new CustomKey();
Map<CustomKey ,String> map = new HashMap<CustomKey,String>();
map.put(refKey,"Shamik");
refKey.setName("Bubun");
map.get(refKey);

It will return null as when equals method invokes it return false. So immutability is must required.

what is servlet collaboration?

Servlet Collaboration means how one servlet can communicate with other. Sometimes servlets are to pass the common information that is to be shared directly by one servlet to another through various invocations of the methods. To perform these operations, each servlet needs to know the other servlet with which it collaborates. Here are several ways to communicate with one another:


1. ServletContext :  In an application, there must be one Servlet context which is shared by all the servlets in this application. It works as a global map .each servlet put  necessary information , which needs to be shared
and other can get that info
  <servlet>
  <servlet-name>ServletName</servlet-name>
  <servlet-class>com.example.ServletTest</servlet-class>
 </servlet>

 <context-param>
   <param-name>name</param-name>
   <param-value>Shamik Mitra</param-value>
 </context-param>




To get this
getServletContext().getInitParameter("email");

Request Dispatcher:
request.setAttribute("name", "Shamik Mitra")
request.getRequestDispatcher("destination_name").forward(req,res);
request.getRequestDispatcher("destination_name").include(req,res);

Java Singleton class :

public class Javacontext
{
   private static Javacontext ctx = new Javacontext();
private String name ="Shamik";
private Javacontext()
{
}
public static Javacontext getInstance()
{
return ctx;
}
public String getname()
{
return name;
}
}


Java Properties: Using java properties you can share information

import java.util.*;

public class PropDemo {

   public static void main(String args[]) {
      Properties prop= new Properties();
     Set<String> key;
   
      prop.put("name", "Shamik Mitra");
   

      // Show all states and capitals in hashtable.
      key= prop.keySet(); // get set-view of keys
      Iterator itr = key.iterator();
      while(itr.hasNext()) {
         str = (String) itr.next();
         System.out.println("The key is" +
            str + " name is " + prop.getProperty(str) + ".");
      }
   
   }
}

Can we Overload Main method in java.

Yes you can overload main method but public static void main(String[] args) is entry point in java. JVM always search for this method.
If it is not present in overloaded version ,when you try to run your code that gives run time exception no main method found.


From public static void main(String[] args), you can call other overloaded main function.

Keep in one thing in mind

If some one write

public static void main(String... args)//Varags

That is equivalent public static void main(String[] args) that will gives you compile time error.

Example :
package com.example.main;

public class OverLoadmain {
   
    public static void main(String[] args) {
       
        System.out.println("I am in main ");
       
    }
   
public static void main(int args) {
   
    System.out.println("I am in int");
       
    }


public static void main(String args) {
    System.out.println("I am in String");
}


/*public static void main(String... args) {
    System.out.println("I amn in varags ");
}*/

}

Display trangle in screen using Java.

package com.example.loop.star;

/*
 *
 * This class display triangle as follows
 *
 *         *
 *        * *
 *      * * * *
 *    * * * * * *     
 */

public class DisplayTrangle {
   
    public void triagle_center(int max){//max means maximum star having
        int n=max/2;
       
        /*This loop prints Top star  as  max star is 20 so i first row we have 19 single blanks and one star to complete left hand
         * So n = 20/2 = 10
         *
         * For first row middle point is 11 th position so 19 single blanks one *
         *
         *
         * Row onwards
         *
         * star = row number * 2 if 1st row 2 stars
         * double blank = middle pos - row number;= 10-1=9 double blanks
         *
         * as middle pos is  11.        *
         *
         *
         * *\
         *
         */
       
        for(int m=0;m<((2*n)-1);m++){//for upper star
            System.out.print(" ");
        }
        System.out.println("*");

        for(int j=1;j<=n;j++){
            for(int i=1;i<=n-j; i++){
                System.out.print("  ");
            }
            for(int k=1;k<=2*j;k++){
            System.out.print("* ");
            }

            System.out.println();
        }


    }
   
   
    public static void main(String[] args) {
       
        DisplayTrangle ref = new DisplayTrangle();
        ref.triagle_center(20);
       
    }


}

Is Spring Bean Thread Safe?

Thread safety is a different context . Singleton spring beans has no relation with thread safety. spring container only manages life-cycle of objects and guaranteed that only one object in spring container. so If an Non thread safe object is injected then obviously it is not thread safe. To make it thread safe you have to handle it by coding.

If it is a web-application , Scope("request") can achieve thread-safety  as for each new request it creates a new object or scope("prototype") will do this.(for each  invocation it creates new bean .)