Friday, 26 February 2016

How to get the standard input from console in Java?

Using Scanner class:

Scanner scanner = new Scanner(System.in); String input;
while(scanner.hasNextLine()) {
     input = scanner.nextLine(); 
     System.out.println(input);
}

scanner.close(); // Close to avoid the Resource leak.

Scanner close methods:
next, nextByte, nextShort, nextInt, nextLong, nextFloat, nextDouble.

Using InputStreamReader:

BufferedReader br = new BufferedReader(new InputStreamReader (System.in) );

String input;
while((input=br.readLine()) != null) {
     System.out.println(input);
}


Which one should be opt?
It depends on the developer’s requirement.

For performance perspective, character by character reading from an unbuffered input stream or reader is inefficient. If the file needs to be read that way, developer should prefer BufferedReader.

What is the difference between thin and thick client?

The thin vs. thick distinction usually refers to how much processing or "business logic" is done on the client.

Thin client:
Basically, a thin client is a web based application and most of the processing is done on the server side.

Example:
Web browser is the classic example of thin client. It can be the client application for anyone's server application.

The client can be generic like a web browser, and since most of the logic takes places on the central server, it's much easier to push updates out to the clients.

Advantage of thin clients is they make fewer demands on the client machine, which can be anything from a computer to a smart phone to a household device like a blender or TV set top box.

Thick client:
A thick client is more like a standalone application, which run on the client machine and communicates with the server less frequently.

With thick client, there won't be much processing via the network. In a way, it will be a much faster option if your network is slow or congested.

Example:
A virus scanner is a good example. It downloads new virus definitions from the server, but then runs its scan on the client machine without further communication to the server.

Advantage of thick clients is that the performance isn't tied to the load on the server, and the speed of the network connection.


Swapping of two numbers without using third variable

Approach#1.
Addition and Subtraction Method

Integer a, b
read a and b
a= a+b;
b=a-b;
a=a-b;

Problem:
Incorrect result when sum of numbers will exceed the Integer range.


Approach#2. 
Multiplication and Division Method

Integer a, b
read a and b
a=a*b;
b=a/b;
a=a/b;

Problems:
1. If the value of a*b exceeds the range of integer.
2. If the value of a or b is zero then it will give wrong results.

Approach#3.
XOR Method

Integer a , b
read a and b
a=a^b;
b=a^b;
a=a^b;

Best approach to solve this problem without any pitfalls.



Monday, 22 February 2016

How to format messages in Java?

MessageFormat

The MessageFormat class can be used quite nicely to compose messages.

MessageFormat takes a set of objects, formats them, then inserts the formatted strings into the pattern at the appropriate places.

import java.text.*;

public class MessageFormator {

     public static void main(String[] args) {
           String message="Request id# {0} will be resolve till {1}.";
           Object values[] = { "1325", "25-Mar-2016" };
           String s = MessageFormat.format(message, values);
           System.out.println(s);
    }
}
Output:
Request id# 1325 will be resolve till 25-Mar-2016.







Thursday, 18 February 2016

5 Class Design Principles in Java

[S.O.L.I.D.]
The 5 Class Design Principles

S.O.L.I.D is the acronym for five basic principles of object-oriented programming to design a class.

Single responsibility
Open-closed
Liskov substitution
Interface segregation and
Dependency inversion.

S.O.L.I.D principles help us to create a system that is easy to maintain and extend over time. Well designed and written classes can speed up the coding process by leaps and bounds, while reducing the number of bugs in comparison.

Classes are the building blocks of System. If these blocks are not strong, your building (i.e. System) is going to face the tough time in future.

If Classes are not so well-written, can lead to very difficult situations when the application scope goes up or application faces certain design issues either in production or maintenance.

It is part of an overall strategy of agile and Adaptive Software Development.

S
Single responsibility principle
“a class should have only a single responsibility” (i.e. only one potential change in the software's specification should be able to affect the specification of the class)
O
Open/closed principle
“software entities … should be open for extension, but closed for modification.”

L
Liskov substitution principle

“objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.”

I
Interface segregation principle

“many client-specific interfaces are better than one general-purpose interface.”
D
Dependency inversion principle

one should “Depend upon Abstractions. Do not depend upon concretions.”


Introduced by Michael Feathers for the "first five principles" named by Robert C. Martin in the early 2000s.

Wednesday, 17 February 2016

Difference between ArrayIndexOutfOBounds and ArrayStoreException

ArrayIndexOutOfBoundsException: Since JDK1.0

ArrayIndexOutOfBoundsException occurs when your code tries to access an invalid index for a given array e.g. negative index or higher index than length - 1.

java.lang.Object à
   java.lang.Throwable à
      java.lang.Exception  à
         java.lang.RuntimeException  à
            java.lang.IndexOutOfBoundsException à
               java.lang.ArrayIndexOutOfBoundsException

public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

ArrayStoreException:  Since JDK1.0

ArrayStoreException occurs when you have stored an element of type other than type of array.

java.lang.Object à
   java.lang.Throwable à
      java.lang.Exception  à
         java.lang.RuntimeException  à
            java.lang.ArrayStoreException

public class ArrayStoreException extends RuntimeException
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

Example:
Object x[] = new String[3];
x[0] = new Integer(0);


Tuesday, 16 February 2016

Find the element repeated more than n/2 times

There is an array (of size N) with an element repeated more than N/2 number of time and the rest of the element in the array can also be repeated but only one element is repeated more than N/2 times. Find the number.

Approach#1
Keep the count of each number in a hash map.
Extra space required for this approach.

Approach#2
Simplest, sort the array and the number at n/2+1th index is the required number.
Time complexity to sort array is: O (nlogn).

Approach#3
Moore’s Voting Algorithm
1. Define two variables majority_elem to keep track of majority element and counter (count).
2. Initially we set the first element of the array as the majority element.
3. Traverse the array:
a. If the current element == majority_elem
Increment count
    else
Decrement count

b. If count becomes zero,
Set count = 1
Set majority_elem = current element.
4. Print majority_elem.

array = [1, 2, 3, 4, 5, 5, 5, 5, 5 ]
majority_elem = items[0]
count = 1

for i ß0 to end {
if (items[i] == majority_elem) {
          count += 1;
            } else {
          count -= 1
            }

           if (count == 0) {
                majority_elem = items[i];
                count = 1;
            }
}
print(majority_elem)

Note:  For boundary condition, Check that the occurrence of element is more than n/2.


Intuition behind the algorithm:
Suppose that you were to have a roomful of people each holding one element of the array. Whenever two people find each other where neither is holding the same array element as the other, the two of them sit down. Eventually, at the very end, if anyone is left standing, there's a chance that they're in the majority, and you can just check that element. As long as one element occurs with frequency at least N/2, you can guarantee that this approach will always find the majority element. 
Related Posts Plugin for WordPress, Blogger...