Tuesday, 24 December 2013

Unknown

Dynamic Binding in java


Suppose you have 3 Java classes: A, B, and C. Class B extends A, and class C extends B. Think of the class inheritance hierarchy alphabetically – with A at the top, then B in the middle, and finally C on the bottom. All 3 classes implement the instance method void doIt(). A reference variable is instantiated as "A x = new B();" and then x.doIt() is executed. What version of the doIt() method is actually executed and why?



Yikes! This a long question, and could be confusing when you see it the first time – but it’s really not that bad at all. The best way to solve something like this is to write out the actual code. With that in mind here is what the Java code would look like:
class A
{
  public doIt( )
  {
    //this does something
  }
}

class B extends A
{
  public doIt( )
  {
    //this does something
  }
}

class C extends B
{
  public doIt( )
  {
    //this does something
  }

}

public static void main(String[] args) {


// this is a legal Java statement:
A x = new B( );


/*
What version of the doIt( ) method
will get executed by the statement below
- the one that belongs to class A, B, or C?
*/

x.doIt( );
  
}
So, given the code above the question is which version of the doIt( ) method will be executed – the one in class A, B, or C?
The statement that causes a lot of confusion is the “A x = new B();” statement. What exactly is going on here? Well, although the variable x is an object of type A, it is instantiated as an object of class B – because of the “= new B( );” part of the statement. The Java runtime will basically look at this statement and say “even though x is clearly declared as type A, it is instantiated as an object of class B, so I will run the version of the doIt() method that is defined in class B.”

Understanding the example of dynamic binding in the code above

The version of the doIt() method that’s executed by the object x is the one in class B because of what is known as dynamic binding in Java – the code above can be considered to be an example of dynamic binding. Dynamic binding basically means that the method implementation that is actually called is determined at run-time, and not at compile-time. And that’s why it’s called dynamic binding – because the method that will be run is chosen at run time. Dynamic binding is also known as late binding.
Read More

Monday, 23 December 2013

Unknown

how final modifier works in java

In Java, what does the ‘final’ modifier mean when applied to a method, class, and an instance variable?

 

  • When applied to a method definition the final modifier indicates that the method may not be overridden in a derived class.
  • When applied to a class, the final modifier indicates that the class can not be used as a base class to derive any class from it. It’s also good to point out in an interview that the final modifier, when applied to either a class or a method, turns off late binding, and thus prevents polymorphism.
  • And, when applied to an instance variable, the final modifier simply means that the instance variable can’t be changed. 

Read More
Unknown

What’s the difference between equals() and == in java ?


Before discussing the difference between “==” and the equals() method, it’s important to understand that an object has both a location in memory and a specific state depending on the values that are inside the object.

The “==” operator

In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location. A very simple example will help clarify this:
String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1 == obj2)
ln("obj1==obj2 is TRUE");
else
System.out.
System.out.prin tprintln("obj1==obj2 is FALSE");
Take a guess at what the code above will output. Did you guess that it will output obj1==obj2 is TRUE? Well, if you did, then you are actually wrong. Even though the strings have the same exact characters (“xyz”), The code above will actually output:
 obj1==obj2 is FALSE

The “==” operator compares the objects’ location(s) in memory

Are you confused? Well, let us explain further: as we mentioned earlier, the “==” operator is actually checking to see if the string objects (obj1 and obj2) refer to the exact same memory location. In other words, if both obj1 and obj2 are just different names for the same object then the “==” operator will return true when comparing the 2 objects. Another example will help clarify this:
String obj1 = new String("xyz");
//now obj2 and obj1 reference the same place in memory

String obj2 = obj1; if(obj1 == obj2)
RUE");
else
System.out.println("obj1==obj2
System.out.printlln("obj1==obj2 is Tis FALSE");
Note in the code above that obj2 and obj1 both reference the same place in memory because of this line: “String obj2 = obj1;”. And because the “==” compares the memory reference for each object, it will return true. And, the output of the code above will be:
obj1==obj2 is TRUE

The equals() method

Now that we’ve gone over the “==” operator, let’s discuss the equals() method and how that compares to the “==” operator. The equals method is defined in the Object class, from which every class is either a direct or indirect descendant. By default, the equals() method actually behaves the same as the “==” operator – meaning it checks to see if both objects reference the same place in memory. But, the equals method is actually meant to compare the contents of 2 objects, and not their location in memory.

So, how is that behavior actually accomplished? Simple – the equals class is overridden to get the desired functionality whereby the object contents are compared instead of the object locations. This is the Java best practice for overriding the equals method – you should compare the values inside the object to determine equality. What value you compare is pretty much up to you. This is important to understand – so we will repeat it: by default equals() will behave the same as the “==” operator and compare object locations. But, when overriding the equals() method, you should compare the values of the object instead.

An example of the equals() method being overriden

The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal. Here is an example that will help clarify this:
String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1.equals(obj2))
obj1==obj2 is TRUE");
else
System.out.print
System.out.printlln( "ln("obj1==obj2 is FALSE");
This code will output the following:
obj1==obj2 is TRUE
As we discussed, Java’s String class overrides the equals() method to compare the characters in a string. This means that the comparison between the 2 String objects returns true since they both hold the string “xyz”. It should now be clear what the difference is between the equals() method and the “==” operator.

Read More

Friday, 20 December 2013

Unknown

Java interface versus abstract class


An interface differs from an abstract class because an interface is not a class. An interface is essentially a type that can be satisfied by any class that implements the interface.
Any class that implements an interface must satisfy 2 conditions:
  • It must have the phrase "implements Interface_Name" at the beginning of the class definiton.
  • It must implement all of the method headings listed in the interface definition.
This is what an interface called "Dog" would look like:
public interface Dog
{
 public boolean Barks();

 public boolean isGoldenRetriever();
}
Now, if a class were to implement this interface, this is what it would look like:
public class SomeClass implements Dog
{
 public boolean Barks{
 // method definition here
 }

 public boolean isGoldenRetriever{
 // method definition here
 }
}

Now that we know the basics of interfaces and abstract classes, let’s get to the heart of the question and explore the differences between the two. Here are the three major differences: 
Read More
Unknown

When to use abstract methods in Java?


Why you would want to declare a method as abstract is best illustrated by an example. Take a look at the code below:
/* the Figure class must be declared as abstract 
   because it contains an abstract method  */

public abstract class Figure
{
 /* because this is an abstract method the 
    body will be blank  */
 public abstract float getArea(); 
}

public class Circle extends Figure
{
 private float radius;

 public float getArea()
 {
  return (3.14 * (radius * 2));  
 }
}

public class Rectangle extends Figure
{
 private float length, width;

 public float getArea(Figure other)
 {
  return length * width;
 }
}

In the Figure class above, we have an abstract method called getArea(), and because the Figure class contains an abstract method the entire Figure class itself must be declared abstract. The Figure base class has two classes which derive from it – called Circle and Rectangle. Both the Circle and Rectangle classes provide definitions for the getArea method, as you can see in the code above.

But the real question is why did we declare the getArea method to be abstract in the Figure class? Well, what does the getArea method do? It returns the area of a specific shape. But, because the Figure class isn’t a specific shape (like a Circle or a Rectangle), there’s really no definition we can give the getArea method inside the Figure class. That’s why we declare the method and the Figure class to be abstract. Any classes that derive from the Figure class basically has 2 options: 1. The derived class must provide a definition for the getArea method OR 2. The derived class must be declared abstract itself. 
Read More

Wednesday, 18 December 2013

Unknown

In Java, will the code in the finally block be called and run after a return statement is executed?


The answer to this question is a simple yes – the code in a finally block will take precedence over the return statement. Take a look at the code below to confirm this fact:

Code that shows finally runs after return

class SomeClass
{
    public static void main(String args[]) 
    { 
        // call the proveIt method and print the return value
     System.out.println(SomeClass.proveIt()); 
    }

    public static int proveIt()
    {
     try {  
             return 1;  
     }  
     finally {  
         System.out.println("finally block is run 
            before method returns.");
     }
    }
}
Running the code above gives us this output:

finally block is run before method returns.
1

From the output above, you can see that the finally block is executed before control is returned to the “System.out.println(SomeClass.proveIt());”  statement – which is why the “1″ is output after the “finally block is  run before method returns.” text. 
Read More
Unknown

what is reflection in java


  • The word reflection implies that the properties of whatever being examined are displayed or reflected to someone who wants to observe those properties. Similarly, Reflection in Java is the ability to examine and/or modify the properties or behavior of an object at run-time. It’s important to note that reflection specifically applies to objects – so you need an object of a class to get information for that particular class.
  • Reflection is considered to be an advanced technique, and can be quite powerful when used correctly.
  • Reflection in Java consists of 2 primary things that you should remember:
  • 1. Metadata. Metadata literally means data about the data. In this case, metadata means extra data that has to do with your Java program – like data about your Java classes, constructors, methods, fields, etc.
  • 2. Functionality that allows you to manipulate the metadata as well. So, functionality that would allow you to manipulate those fields, methods, constructors, etc. You can actually call methods and constructors using Java reflection – which is an important fact to remember.
Read More

Tuesday, 17 December 2013

Unknown

Get Http Status code using java code


import java.net.HttpURLConnection;
import java.net.URL;

class ResponseCodeCheck 
{

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

        URL url = new URL("http://google.com");
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();

        int code = connection.getResponseCode();
        System.out.println("Response code of the object is "+code);
        if (code==200)
        {
            System.out.println("OK");
        }
    }
}
Read More

Monday, 16 December 2013

Unknown

Difference between string and stringbuffer class


String
  • Ikt is used to manipulate character strings that cannot be changed (read-only and immutable).
StringBuffer:
  • A StringBuffer (or its non-synchronized cousin StringBuilder) is used when you need to construct a string piece by piece without the performance overhead of constructing lots of little Strings along the way.
  • StringBuffer is used to represent characters that can be modified.
  • Performance wise, StringBuffer is faster when performing concatenations. This is because when you concatenate a String, you are creating a new object (internally) every time since String is immutable.
Example:

public class Concat
{
    public static String concatWithString()
    {
        String t = "Cat";
        for (int i=0; i<10000; i++)
        {
            t = t + "Dog";
        }
        return t;
    }
    public static String concatWithStringBuffer()
    {
        StringBuffer sb = new StringBuffer("Cat");
        for (int i=0; i<10000; i++)
        {
            sb.append("Dog");
        }
        return sb.toString();
    }
    public static void main(String[] args)
    {
        long start = System.currentTimeMillis();
        concatWithString();
        System.out.println("Concat with String took: " + (System.currentTimeMillis() - start) + "ms");
        start = System.currentTimeMillis();
        concatWithStringBuffer();
        System.out.println("Concat with StringBuffer took: " + (System.currentTimeMillis() - start) + "ms");
    }
}
Read More

Friday, 13 December 2013

Unknown

4 Version of Java


Read More
Unknown

Write a program to generate Harmonic Series.

/*Example 
 Input - 5
 Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */

class HarmonicSeries {

    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
        double result = 0.0;
        while (num > 0) {
            result = result + (double) 1 / num;
            num--;
        }
        System.out.println("Output of Harmonic Series is " + result);
    }
}
Read More

Thursday, 12 December 2013

Unknown

Idiot Girl


Girl: Which computer do u have?
Boy: I have a computer with intel core i7
processor at 3.3 ghz, windows 7, 64 bit, 8gb ram
& nvidia gtx 560 graphics card.

Boy: which computer do YOU have???
Girl: A PINK ONE !!


What to say now.
Read More
Unknown

Write a program to find average of Consecutive N Odd Number and Even Number



class EvenOdd_Avg {

    public static void main(String args[]) {
        int n = Integer.parseInt(args[0]);
        int cntEven = 0, cntOdd = 0, sumEven = 0, sumOdd = 0;
        while (n > 0) {
            if (n % 2 == 0) {
                cntEven++;
                sumEven = sumEven + n;
            } else {
                cntOdd++;
                sumOdd = sumOdd + n;
            }
            n--;
        }
        int evenAvg, oddAvg;
        evenAvg = sumEven / cntEven;
        oddAvg = sumOdd / cntOdd;
        System.out.println("Average of first N Even no is " + evenAvg);
        System.out.println("Average of first N Odd no is " + oddAvg);
    }
}
Read More

Wednesday, 11 December 2013

Unknown

1 to 10 Display Triangle


/*
1
2 3
4 5 6
7 8 9 10 ... N */
class Output1 {

    public static void main(String args[]) {
        int c = 0;
        int n = Integer.parseInt(args[0]);
        loop1:
        for (int i = 1; i <= n; i++) {
            loop2:
            for (int j = 1; j <= i; j++) {
                if (c != n) {
                    c++;
                    System.out.print(c + " ");
                } else {
                    break loop1;
                }
            }
            System.out.print("\n");
        }
    }
}
Read More
Unknown

Write a program to Find whether number is Prime or Not.



class PrimeNo {

    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
        int flag = 0;
        for (int i = 2; i < num; i++) {
            if (num % i == 0) {
                System.out.println(num + " is not a Prime Number");
                flag = 1;
                break;
            }
        }
        if (flag == 0) {
            System.out.println(num + " is a Prime Number");
        }
    }
}
Read More

Tuesday, 10 December 2013

Unknown

Write a program to find whether no. is palindrome or not.


/*Example 

:
Input - 12521 is a palindrome no.
Input - 12345 is not a palindrome no. */
class Palindrome {

    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
        int n = num; //used at last time check
        int reverse = 0, remainder;
        while (num > 0) {
            remainder = num % 10;
            reverse = reverse * 10 + remainder;
            num = num / 10;
        }
        if (reverse == n) {
            System.out.println(n + " is a Palindrome Number");
        } else {
            System.out.println(n + " is not a Palindrome Number");
        }
    }
}
Read More
Unknown

Display Triangle


/*
0
1 0
1 0 1
0 1 0 1 */
class Output2 {

    public static void main(String args[]) {
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(((i + j) % 2) + " ");
            }
            System.out.print("\n");
        }
    }
}
Read More

Monday, 9 December 2013

Unknown

Write a program to Display Invert Triangle using while loop.


/*Example
:
Input - 5
Output :
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1
27
*/
class InvertTriangle {

    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
        while (num > 0) {
            for (int j = 1; j <= num; j++) {
                System.out.print(" " + num + " ");
            }
            System.out.print("\n");
            num--;
        }
    }
}
Read More
Unknown

Write a program to find whether given no. is Armstrong or not.


/*Example :
 Input - 153
 Output - 1^3 + 5^3 + 3^3 = 153, so it is Armstrong no. */

class Armstrong {

    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
        int n = num; //use to check at last time
        int check = 0, remainder;
        while (num > 0) {
            remainder = num % 10;

            check = check + (int) Math.pow(remainder, 3);
            num = num / 10;
        }
        if (check == n) {
            System.out.println(n + " is an Armstrong Number");
        } else {
            System.out.println(n + " is not a Armstrong Number");
        }
    }
}
Read More
Unknown

switch case demo


/*Example 
:
Input - 124
Output - One Two Four */
class SwitchCaseDemo {

    public static void main(String args[]) {
        try {
            int num = Integer.parseInt(args[0]);
            int n = num; //used at last time check
            int reverse = 0, remainder;
            while (num > 0) {
                remainder = num % 10;
                reverse = reverse * 10 + remainder;
                num = num / 10;
            }

            String result = ""; //contains the actual output
            while (reverse > 0) {
                remainder = reverse % 10;
                reverse = reverse / 10;
                switch (remainder) {
                    case 0:
                        result = result + "Zero ";
                        break;
                    case 1:
                        result = result + "One ";
                        break;
                    case 2:
                        result = result + "Two ";
                        break;
                    case 3:
                        result = result + "Three ";
                        break;
                    case 4:
                        result = result + "Four ";
                        break;
                    case 5:
                        result = result + "Five ";
                        break;
                    case 6:
                        result = result + "Six ";
                        break;

                    case 7:
                        result = result + "Seven ";
                        break;
                    case 8:
                        result = result + "Eight ";
                        break;
                    case 9:
                        result = result + "Nine ";
                        break;
                    default:
                        result = "";
                }
            }
            System.out.println(result);
        } catch (Exception e) {
            System.out.println("Invalid Number Format");
        }
    }
}
Read More

Sunday, 8 December 2013

Unknown

Program to Display Multiplication Table



class MultiplicationTable {

    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
        System.out.println("*****MULTIPLICATION TABLE*****");
        for (int i = 1; i <= num; i++) {
            for (int j = 1; j <= num; j++) {
                System.out.print(" " + i * j + " ");
            }
            System.out.print("\n");
        }
    }
}
Read More
Unknown

Write a program to find average of consecutive N Odd no. and Even no.



class EvenOdd_Avg {

    public static void main(String args[]) {
        int n = Integer.parseInt(args[0]);
        int cntEven = 0, cntOdd = 0, sumEven = 0, sumOdd = 0;
        while (n > 0) {
            if (n % 2 == 0) {
                cntEven++;
                sumEven = sumEven + n;
            } else {
                cntOdd++;
                sumOdd = sumOdd + n;
            }
            n--;
        }
        int evenAvg, oddAvg;
        evenAvg = sumEven / cntEven;
        oddAvg = sumOdd / cntOdd;
        System.out.println("Average of first N Even no is " + evenAvg);
        System.out.println("Average of first N Odd no is " + oddAvg);
    }
}
Read More
Unknown

Write a program to generate Harmonic Series.


/*Example :
 Input - 5
 Output - 1 + 1/2 + 1/3 + 1/4 + 1/5 = 2.28 (Approximately) */

class HarmonicSeries {

    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
        double result = 0.0;
        while (num > 0) {
            result = result + (double) 1 / num;
            num--;
        }
        System.out.println("Output of Harmonic Series is " + result);
    }
}
Read More
Unknown

Write a program to convert given no. of days into months and days.(Assume that each month is of 30 days)


/*Example

:
Input - 69
Output - 69 days = 2 Month and 9 days */
class DayMonthDemo {

    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
        int days = num % 30;
        int month = num / 30;
        System.out.println(num + " days = " + month + " Month and " + days + " days");
    }
}
Read More
Unknown

Write a program to Swap the values



class Swap {

    public static void main(String args[]) {
        int num1 = Integer.parseInt(args[0]);
        int num2 = Integer.parseInt(args[1]);
        System.out.println("\n***Before Swapping***");
        System.out.println("Number 1 : " + num1);
        System.out.println("Number 2 : " + num2);
//Swap logic
        num1 = num1 + num2;
        num2 = num1 - num2;
        num1 = num1 - num2;
        System.out.println("\n***After Swapping***");
        System.out.println("Number 1 : " + num1);
        System.out.println("Number 2 : " + num2);
    }
}
Read More

Friday, 6 December 2013

Unknown

Write a program to concatenate string using for Loop


/*Example
:
Input - 5

Output - 1 2 3 4 5 */
class Join {

    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
        String result = " ";
        for (int i = 1; i <= num; i++) {
            result = result + i + " ";
        }
        System.out.println(result);
    }
}
Read More
Unknown

Write a program to find SUM AND PRODUCT of a given Digit.



class Sum_Product_ofDigit {

    public static void main(String args[]) {
        int num = Integer.parseInt(args[0]);
//taking value as command line argument.
        int temp = num, result = 0;
//Logic for sum of digit
        while (temp > 0) {
            result = result + temp;
            temp--;
        }
        System.out.println("Sum of Digit for " + num + " is : " + result);
//Logic for product of digit
        temp = num;

        result = 1;
        while (temp > 0) {
            result = result * temp;
            temp--;
        }
        System.out.println("Product of Digit for " + num + " is : " + result);
    }
}
Read More

Thursday, 5 December 2013

Unknown

Write a program to display a greet message according to Marks obtained by student



class SwitchDemo {

    public static void main(String args[]) {
        int marks = Integer.parseInt(args[0]); //take marks  as command line argument

        switch (marks / 10) {
            case 10:
            case 9:
            case 8:
                System.out.println("Excellent");
                break;
            case 7:
                System.out.println("Very Good");
                break;
            case 6:
                System.out.println("Good");
                break;
            case 5:
                System.out.println("Work Hard");
                break;
            case 4:
                System.out.println("Poor");
                break;
            case 3:
            case 2:
            case 1:
            case 0:
                System.out.println("Very Poor");
                break;
            default:
                System.out.println("Invalid value Entered");
        }
    }
}
Read More
Unknown

To Find Minimum of Two Numbers using conditional operator

/*
 To find minimum of 2 Numbers using ternary operator
 */

class Minoftwo {

    public static void main(String args[]) {
//taking value as command line argument.
//Converting String format to Integer value
        int i = Integer.parseInt(args[0]);
        int j = Integer.parseInt(args[1]);
        int result = (i < j) ? i : j;
        System.out.println(result + " is a minimum value");
    }
}
Read More
Unknown

To Find Maximum of Two Numbers.

/*
 To Find Maximum of 2 Numbers using if else
 */

class Maxoftwo {

    public static void main(String args[]) {
//taking value as command line argument.
//Converting String format to Integer value
        int i = Integer.parseInt(args[0]);
        int j = Integer.parseInt(args[1]);
        if (i > j) {
            System.out.println(i + " is greater than " + j);
        } else {
            System.out.println(j + " is greater than " + i);
        }
    }
}
Read More