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

Wednesday, 28 September 2016

How to convert a binary to integer and vice versa ?


int decimalValue = Integer.parseInt(strNum, 2);    // Binary to Decimal
String binaryValue = Integer.toString(num, 2)   // Decimal to Binary






Use 8 for Octal and 16 for Hexadecimal numbers.

Thursday, 2 June 2016

java vs. javaw



  • java command waits for the program to completeYou cannot proceed with next commands.
  • javaw command won't wait for program to completeYou can execute other commands.
    • javaw launches program in background

Sunday, 8 May 2016

How to evaluate a postfix expression ?


Postfix notation represents a algebraic expression.
These are evaluated faster than infix notation, as ( ) are not required.

Algorithm - using Stack

  • For each element in postfix string
    • if element is an operand
      • push element into Stack => Operand
    • else  // Operator
      • Pop from Stack => Operand 1
      • Pop from Stack => Operand 2
      • Evaluate value using both operands and element (Operator) => value
      • Push the value to Stack
  • Pop the element of Stack => Final result


Example
String postfix = "2 3 1 * + 9 -"

element
oprnd1
oprnd2
value
stack
2



2
3



2,3
1



2,3,1
*
3
1
3*1
2,3
+
3
2
3+2
5
9



5,9
-
5
9
5-9
-4


Java code
public static int evaluatePostfix(String postfixStr) {
  String[] postfixArr = postfixStr.split("");
  Stack<Integer> stack = new Stack<Integer>();

  for(String element : postfixArr) {
      boolean isOperator = isOperator(element);
      if(isOperator) {
         int value1 = stack.pop();
         int value2 = stack.pop();
         int value = calculate(value2, value1, element);
         stack.push(value);
      else {
         stack.push(Integer.valueOf(element));
      }
  }

  return stack.pop();
}

private static int calculate(int a, int b, String operator){
  int result = 0;
  if("+".equals(operator)) {
    result = (a+b);
  else if("-".equals(operator)) {
    result = (a-b);
  else if("*".equals(operator)) {
    result = (a*b);
  else if("/".equals(operator)) {
    result = (a/b);
  
  return result;
}

private static boolean isOperator(String element) {
  if("+".equals(element) || "-".equals(element) 
         || "/".equals(element) || "*".equals(element)) {
     return true;
  }
  return false;
}

How to check if a number is prime (primality) using Java API ?


Use Java.math.BigInteger.isProbablePrime() which uses Miller–Rabin primality Algo.

Example
BigInteger num = BigInteger.valueOf(number);
System.out.println("is Prime number ? " + num.isProbablePrime());

How to generate next prime number of any number using Java API ?


Use Java.math.BigInteger.nextProbablePrime()

Example
BigInteger num = BigInteger.valueOf(number);
BigInteger nextPrimeNum = num.nextProbablePrime();
System.out.println("Next prime number : " + nextPrimeNum);

Monday, 25 April 2016

Q&A on Inner classes


Q&A on Inner classes

Q 1. What modifiers can be used with a local inner class ? 
A local inner class may be final or abstract

Q 2. Can an inner class declared inside of a method access local variables of this method ?
It's possible, if these variables are final.

What is the need of Serialization ?


Need of Serialization
  • To save the state of an object in a file.
  • An object’s state needs to be manipulated as a stream of bytes.
  • To send state of one or more object’s state over the network through a socket.

instanceof vs. isInstance(Object obj)


 instanceof 
keyword vs. isInstance method

1. instanceof is a reserved word of Java.
    isInstance(Object obj) is a method of java.lang.Class.

2.  instanceof is used of identify whether the object is type of a particular class or its subclass.
     isInstance(obj) is used to identify object of a particular class.

Example
if (obj instanceof MyType) {
   ...
} else if (MyType.class.isInstance(obj)) {
   ...
}

Immutable objects


Immutable Objects
Mutable Objects: When the contents of instance can be changed.
Example - StringBuffer

Immutable Objects: When the contents of instance cannot be changed.
Example - String, Integer, Float


Advantages of immutable classes/object
1) Immutable objects are automatically thread-safe, the overhead caused due to use of synchronization is avoided.

2) Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.

3) The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.

4) The best use of the immutable objects is as the keys of a map.


Building an Immutable class
1. Remove all the mutators
If we removed all of the mutators from the class, would it be Immutable?
No! it wouldn't.
Removing mutators is a necessary first step, but immutability requires more than that to ensure that the contents of an instance never changes.

2. Fields must be private
This is almost enough, but there are two more steps to consider.

3. Make sure class can't be extended or methods can't be overridden
If your class gets extended, it could add extra fields that are not immutable, or the methods could be overridden to return a different value each time.

There are two ways to protect against this :
 1. Strong immutability : Make class final (preferred way)
 2. Weak immutability : Make methods final (Allow class to be extended but protects the original contract specified by the class)

4. Protect mutable fields
Build your immutable class from primitive types or immutable fields, otherwise (for example : java.util.Date type field) you have to protect mutable fields from manipulation.
If a field isn't primitive or immutable, make deep copies of mutable data.
When you copy the instance on the way in and the way out, you need to make a deep copy. Otherwise you run the risk of leaving some mutable data in your immutable class.
  
Example

// RULE 1 - Make the class final (Strong immutability) ; 
// otherwise, You can make all the methods final (Weak immutability)
public final class Employee {
   // RULE 2 - Make all fields private
   private int empId;
   private String empName;
   private java.util.Date joiningDate;

   // RULE 3 - Don't provide mutators (setters) for fields
   // Keeping accessors (getters) are safe
   public int getEmpId() {
      return empId;
   }
   public String getEmpName() {
      return empName;
   }

   // RULE 4 - Protect mutable fields from manipulation : 
   // Make deep copies of mutable data
   public String getJoiningDate() {
      return new java.util.Date( joiningDate.getTime() );
   } 
}


Guidelines
Setters and getters, along with properties should only be created when you find you need them and Not every by default.
You may be needing getters pretty regularly, so keep them.
Setters or writable properties should ever exist in your code through a builder pattern where they are locked down after the object has been completely instantiated.

Programmer should keep in mind that setter is almost same as directly manipulating the property.


Which Java classes are Immutable ?
  • All of the java.lang package wrapper classes : Boolean, Byte, Character, Double, Float, Integer, Long, Short
  • String claas


Where to use immutable objects ?
Where we need a value or fixed instance, Like : 
 1. A color is usually thought of as a value, thus the immutable Color class. (i.e. Green color is a fixed color and cannot represent other color)
 2. A playing card that has a fixed unchanging suit and rank once created (i.e. Paan ka Ikka)
 3. Classes for representing complex numbers or arbitrary-precision rational numbers can be immutable.
 4. Abstract types which contains many discrete values, such as vectors or matrices.


Where not to use ?
 1. The fuel capacity and speed of a car would keep on changing in a racing game, hence making Car object immutable and keep on creating new instances while the state changes is not meaningful.
      You have to avoid creating immutable objects in this case.
 2. All above mentioned immutable objects, could also be defined mutable depending on their usage and need in application.


Why we don’t see immutable objects in our application ?
 1. Programmers don't know when and how to use immutability because they are not familiar with it.

 2. Many programers learn how to program using an imperative (procedural or object-oriented) paradigm, therefore mutability is their basic approach.
     Programmers assumes that generating getters/setters both for all properties of class is the part of OOPs programming.
     It's a mindset 

 3. Using automatic getter / setter generation facility in all Java programming IDEs does not consider the requirement of avoidable methods.

 4. For programmers, it is often more effective to first focus on writing a program that is functionally correct, and then try to find bottlenecks and optimize it.
     They think immutability is a part of optimization.