Powered By Blogger

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;
 }

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