Powered By Blogger

Monday, December 19, 2016

Spring - When problem is solved with maturity!

Key points - 
----------------------------------------------------------------------------------------------------------------

1. Spring is an open-source framework with main intention to achieve loose-coupling.

2. Spring uses layered approach which means user/developer has a choice to use functionality if needed.      
    Example -
    Developer can choose AOP functionality to implement
    Developer can choose to design appication with Spring MVC.
    Developer can choose to integrate with ORM (Hibernate).

3. Spring core module is based on IOC container ( also known as Dependency Injection).

4. org.springframework.beans and org.springframework.context packages are used for DI.

5. BeanFactory interface points -

a. Creates an object of the bean when bean name is specified in getBean() method of BeanFactory interface.

b. "Factory" - this term means creation of objects at one place and user does not have to worry object creation.
Resource res = new FileSystemResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);

or

ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);

or

ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml", "applicationContext-part2.xml"});  

// of course, an ApplicationContext is just a BeanFactory
BeanFactory factory = (BeanFactory) appContext;

6. ApplicationContext interface points-

a. Creates an object of the bean when bean name is specified in getBean() method.

b. Provides internationalization support - means same application can be translated into different languages based on the location.

c. Publishes event to the registered beans as listeners. 

Spring MVC (Model View Controller) -

Key Points - 
-----------------------------------------------------------------------------------------------------------------------

MVC is a design pattern where an application is can be divided into 3 layers so that each layer has exactly one responsibility and does not know much about other layers.

Model        - Looks into application's business logic and interactions with database.

View           - Looks into presentation part on how to display. Also, view technologies can be changed easily or upgraded as view is not dependent on other layers.

Controller - Acts as a middleman in which additional logic can be added for controlling role based access (example). Also, takes command from View layer ( add data, edit data, delete data, etc) and gets the work done from Model layer.(request/response)
------------------------------------------------------------------------------------------------------------------------

Dispatcher Servlet -

1. Web application works with client-server architecture. Client sends a request for some resource and server responds with a resource.

2. We need a servlet which process request with the help of other classes (data + business logic) and send response.

3. DispatcherServlet handles all requests in a central place and sends request to the controller which in turn processes (store/load) data based on the business rules.

4. DispatcherServlet uses FrontController design pattern which means handling of an application will be done at a central place.

5. Example web.xml

    <web-app>
     <servlet>
          <servlet-name>example</servlet-name>
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <load-on-startup>1</load-on-startup>
     </servlet>

     <servlet-mapping>
         <servlet-name>example</servlet-name>
         <url-pattern>*.form</url-pattern>
     </servlet-mapping>
    </web-app>
    (Taken from http://docs.spring.io/spring-framework/docs/2.0.x/reference/mvc.html)

6. URLs ending with .form will be handled by example dispatcher servlet.

7. Spring framework looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of web application. Also, creates beans defined in this xml file.
    As per above point 5 - file name will be example-servlet.xml

   <context:component-scan base-package="com.xyz.xyz" />
 
   <!-- Configuration defining views files -->
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="prefix">
              <value>/WEB-INF/views/</value>
          </property>
          <property name="suffix">
              <value>.jsp</value>
         </property>
 </bean>

8. If you want to give different servlet name or different location (other than default location i.e.,WEB-INF directory, then add following details in the web.xml file

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/example-servlet.xml          
        </param-value>
    </context-param>

Tuesday, December 13, 2016

EXCEPTION - VERY USEFUL WHEN THINGS GO UNEXPECTED!

---------------------------------------------------------------------------------------------------------------
Description -
Exception is a condition where a block of code behaves unexpectedly due to unexpected input from the user or due to programmer's irresponsible code.
---------------------------------------------------------------------------------------------------------------

Key Points-

1. One should handle checked exception in code (either in try/catch block or throws keyword).
   Illustration -
main(){                // you can also declare main() using throws keyword main() throws InsufficientFundsException 

     B b = new B();
     
 try{
 b.myMethod();                             // compiler forces you to handle exception
 }catch(InsufficientFundsException ex){
         ex.printstackTrace();
     }
   }

   public class B{
         public void myMethod() throws InsufficientFundsException{   // Custom exception defined by you. You can throw multiple exceptions.
            if(balance <=0)
               throw new InsufficientFundsException();
         }
   }
 
2. Checked exception is good in some situations as compiler forces programmer to handle checked exception and hence application not breaks.

3. Throw your own exception from catch block when an exception is caught. This helps you to maintain discipline as you handle exceptions in one place.
Illustration -
class A{

   try{
      myMethod();
   }catch(BaseException ex){
     ex.printstackTrace();
   }
   }
    
   public class B{
         public void myMethod() throws BaseException{   // Custom exception defined by you. You can throw multiple exceptions.
   
   try{
     // some database code
     // application logic
   }catch(SQLException ex){
      ex.printstackTrace();
      throw new BaseException("exception occurred while processing myMethod()");
   }
               
         }
   }

4. Runtime exceptions should not be handled in catch block or thrown from a method. Because, these exceptions can be avoided through
   programmer and client can't do anything from this exception. So, these are called unchecked exceptions.
   Ex :- ArithmeticException, ArrayIndexOutOfBoundsException, IllegalArgumentException etc.

5. Use checked exceptions when user can change the input based on the message given by exception.

6. finally block should be used when you are dealing with resources. You have to close resources irrespective of exception.
------------------------------------------------------------------------------------------------------------------

Saturday, July 2, 2016

Anonymous inner class - I am more readable and maintainable and you can create me (class) quickly at your place and override!


---------------------------------------------------------------------------------------------------------------

Description :-

        A class with no name is called Anonymous inner class.

----------------------------------------------------------------------------------------------------------------

Key Points :-

1. Normally used when you want to add small functionality and don’t want to create a new class for it. Look for some real-time examples below for clarity.

2. Increases readability of the code. ( Can be argued because of weird syntax)

3. Increases performance as you are not adding extra classes for small functionality. (Check                     References section)

4. Anonymous class means creating a sub-class with no name and override the functionality.

5. Anonymous class can be created for a class, abstract class and interface.

6. We can think about polymorphism as anonymous inner class is a subclass object and the reference       variable can be thought of as super class reference.

7. Weird syntax

     Hello hello = new Hello() {
            // override method
           public String sayHello(){
               return "Anonymous Hello";
           }
     }; // end of class

8. When you want to add actionListener for button.

    Example :-
    JButton jButton = new JButton(“Click”);
    jButton.addActionListener( new ActionListener() {
           public void actionPerformed(ActionEvent event){
            // code
      }
    });

9. When you want to add customized sorting for the list.

    Example :-
    Collections.sort(list, new Comparator<Employee>(){
         public int compare(Employee emp1, Employee emp2){
           // code
         }
    });

10. When you want to create a thread from Runnable interface.

    Example :-
    Thread thread = new Thread( new Runnable(){
       public void run(){
          // code
       }
    });

----------------------------------------------------------------------------------------------------------------
  
Program :-


Normal class

package com.thebeautifuljava.anonymous;

public class Hello {

 public String sayHello() {
  return "hello";
 }
}

----------------------------------------------------------------------------------------------------------------

Abstract class

package com.thebeautifuljava.anonymous;

public abstract class AbstractHello {

 public abstract String sayHello();
}

----------------------------------------------------------------------------------------------------------------

Interface

package com.thebeautifuljava.anonymous;

public interface InterfaceHello {

 public abstract String sayHello();
}

----------------------------------------------------------------------------------------------------------------

main() shows how anonymous class overrides method for each of the above

package com.thebeautifuljava.anonymous;

public class AnonymousDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  // override method of normal class
  Hello hello = new Hello() {
   public String sayHello() {
    // TODO Auto-generated method stub
    return "Anonymous Hello";
   }
  };

  System.out.println(hello.sayHello());

  AbstractHello abstractHello = new AbstractHello() {

   // override method of abstract class
   public String sayHello() {
    // TODO Auto-generated method stub
    return "Abstract Anonymous Hello";
   }
  };

  System.out.println(abstractHello.sayHello());

  InterfaceHello interfaceHello = new InterfaceHello() {

   // override method of interface
   public String sayHello() {
    // TODO Auto-generated method stub
    return "Interface Anonymous Hello";
   }
  };

  System.out.println(interfaceHello.sayHello());

 }

}

----------------------------------------------------------------------------------------------------------------

Override method which has parameter

package com.thebeautifuljava.anonymous;

public class HelloParameter {

 public String saySomething(String string) {
  return string;
 }
}

package com.thebeautifuljava.anonymous;

public class AnonymousParameterDemo {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  // with anonymous class
  HelloParameter helloParameter = new HelloParameter() {
   public String saySomething(String string) {
    return string + " Anonymous";
   }
  };

  System.out.println(helloParameter.saySomething("Hi"));

  // without anonymous class
  HelloParameter helloParameterNormal = new HelloParameter();
  System.out.println(helloParameterNormal.saySomething("Hi"));
 }

}

----------------------------------------------------------------------------------------------------------------

References :-



Saturday, June 25, 2016

Certification programs explained


----------------------------------------------------------------------------------------------------------------
1. String behaviour.

package com.thebeautifuljava.certificationprograms;

public class Test1 {

 public static void main(String[] args) {

  String str1 = "abc"; // object is created in string constant pool
  String str2 = "def"; // object is created in string constant pool

  String str3 = str1.concat(str2); // str3 = "abc".concat("def") 
                                  // str3 points to the new object "abcdef" in pool and heap 
                                  // (Refer String chaper in Java 6 Kathy Sierra and Bert Bates)

  str1.concat(str2); // "abc".concat("def") => "abcdef" (No reference). This object is already present in pool and
                     // new object "abcdef" is created in heap also!
                      // (Refer String chaper in Java 6 Kathy Sierra and Bert Bates)

  System.out.println(str1); // str1 still points to object "abc" as 
                           // str1 reference is not updated!!
 }

}

----------------------------------------------------------------------------------------------------------------
2. ceil() and round() methods of Math class.

package com.thebeautifuljava.certificationprograms;

public class Test2 {
 public static void main(String args[]) {
  int i;
  float f = 2.3f;
  double d = 2.7;
  i = ((int) Math.ceil(f)) * ((int) Math.round(d)); // i = ((int) 3.0) * ((int) 3) => i = // (3 * 3) => i = 9
  System.out.println(i); // prints 9
 }
}
----------------------------------------------------------------------------------------------------------------
3. Post decrement operator behaviour.



package com.thebeautifuljava.certificationprograms;

public class Test3 {

 public static void main(String args[]) {
  int i = 1;
  do {
   i--; // i=1
  } while (i > 2); // i=0, (0 > 2)? - false
  System.out.println(i); // prints 0
 }

}

----------------------------------------------------------------------------------------------------------------
4. Difference between == operator and equals() method of Object class.



package com.thebeautifuljava.certificationprograms;

public class Test4 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  String s1 = "abc"; // memory is allocated in string constant pool
  String s2 = new String("abc"); // memory is allocated in heap and "abc" literal is created in pool also!
                                 // (Refer String chaper in Java 6 Kathy Sierra and Bert Bates)
  if (s1 == s2) // false - as s1 and s2 points to different memory locations
   System.out.println(1);
  else
   System.out.println(2); // prints 2
  if (s1.equals(s2)) // true - ("abc".equals("abc"))? 
                    // as equals method  compares String object's contents
   System.out.println(3); // prints 3
  else
   System.out.println(4);
 }

}

----------------------------------------------------------------------------------------------------------------
5. Post increment and decrement operator.



package com.thebeautifuljava.certificationprograms;

public class Test6 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  int i = 1, j = 1;
  try {
   i++; // i=1
   j--; // j=1, i=2
   if (i == j) // j=0 => (2==0)? - false
    i++;
  } catch (ArithmeticException e) {
   System.out.println(0);
  } catch (ArrayIndexOutOfBoundsException e) {
   System.out.println(1);
  } catch (Exception e) {
   System.out.println(2);
  } finally {
   System.out.println(3); // prints 3 (because no exception)
  }
  System.out.println(4); // prints 4 (executes after finally block)
 }

}

----------------------------------------------------------------------------------------------------------------
6. Pre increment and post decrement operator.



package com.thebeautifuljava.certificationprograms;

public class Test7 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  int i = 0, j = 2;
  do {
   i = ++i; // i=1 => i=2
   j--; // j=1 => j=0
  } while (j > 0); // (1 > 0)? - true => (0 > 0)? - false
  System.out.println(i);
 }

}

----------------------------------------------------------------------------------------------------------------
7. switch-case statement.



package com.thebeautifuljava.certificationprograms;

public class Test8 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  int i, j = 1;
  i = (j > 1) ? 2 : 1; // (1 > 1)?2 : 1 - false and i=1
  switch (i) { // switch(1)
  case 0:
   System.out.println(0);
   break;
  case 1:
   System.out.println(1); // prints 1 (because no break statement after case 2)
  case 2:
   System.out.println(2); // prints 2
   break;
  case 3:
   System.out.println(3);
   break;
  }
 }

}

----------------------------------------------------------------------------------------------------------------
8. Assignment operator, wrapper class and array.



command line - java Test9 5

package com.thebeautifuljava.certificationprograms;

public class Test9 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  Integer intObj = Integer.valueOf(args[args.length - 1]); // args[1-1] => args[0]
  int i = intObj.intValue(); // args[0] = 5 - command line argument
  if (args.length > 1) // false - args.length = 1 (1 > 1)?
   System.out.println(i);
  if (args.length > 0) // true - args.length = 1 (1 > 0)?
   System.out.println(i - 5); // executes i=i-5, updated i's value is 0
  else
   System.out.println(i - 2);
 }

}

----------------------------------------------------------------------------------------------------------------
9. for-loop working.



package com.thebeautifuljava.certificationprograms;

public class Test10 {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

  for (int i = 0; i < 2; i++) { // First iteration i=0, Second iteration i=1
   for (int j = 2; j >= 0; j--) { // 2 iterations j=2,1, 1 iteration
    if (i == j) // Second iteration of inner loop - i=1,j=1 condition is true
     break;
    System.out.println("i=" + i + " j=" + j); // prints i=0,j=1 i=0,j=2 i=1,j=2 for 3 iterations
   }
  }
 }

}

----------------------------------------------------------------------------------------------------------------

Thursday, June 23, 2016

Wrapper class – Hey primitive, don’t worry I will wrap you and then let convert to desired respective objects!



---------------------------------------------------------------------------------------------------------------- Description :-

       For every primitive data type like byte, int,  short,  long,  float,  double, char, boolean, there are  equivalent classes Byte, Integer, Short, Long, Float, Double, Character, Boolean respectively in Java.

---------------------------------------------------------------------------------------------------------------- Key points :-

1. Mainly used to convert from one object to another. For more information, see “Program” section.

2. Only objects are allowed in collections like List, Set, Map. In collection, auto-boxing is done internally.

3. Boxing refers to converting from primitive data type (int) to its respective object (Integer).

   Example :-
   int number = 5;
   Integer numberConversion = new Integer(number);

4. Unboxing refers to converting from object (Float) to  its respective primitive data type (float).

   Example :-
   float number = 5.4f;
   Float numberConversion = new Float(number);
   numberConversion.floatValue();

5. Autoboxing refers to internal conversion from primitive data type (double) to its respective object (Double)

   Example :-
   List<Integer> list = new ArrayList<Integer>();
   list.add(1);   //autoboxing
   list.add(5); //autoboxing

---------------------------------------------------------------------------------------------------------------- Program :-
package com.thebeautifuljava.wrapper;

public class WrapperDemo {

 public static void main(String[] args) {
  // TODO Auto-generated method stub

  integerConversions(10, "10");
  System.out.println("----------------------------------------------------");
  
  doubleConversions(10.0, "10.0");
  System.out.println("----------------------------------------------------");
  
  floatConversions(10.0f, "10.0");
  System.out.println("----------------------------------------------------");
  
  short shortValue = 10;
  shortConversions(shortValue, "10");
  System.out.println("----------------------------------------------------");
  
  longConversions(10, "10");
  System.out.println("----------------------------------------------------");
  
  byte byteValue = 10;
  byteConversions(byteValue, "10");
  System.out.println("----------------------------------------------------");
 }

 /***********************BYTE CONVERSIONS*********************************/
 private static void byteConversions(byte byteValue, String numberTenString) {
  // TODO Auto-generated method stub
  Byte numberTenCoversion = new Byte(byteValue);

  byte numberTenByte = numberTenCoversion.byteValue();
  System.out.println("CONVERSION FROM Byte TO byte :" + numberTenByte);

  double numberTenDouble = numberTenCoversion.doubleValue();

  System.out
    .println("CONVERSION FROM Byte TO double :" + numberTenDouble);

  float numberTenFloat = numberTenCoversion.floatValue();
  System.out.println("CONVERSION FROM Byte TO float :" + numberTenFloat);

  int numberTenInt = numberTenCoversion.intValue();
  System.out.println("CONVERSION FROM Byte TO int :" + numberTenInt);

  long numberTenLongConversion = numberTenCoversion.longValue();

  System.out.println("CONVERSION FROM Byte TO long :"
    + numberTenLongConversion);

  short numberTenShort = numberTenCoversion.shortValue();
  System.out.println("CONVERSION FROM Byte TO short :" + numberTenShort);

  byte numberTenByteParse = Byte.parseByte(numberTenString);

  System.out.println("CONVERSION FROM String TO byte :"
    + numberTenByteParse);

  String numberTenStringConvert = Byte.toString(byteValue);

  System.out.println("CONVERSION FROM byte TO String :"
    + numberTenStringConvert);

  Byte numberTenByteConvert = Byte.valueOf(byteValue);
  System.out.println("CONVERSION FROM byte TO Byte :"
    + numberTenByteConvert);

  Byte numberTenStringByteConvert = Byte.valueOf(numberTenString);

  System.out.println("CONVERSION FROM String TO Byte :"
    + numberTenStringByteConvert);
 }

 /***********************LONG CONVERSIONS*********************************/
 private static void longConversions(long numberTen, String numberTenString) {
  // TODO Auto-generated method stub
  Long numberTenLong = new Long(numberTen);

  byte numberTenByte = numberTenLong.byteValue();
  System.out.println("CONVERSION FROM Long TO byte :" + numberTenByte);

  double numberTenDouble = numberTenLong.doubleValue();
  System.out
    .println("CONVERSION FROM Long TO double :" + numberTenDouble);

  float numberTenFloat = numberTenLong.floatValue();
  System.out.println("CONVERSION FROM Long TO float :" + numberTenFloat);

  int numberTenInt = numberTenLong.intValue();
  System.out.println("CONVERSION FROM Long TO int :" + numberTenInt);

  long numberTenLongConversion = numberTenLong.longValue();

  System.out.println("CONVERSION FROM Long TO long :"
    + numberTenLongConversion);

  short numberTenShort = numberTenLong.shortValue();
  System.out.println("CONVERSION FROM Long TO short :" + numberTenShort);

  long numberTenLongParse = Long.parseLong(numberTenString);

  System.out.println("CONVERSION FROM String TO long :"
    + numberTenLongParse);

  String numberTenStringConvert = Long.toString(numberTen);

  System.out.println("CONVERSION FROM long TO String :"
    + numberTenStringConvert);

  Long numberTenLongConvert = Long.valueOf(numberTen);
  System.out.println("CONVERSION FROM long TO Long :"
    + numberTenLongConvert);

  Long numberTenStringLongConvert = Long.valueOf(numberTenString);

  System.out.println("CONVERSION FROM String TO Long :"
    + numberTenStringLongConvert);
 }

  /***********************SHORT CONVERSIONS*********************************/
 private static void shortConversions(short numberTen, String numberTenString) {
  // TODO Auto-generated method stub
  Short numberTenShort = new Short(numberTen);

  byte numberTenByte = numberTenShort.byteValue();
  System.out.println("CONVERSION FROM Short TO byte :" + numberTenByte);

  double numberTenDouble = numberTenShort.doubleValue();
  System.out.println("CONVERSION FROM Short TO double :"
    + numberTenDouble);

  float numberTenFloat = numberTenShort.floatValue();
  System.out.println("CONVERSION FROM Short TO float :" + numberTenFloat);

  int numberTenInt = numberTenShort.intValue();
  System.out.println("CONVERSION FROM Short TO int :" + numberTenInt);

  long numberTenLong = numberTenShort.longValue();
  System.out.println("CONVERSION FROM Short TO long :" + numberTenLong);

  short numberTenShortConversion = numberTenShort.shortValue();

  System.out.println("CONVERSION FROM Short TO short :"
    + numberTenShortConversion);

  short numberTenShortParse = Short.parseShort(numberTenString);

  System.out.println("CONVERSION FROM String TO short :"
    + numberTenShortParse);

  String numberTenStringConvert = Short.toString(numberTen);

  System.out.println("CONVERSION FROM short TO String :"
    + numberTenStringConvert);

  Short numberTenShortConvert = Short.valueOf(numberTen);

  System.out.println("CONVERSION FROM short TO Integer :"
    + numberTenShortConvert);

  Short numberTenStringShortConvert = Short.valueOf(numberTenString);

  System.out.println("CONVERSION FROM String TO Integer :"
    + numberTenStringShortConvert);
 }

 /***********************FLOAT CONVERSIONS*********************************/
 private static void floatConversions(float numberFloat,
   String numberFloatString) {
  // TODO Auto-generated method stub
  Float numberTenFloat = new Float(numberFloat);

  byte numberTenByte = numberTenFloat.byteValue();
  System.out.println("CONVERSION FROM Float TO byte :" + numberTenByte);

  double numberTenDouble = numberTenFloat.doubleValue();
  System.out.println("CONVERSION FROM Float TO double :"
    + numberTenDouble);

  float numberTenFloatConversion = numberTenFloat.floatValue();

  System.out.println("CONVERSION FROM Float TO float :"
    + numberTenFloatConversion);

  int numberTenInt = numberTenFloat.intValue();
  System.out.println("CONVERSION FROM Float TO int :" + numberTenInt);

  long numberTenLong = numberTenFloat.longValue();
  System.out.println("CONVERSION FROM Float TO long :" + numberTenLong);

  short numberTenShort = numberTenFloat.shortValue();
  System.out.println("CONVERSION FROM Float TO short :" + numberTenShort);

  float numberTenFloatParse = Float.parseFloat(numberFloatString);

  System.out.println("CONVERSION FROM String TO float :"
    + numberTenFloatParse);

  String numberTenStringConvert = Float.toString(numberFloat);

  System.out.println("CONVERSION FROM float TO String :"
    + numberTenStringConvert);

  Float numberTenFloatConvert = Float.valueOf(numberFloat);

  System.out.println("CONVERSION FROM float TO Float :"
    + numberTenFloatConvert);

  Float numberTenStringFloatConvert = Float.valueOf(numberFloatString);

  System.out.println("CONVERSION FROM String TO Float :"
    + numberTenStringFloatConvert);

 }

 /***********************DOUBLE CONVERSIONS*********************************/
 private static void doubleConversions(double numberTen,
   String numberTenString) {

  Double numberTenDouble = new Double(numberTen);

  byte numberTenByte = numberTenDouble.byteValue();
  System.out.println("CONVERSION FROM Double TO byte :" + numberTenByte);

  double numberTenDoubleConversion = numberTenDouble.doubleValue();

  System.out.println("CONVERSION FROM Double TO double :"
    + numberTenDoubleConversion);

  float numberTenFloat = numberTenDouble.floatValue();
  System.out
    .println("CONVERSION FROM Double TO float :" + numberTenFloat);

  int numberTenInt = numberTenDouble.intValue();
  System.out.println("CONVERSION FROM Double TO int :" + numberTenInt);

  long numberTenLong = numberTenDouble.longValue();
  System.out.println("CONVERSION FROM Double TO long :" + numberTenLong);

  short numberTenShort = numberTenDouble.shortValue();
  System.out
    .println("CONVERSION FROM Double TO short :" + numberTenShort);

  double numberTenDoubleParse = Double.parseDouble(numberTenString);

  System.out.println("CONVERSION FROM String TO double :"
    + numberTenDoubleParse);

  String numberTenStringConvert = Double.toString(numberTen);

  System.out.println("CONVERSION FROM double TO String :"
    + numberTenStringConvert);

  Double numberTenDoubleConvert = Double.valueOf(numberTenString);

  System.out.println("CONVERSION FROM double TO Double :"
    + numberTenDoubleConvert);

  Double numberTenStringDoubleConvert = Double.valueOf(numberTenString);

  System.out.println("CONVERSION FROM String TO Double :"
    + numberTenStringDoubleConvert);

 }

 /***********************INTEGER CONVERSIONS*********************************/
 private static void integerConversions(int numberTen, String numberTenString) {

  // TODO Auto-generated method stub
  Integer numberTenInteger = new Integer(numberTen);

  byte numberTenByte = numberTenInteger.byteValue();
  System.out.println("CONVERSION FROM Integer TO byte :" + numberTenByte);

  double numberTenDouble = numberTenInteger.doubleValue();

  System.out.println("CONVERSION FROM Integer TO double :"
    + numberTenDouble);

  float numberTenFloat = numberTenInteger.floatValue();
  System.out.println("CONVERSION FROM Integer TO float :"
    + numberTenFloat);

  int numberTenInt = numberTenInteger.intValue();
  System.out.println("CONVERSION FROM Integer TO int :" + numberTenInt);

  long numberTenLong = numberTenInteger.longValue();
  System.out.println("CONVERSION FROM Integer TO long :" + numberTenLong);

  short numberTenShort = numberTenInteger.shortValue();
  System.out.println("CONVERSION FROM Integer TO short :"
    + numberTenShort);

  int numberTenIntParse = Integer.parseInt(numberTenString);
  System.out.println("CONVERSION FROM String TO int :"
    + numberTenIntParse);

  String numberTenStringConvert = Integer.toString(numberTen);

  System.out.println("CONVERSION FROM int TO String :"
    + numberTenStringConvert);

  Integer numberTenIntegerConvert = Integer.valueOf(numberTen);

  System.out.println("CONVERSION FROM int TO Integer :"
    + numberTenIntegerConvert);

  Integer numberTenStringIntegerConvert = Integer
    .valueOf(numberTenString);
  System.out.println("CONVERSION FROM String TO Integer :"
    + numberTenStringIntegerConvert);

 }

}


---------------------------------------------------------------------------------------------------------------- References :-

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html

https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html

https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html

https://docs.oracle.com/javase/7/docs/api/java/lang/Short.html

https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html

https://docs.oracle.com/javase/7/docs/api/java/lang/Byte.html

Monday, June 20, 2016

simple_programs

Nitin P Wadakar

Completed M.Tech in IT from VIT, Vellore and he is a fresher from Bengaluru. Helped in contributing these programs.




----------------------------------------------------------------------------------------------------------------

CommonUtils class is an utility class and any class can reuse methods from it.

1. Read input from keyboard and used as a common class.

package com.thebeautifuljava.utils;

import java.util.Scanner;

public class CommonUtils {

 public static int readFromKeyBoard() {
  Scanner scanner = new Scanner(System.in);
  return scanner.nextInt();
 }

}
----------------------------------------------------------------------------------------------------------------

Two different ways of writing logic to find biggest of 2 numbers.
2. Biggest of 2 numbers.


package com.thebeautifuljava.simpleprograms;

public class BiggestOfTwoNumbers {
 public static void main(String[] args) {
  System.out.println("BIGGEST OF 2 NUMBERS IS:" + findBiggest(100, 65));
  System.out.println("BIGGEST OF 2 NUMBERS IS (Ternary):"
    + findBiggestTernary(100, 65));
 }

 // method 1
 private static int findBiggest(int first, int second) {
  if (first > second)
   return first;
  return second;
 }

 // method 2
 private static int findBiggestTernary(int first, int second) {
  return (first > second) ? first : second;
 }

}
----------------------------------------------------------------------------------------------------------------

Best way to re-use CommonUtils class.

3. Biggest of 2 numbers by inputting through keyboard.


package com.thebeautifuljava.simpleprograms;

import com.thebeautifuljava.utils.CommonUtils;
public class BiggestOfTwoNumbersRead {
 public static void main(String[] args) {

  System.out.println("ENTER FIRST NUMBER :");
  int first = CommonUtils.readFromKeyBoard();

  System.out.println("ENTER SECOND NUMBER :");
  int second = CommonUtils.readFromKeyBoard();

  System.out.println("BIGGEST OF 2 NUMBERS IS:" + findBiggest(first, second));
 }

 private static int findBiggest(int first, int second) {
  if (first > second)
   return first;
  return second;
 }

}
----------------------------------------------------------------------------------------------------------------

Best way to re-use CommonUtils class.
4. Calculate factorial of a given number.


package com.thebeautifuljava.simpleprograms;

import com.thebeautifuljava.utils.CommonUtils;

public class Factorial {

 public static void main(String[] args) {

  System.out.println("ENTER NUMBER :");
  int number = CommonUtils.readFromKeyBoard();

  System.out.println("Factorial :" + getFactorial(number));
 }

 private static long getFactorial(int number) {
  // TODO Auto-generated method stub

  int factorial = 1;

  for (int i = 1; i <= number; i++) {
   factorial = factorial * i;
  }

  return factorial;

 }

}
----------------------------------------------------------------------------------------------------------------
5. Print fibonacci series.


package com.thebeautifuljava.simpleprograms;

import com.thebeautifuljava.utils.CommonUtils;

public class FibonacciSeries {

 public static void main(String args[]) {

  System.out.println("ENTER LIMIT :");
  int limit = CommonUtils.readFromKeyBoard();

  printNumbers(limit);
 }

 private static void printNumbers(int limit) {

  int first = 0, second = 1;

  // prints 0 and 1
  System.out.println("FIBONACCI SERIES:");
  System.out.print(first + " " + second);

  for (int i = 2; i < limit; i++) {

   int next = first + second;
   System.out.print(" " + next);

   first = second;
   second = next;
  }
 }
}
----------------------------------------------------------------------------------------------------------------
6. Check whether number is prime.


package com.thebeautifuljava.simpleprograms;

import com.thebeautifuljava.utils.CommonUtils;

public class PrimeNumberCheck {

 public static void main(String args[]) {

  System.out.println("PLEASE ENTER A NUMBER :");
  int number = CommonUtils.readFromKeyBoard();

  // validation check for negative numbers and zero
  if (number <= 0) {
   throw new IllegalArgumentException("PLEASE ENTER A POSITIVE NUMBER");
  }

  if (number == 1) {
  throw new IllegalArgumentException("NUMBER IS NOT PRIME");
  }

  System.out.println("IS PRIME NUMBER :" + isPrime(number));
 }

 private static boolean isPrime(int number) {

  // If number is 50, then sqrt(50) will be 7.071...
  int sqrt = (int) Math.sqrt(number) + 1;

  for (int i = 2; i < sqrt; i++) {
   // check for divisibility of a number
   if (number % i == 0) {
    return false;
   }
  }

  return true;
 }

}
----------------------------------------------------------------------------------------------------------------