AdSense

AdSense3

Monday, 6 July 2015

Java Important Interview Programs - 1

1. Find out duplicate number between 1 to N numbers.


Description:
You have got a range of numbers between 1 to N, where one of the number is
repeated. You need to write a program to find out the duplicate number.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package kundan;
import java.util.ArrayList;
import java.util.List;
public class DuplicateNumber {
    public int findDuplicateNumber(List<Integer> numbers){
         
        int highestNumber = numbers.size() - 1;
        int total = getSum(numbers);
        int duplicate = total - (highestNumber*(highestNumber+1)/2);
        return duplicate;
    }
     
    public int getSum(List<Integer> numbers){
         
        int sum = 0;
        for(int num:numbers){
            sum += num;
        }
        return sum;
    }
     
    public static void main(String a[]){
        List<Integer> numbers = new ArrayList<Integer>();
        for(int i=1;i<30;i++){
            numbers.add(i);
        }
        //add duplicate number into the list
        numbers.add(22);
        DuplicateNumber dn = new DuplicateNumber();
        System.out.println("Duplicate Number: "+dn.findDuplicateNumber(numbers));
    }
}

Output:
Duplicate Number: 22

2. Find out middle index where sum of both ends are equal.


Description:
You are given an array of numbers. Find out the array index or position
where sum of numbers preceeding the index is equals to sum of numbers
succeeding the index.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package kundan;
public class FindMiddleIndex {
    public static int findMiddleIndex(int[] numbers) throws Exception {
        int endIndex = numbers.length - 1;
        int startIndex = 0;
        int sumLeft = 0;
        int sumRight = 0;
        while (true) {
            if (sumLeft > sumRight) {
                sumRight += numbers[endIndex--];
            } else {
                sumLeft += numbers[startIndex++];
            }
            if (startIndex > endIndex) {
                if (sumLeft == sumRight) {
                    break;
                } else {
                    throw new Exception(
                            "Please pass proper array to match the requirement");
                }
            }
        }
        return endIndex;
    }
    public static void main(String a[]) {
        int[] num = { 2, 4, 4, 5, 4, 1 };
        try {
            System.out.println("Starting from index 0, adding numbers till index "
                            + findMiddleIndex(num) + " and");
            System.out.println("adding rest of the numbers can be equal");
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Output:
Starting from index 0, adding numbers till index 2 and
adding rest of the numbers can be equal

3. Write a singleton class.


Description:
Singleton class means you can create only one object for the given class. You can create a singleton class by making its constructor as private, so that you can restrict the creation of the object. Provide a static method to get instance of the object, wherein you can handle the object creation inside the class only. In this example we are creating object by using static block.

Code:
package kundan;

public class MySingleton {

 private static MySingleton myObj;
 
 static{
  myObj = new MySingleton();
 }
 
 private MySingleton(){
 
 }
 
 public static MySingleton getInstance(){
  return myObj;
 }
 
 public void testMe(){
  System.out.println("Hey.... it is working!!!");
 }
 
 public static void main(String a[]){
  MySingleton ms = getInstance();
  ms.testMe();
 }
}

4. Write a program to create deadlock between two threads.


Description:
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. 
Deadlocks can occur in Java when the synchronized keyword causes the executing thread to block while waiting 
to get the lock, associated with the specified object. Since the thread might already hold locks associated with 
other objects, two threads could each be waiting for the other to release a lock. In such case, they will end up waiting forever.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package kundan;
public class MyDeadlock {
    String str1 = "Java";
    String str2 = "UNIX";
     
    Thread trd1 = new Thread("My Thread 1"){
        public void run(){
            while(true){
                synchronized(str1){
                    synchronized(str2){
                        System.out.println(str1 + str2);
                    }
                }
            }
        }
    };
     
    Thread trd2 = new Thread("My Thread 2"){
        public void run(){
            while(true){
                synchronized(str2){
                    synchronized(str1){
                        System.out.println(str2 + str1);
                    }
                }
            }
        }
    };
     
    public static void main(String a[]){
        MyDeadlock mdl = new MyDeadlock();
        mdl.trd1.start();
        mdl.trd2.start();
    }
}

5. Write a program to reverse a string using recursive algorithm.


Description:
Write a program to reverse a string using recursive methods.
You should not use any string reverse methods to do this.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package kundan;
public class StringRecursiveReversal {
    String reverse = "";
     
    public String reverseString(String str){
         
        if(str.length() == 1){
            return str;
        } else {
            reverse += str.charAt(str.length()-1)
                    +reverseString(str.substring(0,str.length()-1));
            return reverse;
        }
    }
     
    public static void main(String a[]){
        StringRecursiveReversal srr = new StringRecursiveReversal();
        System.out.println("Result: "+srr.reverseString("kundan"));
    }
}

Output:
Result: nadnuk

6. Write a program to reverse a number.


Description:
Write a program to reverse a number using numeric operations. Below example shows how to reverse a number using numeric operations.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package kundan;
public class NumberReverse {
    public int reverseNumber(int number){
         
        int reverse = 0;
        while(number != 0){
            reverse = (reverse*10)+(number%10);
            number = number/10;
        }
        return reverse;
    }
     
    public static void main(String a[]){
        NumberReverse nr = new NumberReverse();
        System.out.println("Result: "+nr.reverseNumber(17868));
    }
}

Output:
Result: 86871

7. Write a program to convert decimal number to binary format.


Description:
Write a program to convert decimal number to binary format using numeric operations. Below example shows how to convert decimal number to binary format using numeric operations.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package kundan;
public class DecimalToBinary {
    public void printBinaryFormat(int number){
        int binary[] = new int[25];
        int index = 0;
        while(number > 0){
            binary[index++] = number%2;
            number = number/2;
        }
        for(int i = index-1;i >= 0;i--){
            System.out.print(binary[i]);
        }
    }
     
    public static void main(String a[]){
        DecimalToBinary dtb = new DecimalToBinary();
        dtb.printBinaryFormat(25);
    }
}

Output:
11001

8. Write a program to find perfect number or not.


Description:
A perfect number is a positive integer that is equal to the sum
of its proper positive divisors, that is, the sum of its positive
divisors excluding the number itself. Equivalently, a perfect number
is a number that is half the sum of all of its positive divisors.
The first perfect number is 6, because 1, 2 and 3 are its proper
positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6
is equal to half the sum of all its positive divisors:
  ( 1 + 2 + 3 + 6 ) / 2 = 6.

Code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package kundan;
public class IsPerfectNumber {
    public boolean isPerfectNumber(int number){
         
        int temp = 0;
        for(int i=1;i<=number/2;i++){
            if(number%i == 0){
                temp += i;
            }
        }
        if(temp == number){
            System.out.println("It is a perfect number");
            return true;
        } else {
            System.out.println("It is not a perfect number");
            return false;
        }
    }
     
    public static void main(String a[]){
        IsPerfectNumber ipn = new IsPerfectNumber();
        System.out.println("Is perfect number: "+ipn.isPerfectNumber(28));
    }
}

Output:
28
It is a perfect number
Is perfect number: true

Android Core Building Blocks

android components
An android component is simply a piece of code that has a well defined life cycle e.g. Activity, Receiver, Service etc.
The core building blocks or fundamental components of android are activities, views, intents, services, content providers, fragments and AndroidManifest.xml.

Activity

An activity is a class that represents a single screen. It is like a Frame in AWT.

View

A view is the UI element such as button, label, text field etc. Anything that you see is a view.

Intent

Intent is used to invoke components. It is mainly used to:
  • Start the service
  • Launch an activity
  • Display a web page
  • Display a list of contacts
  • Broadcast a message
  • Dial a phone call etc.
For example, you may write the following code to view the webpage.

Service

Service is a background process that can run for a long time.
There are two types of services local and remote. Local service is accessed from within the application whereas remote service is accessed remotely from other applications running on the same device.

Content Provider

Content Providers are used to share data between the applications.

Fragment

Fragments are like parts of activity. An activity can display one or more fragments on the screen at the same time.

AndroidManifest.xml

It contains informations about activities, content providers, permissions etc. It is like the web.xml file in Java EE.

Android Virtual Device (AVD)

It is used to test the android application without the need for mobile or tablet etc. It can be created in different configurations to emulate different types of real devices.

Sunday, 5 July 2015

Java Important Interview Questions - 4

76. What is dynamic class loading?


Answer:
Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Let us
look at how to load classes dynamically by using Class.forName (String className); method, it is a static method.
The above static method returns the class object associated with the class name. The string className can be 
supplied dynamically at run time. Once the class is dynamically loaded the class.newInstance () method returns an instance of the loaded class. It is just like creating a class object with no arguments.
ClassNotFoundException is thrown when an application tries to load in a class through its class name, but no definition for the class with the specified name could be found.

77. What happens if you do not provide a constructor?


Answer:
Java does not actually require an explicit constructor in the class description. If you do not include a constructor,
the Java compiler will create a default constructor in the byte code with an empty argument.

78. Can we have interfaces with no defined methods in java?


Answer:
The interfaces with no defined methods act like markers. They just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently. Marker interfaces are also known as “tag” interfaces.

79. What is the difference between “= =” and equals() method?


Answer:
The == (double equals) returns true, if the variable reference points to the same object in memory. This is called “shallow comparison”.
The equals() method calls the user implemented equals() method, which compares the object attribute values. 
The equals() method provides “deep comparison” by checking if two objects are logically equal as opposed to the shallow comparison provided by the operator ==.
If equals() method does not exist in a user supplied class then the inherited Object class's equals() method will be
called which evaluates if the references point to the same object in memory. In this case, the object.equals() 
works just like the "==" operator.

80. How can you create an immutable class in java?


Answer:
Here are the steps to create immutable class:
Declare the class as final, we can not extend the final class.
public final class MyTestImmutable { ... }
Declare all fields as final. Final fields can not be changed once its assigned.
private final int salary;
Do not provide any method which can change the state of the object, for example the setter methods which 
changes the values of the instance variables.
The “this” reference is not allowed to escape during construction from the immutable class and the immutable 
class should have exclusive access to fields that contain references to mutable objects like arrays, collections and mutable classes like Date etc by:
Declaring the mutable references as private. 

81. What are access modifiers in java?


Answer:
public: A class or interface may be accessed from outside the package. Constructors, inner classes, methods and field variables may be accessed wherever their class is accessed.
protected: Accessed by other classes in the same package or any subclasses of same package or different package.
private: Accessed only within the class in which they are declared.
no modifier (default modifier): Accessed only with in the class.

82. Can we have private constructor in java?


Answer:
Private constructor is used if you do not want other classes to instantiate the object.
Private constructors are used in singleton design pattern, factory method design pattern.

83. Why do we need generics in java?


Answer:
Code that uses generics has many benefits over non-generic code:
1) Stronger type checks at compile time: A Java compiler applies strong type checking to generic code and 
issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, 
which can be difficult to find.
2) Elimination of casts: If you use generics, then explicit type casting is not required.
3) Enabling programmers to implement generic algorithms: By using generics, programmers can implement
generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

84. What is the difference between a product and a project?


Answer:
A project is an endeavor with a clear definition of what needs to be delivered and the date when it needs to be
delivered. Actually, it may seem that a product is a project, but it is not. Because, there is no clear definition of 
what needs to be delivered and there is no clear definition of the the date when it needs to be delivered.
The product backlog is a collection of all possible ideas and additions to a product. The stories in the product
backlog have no particular priority or schedule, although you can sort and organize them in hierarchies in the breakdown view by drag & drop. Thus, if you wish to prioritize your stories but don’t want to create projects or iterations, just use the breakdown view!
Products are developed in projects.

85. How does substring() method works on a string?


Answer:
String in java is a sequence of characters. String is more like a utility class which works on that character sequence. This character sequence is maintained as a array called value[], for example
private final char value[];
String internally defines two private variables called offset and count to manage the char array. The declarations can be as shown below:
/** The offset is the first index of the storage that is used. */
private final int offset;

/** The count is the number of characters in the String. */
private final int count;
Everytime we create a substring from any string object, substring() method assigns the new values of offset and
count variables. The internal char array is unchanged. This is a possible source of memory leak if substring()
method is used without care.

86. What is the difference between a Java Library and a framework?


Answer:
A library is a collection of class definitions and its implementations. The main benifits of creating library is
simply code reuse. A simple example is one of the other developer written code for sending emails. If you think
it is a generic module. Most of the places this code can be reusable. If we can make it a library (jar), we can include this library in our code, and call those methods. The classes and methods normally define specific operations in a domain specific area.

In framework, all the control flow is already defined, and there is a bunch of predefined places that you should fill out with your code. We use framework to develop applications. A framework defines a skeleton where the application defines its own features to fill out the skeleton. In this way, your code will be called by the framework when appropriately. The benefit is that developers do not need to worry about if a design is good or not, but just about implementing domain specific functions.

87. What is difference between Lambda Expression and Anonymous class?


Answer:
The key difference between Anonymous class and Lambda expression is the usage of 'this' keyword. In the anonymous classes, ‘this’ keyword resolves to anonymous class itself, whereas for lambda expression ‘this’ keyword resolves to enclosing class where lambda expression is written.
Another difference between lambda expression and anonymous class is in the way these two are compiled. Java compiler compiles lambda expressions and convert them into private method of the class. It uses invokedynamic instruction that was added in Java 7 to bind this method dynamically.

88. Can Enum extend any class in Java?


Answer:
Enum can not extend any class in java, the reason is by default, Enum extends abstract base class java.lang.Enum. Since java does not support multiple inheritance for classes, Enum can not extend another class.

89. Can Enum implements any interface in Java?


Answer:
Yes, Enum can implement any interface in Java. Since enum is a type, similar to any other class and interface, it can implement any interface in java. This gives lot of flexibility in some cases to use Enum to implement some other behavior.

90. Can we have constructor in abstract class?


Answer:
You can not instantiate abstract class in java. In order to use abstract class in Java, You need to extend it and 
provide a concrete class. Abstract class is commonly used to define base class for a type hierarchy with default implementation, which is applicable to all child classes. Now based on these details, can we have constructor in abstract class?
                    The answer is YES, we can have. You can either explicitly provide constructor to abstract class or if you don't, compiler will add default constructor of no argument in abstract class. This is true for all classes and its also applies on abstract class.

91. What is MVC pattern?


Answer:
MVC is a design pattern called Model-View-Controller. It decouples data access logic from business logic.
Model:
The Model contains the core of the application's functionality. It encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
View:
The view provides the presentation of the model. It is the look and feel of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.
Controller:
The controller reacts to the user input. It creates and sets the model and helps to identify which view should be part of response.

92. What is Spring?


Answer:
Spring is an open source development framework for enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.
Basically Spring is a framework for dependency-injection which is a pattern that allows to build very decoupled systems.
Spring is a good framework for web development. Spring MVC is one of the many parts of Spring, and is a web framework making use of the general features of Spring, like dependency injection. It is a pretty generic framework in that it is very configurable: you can use different DB layers (Hibernate, iBatis, plain JDBC), different view layers (JSP, Velocity, Freemarker...)