Monday 29 February 2016

Advantages of immutable class in Java

1. They are less prone to error and are more secure.

2. Immutable classes are easier to design, implement, and use than mutable classes.

3. Immutable objects are thread-safe so there are no synchronization issues.

4. Immutable objects are good Map keys and Set elements, since these typically do not change once created.

5. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged).

6. Immutability makes it easier to parallelize program as there are no conflicts among objects.

7. The internal state of program will be consistent even if you have exceptions.

8. References to immutable objects can be cached as they are not going to change. (i.e in Hashing it provide fast operations).


References: 
https://en.wikipedia.org/wiki/Immutable_object

Sunday 28 February 2016

Can we instantiate abstract class?

No, we cannot instantiate the abstract class. Because it's abstract and an object is concrete.

An abstract class is sort of like a template, or an empty/partially empty structure, we have to extend it and build on it before we can use it.


abstract class AbstractClass {
    public void method() {
        System.out.print("Abstract class method!!");
    }
}


There is compile time error while instantiating the abstract class.


public class  InstantiateAbstract {
     public static void main(String[] args) {
        AbstractClass object = new AbstractClass();
        object.method();
     }
}
Compile time error: Cannot instantiate the type AbstractClass


Now program is executing without any error.


public class  InstantiateAbstract {
     public static void main(String[] args) {
        AbstractClass object = new AbstractClass() {};
        object.method();
     }
}

Output:
Abstract class method!!


There is some difference to notice?
new AbstractClass() vs. new AbstractClass (){ };;

In the second case, extra curly braces are there, which is the body of a new, nameless class (anonymous class) that extends the abstract class. You have created an instance of an anonymous class and not of an abstract class.

Important point:

If there is any abstract method in abstract class, it is compulsory to provide the implementation of the abstract method inside the curly braces i.e. Compiler will force you to implement the abstract method inside {} of anonymous class.

References:
https://en.wikipedia.org/wiki/Abstract_type
https://en.wikipedia.org/wiki/Class_(computer_programming)

Dependency Lookup


The Dependency Lookup is an approach where we get the resource after demand. Various ways to get the resource are mentioned below:

Using new keyword
ClassA obj = new ClassAImpl(); 

Static factory method
ClassA  obj = ClassA.getClassA(); 

Using JNDI (Java Naming Directory Interface) :
Context ctx = new InitialContext();
Context environmentCtx = (Context) ctx.lookup ("java:comp/env"); 
ClassA obj = (ClassA)environmentCtx.lookup("ClassA "); 

Problems of Dependency Lookup
Tight coupling: The dependency lookup approach makes the code tightly coupled. If resource is changed, we need to perform a lot of modification in the code.

Not easy for testing: This approach creates a lot of problems while testing the application especially in black box testing.

Dependency Injection (DI) is a design pattern that removes the dependency from the code so that it can be easy to manage and test the application. It makes our programming code loosely coupled.

This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.

The org.springframework.beans and org.springframework.context packages are the basis for Spring Framework’s IoC container.


How to Convert String to Int without using Integer.parseInt() method: Code With Example

As integer can be positive and negative, here two cases arise.

Use cases#
Case#1: If string is positive
If user inputs  "12312", then it should give output 12312 as an int number

Case#2: If string is negative
If user inputs "-47939", then it should give output -47939 as an int number.

Case#3: If string contains alphabetic character like "12ab6", it should print an error.

Approach#
We will traverse the character array as we know String is the array of character.

Step#1: int_value = 0;

Step#2: Traverse the Character array from right to left.

Step#3: Find the place_value of the Character because the ASCII value is different of character to string.

Step#4: Multiplying the place value by 10 each time and add to sum.
              int_value = int_value + place_value * 10;


import java.text.ParseException;
public class IntegerParser {

     public static int parseInt(String str) throws ParseException {
           int i = 0, number = 0;
           boolean isNegative = false;
           char[] value = str.toCharArray();
           if(value[0] == '-') {
                isNegative = true;
                i = 1;
           }

           while(i < value.length) {
                char ch = value[i++];
                int place_value = ch - '0';
                if(place_value>=0 && place_value<=9) {
                     number *= 10;
                     number += (ch - '0');
                } else {
                    System.out.println("Wrong input format!!");
                    throw new ParseException("String to int parse",-1);
                }
           }
           if(isNegative) {
                number = -number;
           }
           return number;
     }


     public static void main (String args[]) throws ParseException {
           String  convertingString="1243";
           int integer = parseInt(convertingString);
           System.out.println(integer);

           convertingString="-1243";
           integer = parseInt(convertingString);
           System.out.println(integer);
          
           convertingString="-12a43";
           integer = parseInt(convertingString);
           System.out.println(integer);

     }
}

Output:
1243
-1243
Wrong input format!!
Exception in thread "main" java.text.ParseException: String to int parse
     at IntegerParser.parseInt(IntegerParser.java:39)
     at IntegerParser.main(IntegerParser.java:17)



For suggestions/doubts, please put your comments.

Saturday 27 February 2016

How do I redirect standard output to a file using System.out.println()?

System.out.println() is used to print messages on the console.

System is a class defined in the java.lang package. out is an instance of PrintStream, which is a public and static member of the class System. As all instances of PrintStream class have a public method println().

System.out is a static PrintStream that writes to the console. We can redirect the output to a different PrintStream using the System.setOut() method which takes a PrintStream as a parameter.


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class SetPrintStream {
  public static void main(String[] args) throws FileNotFoundException{
           System.out.println("Print on console");
          
           // Store console print stream.
           PrintStream ps_console = System.out;
          
           File file = new File("file.txt");
           FileOutputStream fos = new FileOutputStream(file);
          
           // Create new print stream for file.
           PrintStream ps = new PrintStream(fos);
          
           // Set file print stream.
           System.setOut(ps);
           System.out.println("Print in the file !!");

           // Set console print stream.
           System.setOut(ps_console);
           System.out.println("Console again !!");
 }
}

Output:
Print on console
Console again !!
    
new file.txt will be created.

Related Posts Plugin for WordPress, Blogger...