Saturday, 18 April 2015

Q. What is the O/P of the following---

 

  if two overloaded methods are:

 

class Test

{

    public static void main(String as[])

    {

        Test t=new Test();

        t.m1(null);

    }

    public void m1(Object obj)

    {

        System.out.println("m1 with obj");

    }

    public void m1(Customer c)

    {

        System.out.println("m1 with Cust");

    }

}

which method will be called and why?


Ans: Jvm will choose the most appropriate methods.Here, we need to know which class is more specialized, Object or Customer.The Customer class is the specialization of Object class.So Customer type method will be called.

 

Thursday, 16 April 2015

Q. What is an SDK ?



Ans: A software development kit (SDK) is typically a set of software development tools whch acts as a platform to start building and developing your application.It includes mainly three things---

1) An IDE (Integrated Development Environment):
it is code editor which allows you to write and edit code eg Eclipse.

2) Performance tools: These include tools for measuring performance, bug finding and also memory leak finding.

3) Build tools:You can use the build tools to build the code into binary package, which can be turned into an app which can then be uploaded.

SDKs also includes sample code and supporting technical notes or other supporting documentation.

Example:
1) iOS xcode for apple devices, visual studios for windows are popular Software Development Kits.

2) The JDK can be called as a subset of a software development kit (SDK).It includes "tools for developing, debugging, and monitoring Java   applications".
 

Tuesday, 14 April 2015

Q. What will happen if final is used and final is removed in the following code.


public class Test

{

    public static void main(String[] args) throws Exception

    {

        final boolean x=true;

        while(x)

        {

            System.out.println("AA");

           

        }

        System.out.println(("BB"));

       

    }}


Ans:If final is used with x then will get C.E  saying Unreachable Code because the condition will always be true. If final is removed then there is a chance that the value of x may be changed (false) and so there is a chance of reaching the statement after while loop and so compilation is successful.


Monday, 13 April 2015

Q. What is the difference between Green Thread and Native Thread?

Ans: Green threads are threads that are scheduled by a virtual machine (VM) instead of natively by the underlying operating system.Green threads emulate multithreaded environments without relying on any native OS capabilities, and they are managed in user space instead of kernel space, enabling them to work in environments that do not have native thread support.


Sunday, 12 April 2015

Q. If the super class implements serializable,then no need that the sub classes would also be implementing serializable interface,then why does HttpServlet class implements Serializable interface when the superclass that it extends, GenericServlet, has already implemented Serializable interface?

Ans: It is not compulsary that if the super class implements serialiable interface then sub class should also implement the same,it is a best practice to declare in the subclass that it also implements the same interface. This way if some one just reads the subclass he will have the complete picture.

Saturday, 11 April 2015

Q. How can we allow duplicate value in set ?



Ans: In the case of Set the hashcode of the object is used to find the place/index where the object will be stored.If somehow we can change the hashcode of the object then the index accessed by using the hashcode will be changed.So same object will be stored in the Set.


Example:
package com.manish.jlc;
import java.util.HashSet;
import java.util.Set;

public class Test1
{
    public static void main(String[] args)
    {
        Set st=new HashSet();
        Student st1=new Student(34);
        st.add(st1);
        st.add(st1);
        st.add(st1);
        st.add(st1);
        System.out.println(st); // [ 34 ]
        st1.age=35;
        st.add(st1);
        System.out.println(st); //[ 35, 35 ]
    }
}
class Student
{
    int age;

    public Student(int age) {
        super();
        this.age = age;
    }
    public int hashCode()
    {
        return this.age;
    }
    public String toString()
    {
        return String.valueOf(age);
    }

 

Wednesday, 25 March 2015

Difference between Encapsulation and Abstraction

Abstraction: Abstraction means representing the essential features without showing the background details.It lets you focus on what the object does instead of how it does.For example: Mobile phone has features calling,messaging etc.A user can call or message without knowing technical details that how a call is connected,how voice is transfered over the network etc.Thus, hiding internal implementation datails and just highlighting the set of services offered is called as Abstraction.

                        Abstraction in java is achieved through interface and abstract class and methods.


                              abstract class MobilePhone

                                {

                                     public abstract call(int number);

                                     public abstract sendMsg(int number,String msg);

                            }


Encapsulation: Binding data and its functionality together into a single unit so that it cannot be accessed directly from outside is called as Encapsulation.

For Example:I have an account in SBI bank.I went to the bank and ask my balance.They will happily tell me my balance.Again,if i ask them to change my balance without withdrawing or depositing any thing,Will they..?. No because i don't have direct access to the property balance.Balance is private member of account class and we cannot directly modify it without using public methods withdraw() or deposit().This is encapsulation.


           Encapsulation in java is achieved through class and access modifier (mainly private ).Hiding data behind the methods is the central concept of encapsulation.If a class has all its member variables private then it is called as tightly encapsulated class.

                            

                           class EncapsulationTest

                                 {

                                       private int a;                                           

                                       private int b;


                                       public int getA()  {    }

                                       public int getB()  {    }

                                       public int setA()  {    }

                                       public int setB()  {    }
                               }


Advantages:

                       1) Security

                       2) Enhancement will become easy.

                       3) Improves modularity of the application.


Note: In the  case of abstraction you are hiding the implementation details from the user and showing only the set of services offered whereas in the case of encapsulation you are hiding the data members from the rest of your code in the application.

Monday, 23 March 2015

Difference between for each loop and an Iterator

package com.manish;
import java.util.*;
public class Test

{

    public static void main(String[] args)

    {

         List lst=new ArrayList();

         lst.add("Manish"); 

         lst.add("Nitesh");

        lst.add("Rupesh"); 

         lst.add("Shubham");

         lst.add("prerit");

// Using for  each we don't have a chance to remove object from the list.

        for(Object l:lst)

        {

            //    lst.remove("Rupesh");     /*    Not OK

 java.util.ConcurrentModificationException   */

        }

        System.out.println(lst);     

 //   O/P    [Manish, Nitesh, Rupesh, Shubham, prerit]

    

// Using iterator we have  a chance to remove  object from the list while iterating  using iterator object.

        Iterator it=lst.iterator();

        while(it.hasNext())

        {

            Object obj=it.next();

            if(obj.equals("Rupesh"))

            {

                 lst.remove("Rupesh");  /*  Not OK it will throw

      java.util.ConcurrentModificationException */

                it.remove();    // OK

            }   

        }

        System.out.println(lst);     

 //  O/P  [Manish, Nitesh, Shubham, prerit]

    }

}

Note: In addition,in the case of for each loop we can access the elements in the forward direction only.If you want to access the elements in both forward and reverse direction then you can use listIterator interface (subclass of Iterator interface).

Saturday, 21 March 2015

Q. How Map allows primitive or integer as key ?



Ans:Map allows object as key and value.In the case of primitive like int, autoboxing (introduced in java 1.5) is done by the compiller.So primitive int is converted to Integer object by the compiller automatically.Thus, Map allows primitive int as key.


                      e.g      package com.manish;

                                 import java.util.*;

                                public class Test

                                {

                                   public static void main(String[] args)

                                    {

                                           Map mp=new HashMap();

                                           mp.put(1, 2);      // OK from 1.5

                                     }

                                 }


The same code will give compillation error when compilled in java 1.4 or lower.


                      e.g      package com.manish;

                                 import java.util.*;

                                public class Test

                                {

                                   public static void main(String[] args)

                                   {

                                     Map mp=new HashMap();

                                     mp.put(1, 2);    // Not OK compillation error in 1.4 version

                                   }

                                 }

Friday, 20 March 2015

Q.Given an array of size 1000 having no's between 1 to 9. Find the number of times each element is repeated in the most efficient way?



                                package com.manish;

                                import java.util.Arrays;

                                public class OccurenceOfNumber 

                                 {


public static void main(String[] args)

{

int arr[]={2,5,8,9,2,1,1,5,5};

Arrays.sort(arr);

for(int i=1;i<arr.length;i++)

{

int low=binarySearchFirst(arr,i);

int high=binarySearchLast(arr,i);

int total=(high>=low && high!=-1 && low!=-1)?(high-low+1):0;

System.out.println(i+" : "+total+" times");

}

}

public static int binarySearchFirst(int arr[],int k)

{

int begin=0;

int end=arr.length-1;

int mid=-1;

while(begin<=end)

{

mid=(begin+end)/2;

if(arr[mid]< k)

{

begin=mid+1;

}

else{

end=mid-1;

}

}

return (begin<=end && begin>=0 && arr[begin]!=k)? -1:begin;

}

public static int binarySearchLast(int arr[],int k)

{

int begin=0;

int end=arr.length-1;

int mid=-1;

while(begin<=end)

{

mid=(begin+end)/2;

if(arr[mid] > k)

{

end=mid-1;

}

else {

begin=mid+1;

}

}

return (end>=begin && end>=0 && arr[end]!=k)? -1:end;

}

                                  }


Q. Given no's 12345.find the sum of all the digits example- 1+2+3+4+5.


                           package com.manish;

                           import java.util.Scanner;

                           public class SumOfDigits

                            {

public static void main(String[] args)

{

int num=new Scanner(System.in).nextInt();

int sum=0;

int input=num;

while(input !=0)

{

int lastdigit=input%10;

sum=sum+lastdigit;

input=input/10;

}

System.out.println(sum);

}

                            }

Q. Find factorial using recursion and iteration ?


                          package com.manish;

                          public class Factorial 

                           {

                              public static void main(String[] args)

{

System.out.println(factorialRecursion(3));

System.out.println(factorialIteration(3));

}

// using iteration

public static int factorialRecursion(int num)

{

if(num==0)

{

return 1;

}

return num*factorialRecursion(num-1);

}

public static int factorialIteration(int num)

{

int res=1;

while(num !=0)

{

res=res*num;

num--;

}

return res;

}

                   }


Q. You are given an array of integers, containing both +ve and -ve numbers. You need to find the two elements such that their sum is closet to zero.

                                    package com.manish;

                                    import java.util.Arrays;

                                    public class MinTest

                                      {

                                            public static void main(String[] args)

                                              {

                                                   int arr[]=new int[]{5,3,1,-8,-8,6};

minSum(arr);

                                              }

                                            public static void minSum(int arr[])

                                              {

                                                  int l, r , min_sum,min_left,min_right,tempsum = 0;

                                                   if(arr.length<2)

                                                   {

                                                        System.out.println("invalid input");

                                                    }

                                                    Arrays.sort(arr);

                                                   l=0;r=arr.length-1;

                                                  min_sum=arr[l]+arr[r];

                                                  min_left=l;

                                                  min_right=r;

                                                   while(l<r)

                                                     {

                                                        tempsum=arr[l]+arr[r];

                                                        if(Math.abs(tempsum) < Math.abs(min_sum))

                                                           {

min_left=l;

                                                                min_right=r;

                                                                min_sum=tempsum;

                                                             }

                                                        if(tempsum < 0) l++;

                                                        else r--;

                                                      }

                                                  System.out.println(arr[min_left]+" "+arr[min_right]);

}

                                   }

  

Q. Write a program to find the fibonacci series by recurssion and iterative way?



                              package com.manish.fiboseries;

                              import java.util.Scanner;

                              public class FibonacciSeries

                                {


public static void main(String[] args)

{

int num=new Scanner(System.in).nextInt();  /* inter the number upto  

                                                   which fibonacci series has to be calculated */

for(int i=1;i<=num;i++) //

{

System.out.print(fibonacciIteration(i)+" ");

}

                                                 System.out.println("");

for(int i=1;i<=num;i++)

{

System.out.print(fibonacciRecursion(i)+" ");

}

}

                                         public static int fibonacciIteration(int number)

                                            {

                                                   if(number == 1 || number == 2)

                                                       {

                                                              return 1;

                                                     }

                                                   int fib1=1, fib2=1, fibonacci=1;

                                                   for(int i= 3; i<= number; i++)

                                                        {

                                                           fibonacci = fib1 + fib2;          

                                                           fib1 = fib2;

                                                           fib2 = fibonacci;

                                                       }

                                                   return fibonacci;

                 }

public static int fibonacciRecursion(int number)     //recursion method

{

                                                  if(number == 1 || number == 2)

                                                      {

                                                            return 1;

                                                    }

                                                   return fibonacciRecursion(number-1)+ fibonacciRecursion(number-2);

                                           }

                          }


Wednesday, 18 March 2015

Q. what is identifier in java?



Ans: Any name in java is called an identfier in java.It may be a method name,class name,variable name etc.

 The allowed characters in identifier are :

1. Alphabets a to z both upper and lower case.

2.Digits 0-9

3.$ and _

e.g- Customer_name, _$Car,_Car etc..


If we are using other then these we will get a compillation error.

  • Identifier cannot start with digits.

          e.g- 123total          // compillation error


  • java identifiers are case sensitive.

         e.g- student and Student are different.

  • Reserved words cannot be used as identifiers.

  • All predefined java class name and interface name we can use as identifier but not recommendable. 

e.g-  class TestIdentifier

      {

            int String=25;       // OK

            System.out.println(String);

       }


Q. Can you execute java application without using main() method ?

Ans:  • Yes, (using static block) before java 7

         • No, from java 7.

Tuesday, 17 March 2015

Q. Is java pure or fully object oriented programing language?

Ans: No, java is not fully object oriented programing language because it supports Primitive data types such as int, byte, long... etc,which are not objects.Smalltalk is a pure OOP language where there are no primitive data types, and boolean, int ... etc are all objects.

Q. What is class, object and instance ?

Ans: Class: class is a blueprint or template which is used to create objects.For example- Suppose you have to make a car and so you made a protype or blueprint on paper that the car will have four wheels,one starring,two headlights etc...etc..Basically, a class will consists of fields,methods and constructors.Field is used to hold the state of the class. Method is used to represent the behavior of the class e.g Car have state (current speed, current gear) and behavior (applying brake, changing gear). Constructor is used to create a new Instance of the Class.


Objects: Now, using that protype or blueprint you can make N number of cars which is nothing but objects.Any entity that has state and behavior is known as an object. An object stores its state in fields and exposes its behavior through methods e.g Car have state (current speed, current gear) and behavior (applying brake, changing gear).


Instance: Nowwill that car created on paper run ...?.No, because it is on paper.An actual object in memory is called an instance.An instance is a unique copy of a class that represents an object. When a new instance of a class is created, the JVM will allocate memory for that class instance.The instance of the object is created using new operator.

      

         e.g   Car c=new Car();


Q. What is keywords in java?How many keywords are there in java?

Q. What is keywords in java?How many keywords are there in java?

Ans: Keywords  are the reserved words in java language that have a predefined meaning.Keywords cannot be used as names for variables, methods, classes, or as any other identifier.There are total 50 keywords in java.  Example: abstract, assert, break, case, catch, class, const, continue, default, do, double, else, enum, extends, final, finally, float, for, goto, if,implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, strictfp, switch, super, synchronized, this, throw, throws,transient,try,void, volatile, while,do.

Q. Is JVM platform independent or dependent?

Ans: JVM is platform dependent.Every  OS  e.g Macintosh, windows or Linux etc. has different JVMs.Java compiller converts the java source file into .class file which is nothing but Byte code or intermediate code which is understood by JVM.Now, JVM  converts the byte code into machine code which is platform specific. Hence,JVM is platform dependent.

Difference between JDK, JRE and JVM

 

Q. What is the difference between JDK, JRE and JVM ?

 

Ans: JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools e.g javac,java etc.


JRE is an acronym for Java Runtime Environment.The JRE provides the libraries, Java virtual machine, and other components necessary to run applets and applications written in the Java programming language.


JVM is the acronym for Java virtual machine.It is an abstract computing machine that has an instruction set and manipulates memory at run time.JVM is platform dependent.

Why java is called Platform Independent OR compile once run anywhere programming language?

 

Q. Why java is called Platform Independent OR compile once run anywhere programming language?

 

Ans:  When a java program is compilled a .class file is generated.This .class file contains the byte code or the intermediate code which is understood by JRE installed on the operating sytems e.g Macintosh, windows or Linux etc. Hence java is called Platform Independent OR compile once run anywhere programming language.

Q. What is Java technology and where it is used?

Q. What is Java technology and where it is used?

Ans: Java is a platform independent programming language  and a computing platform.It was first released by Sun Microsystems as java 1.0 in 1995.It is used in Mobile,Embedded System, Smart Card,Robotics,Games etc.