Facebook

adsense

Tuesday, 31 March 2015

TEST YOUR JAVA SKILLS


1) Which is true about Static Initialization Block?

A. We can use only static members of a class inside the Static Initialization Block.
B. Static Initialization Blocks are mainly used to initialize static fields of a class.
C. Static Initialization Block is the first block to be executed after class is loaded in the memory.
D. All of the above.


2) Where the static initialization blocks are stored in the memory?


3) What will be the output of this program?

class A
{
static int i;

static
{
System.out.println(1);

i = 100;
}
}

public class StaticInitializationBlock
{
static
{
System.out.println(2);
}

public static void main(String[] args)
{
System.out.println(3);

System.out.println(A.i);
}
}

4) What happens when you compile the below class?

class A
{
int i;

static
{
System.out.println(i);
}
}

5) Is the below code written correctly?

class A
{
static
{
static
{
System.out.println(1);
}
}
}
6) How many static initialization blocks are there in the below Class A?

class A
{
static int a = 50;

static
{
a = 50;
}

static
{
a = 50;
}
}

7) What will be the outcome of the following program?

public class A
{
static
{
System.out.println(1);
}

static
{
System.out.println(2);
}

static
{
System.out.println(3);
}

public static void main(String[] args)
{
A a;
}
}

8) What will be the output of this program?

class A
{
static int first;

static String second;

static
{
System.out.println(1);

first = 100;
}

static
{
System.out.println(2);

second = "SECOND";
}
}

public class StaticInitializationBlock
{
static
{
System.out.println(3);
}

public static void main(String[] args)
{
System.out.println(4);

System.out.println(A.first);

System.out.println(A.second);
}
}

9) What will be the output of the below program?

class A
{
static int i;

static
{
i = 100;

System.out.println(1);
}

static void staticMethod()
{
System.out.println(i);

System.out.println(2);
}
}

public class B
{
static
{
System.out.println(3);
}

public static void main(String[] args)
{
System.out.println(4);

System.out.println(A.i);

A.staticMethod();
}
}

10) What is the difference between SIB and IIB?

11) Can we invoke static method inside the SIB – Static Initialization Block?


12) What will be the output of following program?

class A
{
{
System.out.println(1);
}

public A()
{
System.out.println(2);
}

public static void main(String[] args)
{
System.out.println(3);

A a = new A();
}
}

13) What will be the output of the below program?

public class A
{
{
System.out.println("First");
}

{
System.out.println("Second");
}

{
System.out.println("Third");
}

public A()
{
System.out.println("Fourth");
}

public static void main(String[] args)
{
System.out.println("Fifth");

A a = new A();
}
}

14) Which one of these are executed first while creating an object to the class?

a) Statements of IIB block
b) Statements of constructor


15) What will be the outcome of the below program?

public class A
{
int i;

{
System.out.println("IIB-1");

i = 100;
}

{
System.out.println("IIB-2");

System.out.println(i);

i = 200;
}

public static void main(String[] args)
{
System.out.println("main");

A a = new A();

System.out.println(a.i);
}
}

       

Try to solve these conceptual question of java to know how much java do you know, and write your answers in the comment below like, "Q no) answer" or click on answer link , I will post the answer after somedays if I will get a large number of clicks on answer links 

            


Saturday, 28 March 2015

10 Tricky Core java Question and Answers

(click for Answers).

1) Can you instantiate this class?

public class A
{
    A a = new A();
}

2) Is the below code written correctly? If yes, what will be the output?

class A
{
    static void staticMethod()
    {
        System.out.println("Static Method");
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        A a = null;

        a.staticMethod();
    }
}

3) What will be the output of the following program?

class A
{
    static int i = 1111;

    static
    {
        i = i-- - --i;
    }

    {
        i = i++ + ++i;
    }
}

class B extends A
{
    static
    {
        i = --i - i--;
    }

    {
        i = ++i + i++;
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        B b = new B();

        System.out.println(b.i);
    }
}

4) What happens when you call methodOfA() in the below class?


class A
{
    int methodOfA()
    {
        return (true ? null : 0);
    }
}

5) What will be the output of the below program?

public class MainClass
{
    public static void main(String[] args)
    {
        Integer i1 = 127;

        Integer i2 = 127;

        System.out.println(i1 == i2);

        Integer i3 = 128;

        Integer i4 = 128;

        System.out.println(i3 == i4);
    }
}

6) Can we override method(int) as method(Integer) like in the below 

class A
{
    void method(int i)
    {
        //method(int)
    }
}

class B extends A
{
    @Override
    void method(Integer i)
    {
        //method(Integer)
    }
}

7) Which statements in the below class shows compile time error (Line 5 or Line 7 or both)?

public class MainClass
{
    public static void main(String[] args)
    {
        Integer i = new Integer(null);

        String s = new String(null);
    }
}
8) What will be the output of the following program?


public class MainClass
{
    public static void main(String[] args)
    {
        String s = "ONE"+1+2+"TWO"+"THREE"+3+4+"FOUR"+"FIVE"+5; 

        System.out.println(s);
    }
}

9) What will be the output of the below program?

public class MainClass
{
    static int methodOne(int i)
    {
        return methodTwo(i *= 11);
    }

    static int methodTwo(int i)
    {
        return methodThree(i /= 11);
    }

    static int methodThree(int i)
    {
        return methodFour(i -= 11);
    }

    static int methodFour(int i)
    {
        return i += 11;
    }

    public static void main(String[] args)
    {
        System.out.println(methodOne(11));
    }
}

10) What will be the output of the following program?

public class MainClass
{
    public static void main(String[] args)
    {
        int i = 10 + + 11 - - 12 + + 13 - - 14 + + 15;

        System.out.println(i);
    }
}

/////////////////////////////////////////////////////////////////////////////////
ANSWERS

1) Not possible. Because while instantiating, constructor will be called recursively.

2) Yes, the code is correct. You can call static methods through reference variable which is pointing to null. Output will be,
Static Method

3) 6

4) Throws NullPointerException at run time.

5)
true
false

6) No. It gives compile time error. Compiler treats int and Integer as two different types while overriding. Auto-boxing doesn’t happen here.

7) Only Line 7 shows compile time error. Because, compiler will be in an ambiguous situation of which constructor to call. Because, String class has five constructors which take one argument of derived type . Where as Integer class has only one constructor which takes one argument of derived type.

8) ONE12TWOTHREE34FOURFIVE5

9) 11

10) 75

Friday, 27 March 2015

Classes and Objects

General
Class = data + methods
                  Everything (data and methods) in Java is contained in classes. So far you've been using classes to hold methods (main and perhaps a few other static methods). These methods use local variables, which are completely private to the method, and which disappear when the method returns.

Historical development.
                 Classes can also be used to store data. Historically, programming languages had something similar to classes for grouping data, usually called structs or records. These were used for storing only data, not methods. Eventually, advantages of combining both data and the methods to work on that data were recognized.

Classes model problem.
                One advantage of encapsulating data and methods in a class is to make programming objects that reflect "objects" in the problem domain. If your problem deals with orders and products, then you'll very likely have classes called Order and Product.

Classes reduce complexity
                Another advantage of classes is reducing complexity. Complexity limits the size and reliability of programs. Complexity is reduced by increasing cohesion (putting things together that belong together) and reducing coupling (interconnections). The proper use of classes can make large improvements in both of these.

Class, object, OOP.
                The name class was almost universally adopted for programming language structure which combines data and methods, object is used for each instance of a class that is created, and the practices that developed around these ideas is called Object-Oriented Programming (OOP).

Value objects - Data-first approach.
                We'll start with classes that represent data, and then add constructors and methods. Ultimately you will be more concerned with methods than data, and you'll see how (and why) methods are used to completely hide the data implementation.

A class stores the attributes (data) of something

Group values.
            Classes are used to group a number of related, named, data values associated with an entity. By entity we mean something that is typically a noun when you are talking about a problem you are solving. For example, in a university computing system, you might have a class to represent a student, an instructor, a classroom, a department, a course, a section of a course, ....

Student example.
            The information you would store about students, would be their name, id, etc. We'll keep this example simple and just save name and id information.

Declare each field.
             A class contains declarations of the fields (instance variables, attributes) that hold the data associated with a student. These declarations are like declaring a local variable in a method, except that you will also specify the visibility. We'll start by using the visibility modifier public, which lets anyone see them. For example, the following Student1 class can be used to represent a student. As you go through these notes, we'll make improvements to this class.

public class Student1 {
    public String firstName;
    public String lastName;
    public int    id;
}

A class is a type

Noun.
      Classes are usually given the name of a noun, and the fields (variables) in it are attributes associated with that noun. Predefined Java classes that you have already used are String, which contains the characters in the string and the length, JOptionPane, which contains information necessary to produce a dialog box on the screen, etc. These predefined Java classes are used for the programming infrastructure that you need. Many common infrastructure classes are available in the 3000+ predefined Java library classes. But, of course, these don't address your problems.

Business objects.
              Most classes you define will concern your problem domain, where they represent business objects (Student, TimeOfDay, Order, ...).
Declaring business object variables is like declaring any other variable. Use the class name as a type, just as you've used String, int, etc. For example, the following declares two 

Student1 variables.
Student1 bestInClass;  // This variable references a Student1 object.
Student1 t;            // And here is another

These don't have values yet, but we'll do that in the next section.

Does your problem require classes or simple variables?

If the data you are working with, for example a temperature, can be expressed as a simple value and the operations on it are all defined by operators, then just use a simple variable for it (int, double, String, ...). Often the data associated with an entity in your problem is not a simple value, but has multiple attributes.

Examples showing classes as groups of attriutes.

  • Instead of working with simple temperature numbers, you might have TemperatureMeasurement objects, which have several attributes: the temperature, the time, and the location.
  • A Student class would represent information about a student: name, id, address, ... Each object of this class would have a data about a specific student.
  • A Classroom class would have information about a classroom's building, room number, capacity, whether it has a projector, etc.

Object-Oriented Design involves deciding which classes you need to represent the things (entities) in your problem. For simple programs, you often use only simple variables, but as programs get larger, you will define more and classes to represent the things you are working with.

Friday, 20 March 2015

Array

Arrays are to data as loops are to control flow.

Overview

The basic solution. Arrays are the basic way to store large numbers of values. Every programming language you're likely to use has arrays as part of the fundamental language, although with many little variations on how they work.
Strings are like arrays of chars and you should be familiar with the idea of storing multiple values which are accessed by a numeric index.
Other possibilities. Arrays in Java are great for working with a fixed numbers of elements, but Java also has the Collections library of classes that are a better choice when working with a variable number of objects, e.g, ArrayList, but it's essential to learn about arrays, so we'll start with them.

Arrays store many values using one name and an index

An array can store many similar values in memory. Each value is accessed by specifying an integer subscript or index in brackets following the array name. "Array" in Java means approximately the same thing as array, matrix, or vector does in math. Unlike math and some other programming languages, in Java you must both declare an array and allocate a fixed amount of memory for it.

Declaring an array

An array variable is like other variables -- you must declare it, which means you must declare the type of elements that are in an array. All elements must be the same type. Write the element type name, then "[]", then the name of the array variable. The declaration allocates only enough space for a reference to an array (typically 4 bytes), but doesn't create the actual array object.

               String[]  args;   // args is an array of Strings
               int[]     scores; // scores is an array of ints
               JButton[] controlButtons;  // controlButtons is an                                                                              array of JButtons

No size in declaration. Unlike some languages, never put the size of the array in the declaration because an array declaration specifies only the element type and the variable name. The size is specified when you allocate space for the array.

Names - Plurals or collective nouns are most common for array names
Most programming guidelines suggest using plural names, or nouns denoting a collection of things, for arrays and other collections of multiple values. This is not a rigid rule, and your choice will often be based on linguistic sensitive. For example, you might have an array of words and their frequencies. It would be entirely appropriate to name this wordFrequencyTable because the word "table" suggests many entries. If you had an array of single words, you might call it words or wordList. Naming the array using the singular word would probably be very confusing to most readers.
Examples in this text often follow the common convention of using the array variable name "a". This seriously violates the rule of having meaningful names, so please don't adopt this textbook-example style in your code!

Allocate an array object with 'new' keyword 

Create an array using new. This example creates an array of 100 int elements, from a[0] to a[99].

            int[] a;           // Declare a to be an array of ints
            a = new int[100];  // Allocate an array of 100 ints

These are often combined in one   
          int[] a = new int[100];  // Declare and allocate.

Subscripts (indexes/indices)

Subscripts are enclosed in square brackets []. xi in mathematics is x[i] in Java, and is pronounced "x-sub-i".

Subscript ranges always start at zero because Java came largely from C++, which had a good reason for using zero (pointer arithmetic on arrays). It isn't the way that humans normally count; you'll just have to live with it.

Java always checks subscript legality to be sure the subscript is >= 0, and less than the number of elements in the array. If the subscript is outside this range, Java throws ArrayIndexOutOfBoundsException. This is far superior to the behaver of C and C++, which allow out of range references. Consequently, Java programs are far less susceptible to bugs and security flaws than C/C++ programs.

Zero-based indexing is a constant annoyance of Java's zero-based indexing. The natural human value for hours or days should be used as an index to make the program most readable, but this would mean starting with 1, not zero.

Translate or ignore 0 element? If the data you are working with naturally starts at one, not zero, either the data must be modified before using it as an index, or the size of the array could be increased by one row so that the natural values could be used, and row 0 would never be referenced. Ignoring the zeroth array element instead of translating data to be zero based is a style decision, and you'll find various positions on this matter. See the AutoSales example below.

Length of an array

Each array has a constant (final) instance variable that has its length. You can find out how many elements an array can hold by writing the array name followed by .length. In the previous example, a.length would be 100. Remember that this is the number of elements in the array, one more than the maximum subscript.

Example - Reading into an array
This shows typical input code for reading into an array from a Scanner. This program is very strange because it doesn't do anything with the data, but it's shown here as an early step in the iterative process.


// InputArray.java -- Simple demo of reading into an array.
// Fred Swartz - 26 Aug 2006 - Placed in the public domain.

import java.util.*;

public class InputArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);

int[] scores = new int[100];
int n = 0;  // Current number of values in scores.

while (in.hasNextInt()) {
if (n >= scores.length) {
System.err.println("Too much data!");
System.exit(1);
}
scores[n] = in.nextInt();
n++;
}

//... Now do something with the scores!
}
}

Java idiom for looping over an array - for loop

For loop. The most common use of .length is in a for loop test condition. For example, the variable i will go over the entire range of subscripts of the array a.
int[] a = new int[1000]; // Declare, allocate array of 1000 ints, a[0]...a[999]

//... Assign random values to each element.
for (int i = 0; i < a.length(); i++) {
    a[i] = (int)(Math.random() * 100000);  // Random number 0-99999
}
//... Add all elements of the array a.
int sum = 0;
for (int i = 0; i < a.length; i++) { 
    sum += a[i];
}

Enhanced for loop. If you only need to reference the value of each of the elements, you can use the somewhat simpler enhanced for loop (also known as the foreach loop), which keeps track of the index and assigns successive values to a variable (v in this example). The foreach loop only gets the values, so it couldn't have been used to set the values in the first loop above.
//... Add all elements of the array a.
int sum = 0;
for (int v : a) { 
    sum += v;
}

Initial array element values -- zero/null/false

When an array is allocated (with new), all elements are set to an initial value. The initial value is 0 if the element type is numeric (int, float, ...), false for boolean, and null for all object types.

Array Initialization

When you declare an array, you can can also allocate a preinitialized array object in the same statement. In this case, do not give the array size because Java counts the number of values to determine the size. For example,
   
       String[] days = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};

Array diagrams

This code declares and initializes an array.
            int[] a = {1, 2, 4, 8, 16};
Arrays are often represented with diagrams that represent their memory use. The diagrams below are typical ways to represent the memory used by an array.
Each box represents the amount of memory needed to hold  one array element. For ints this is 4 bytes. The array variable, a, is a reference (ie, memory address in the heap) of the block of memory that holds the actual array elements. References are often represented by a black disk with an arrow pointing to the data they reference. Most often array diagrams are written vertically, but sometimes the cells are arranged horizontally, especially for arrays of characters. Of course in the actual physical memory there is no such idea as vertical or horizontal.


Array variables are references to a block of elements

When you declare an array variable, Java reserves only enough memory for a reference (Java's name for an address or pointer) to an array object. References typically require only 4 bytes. When an array object is created with new, a reference is returned, and that reference can then be assigned to a variable. When you assign one array variable to another, only the reference is copied. For example,

           int[] a = new int[] {100, 99, 98};  // "a" references the    array object.
           int[] b;                            // "b" doesn't reference     anything.

           b = a;      // Now "b" refers to the SAME array as "a"
          b[1] = 0;   // Also changes a[1] because a and b refer to                                       the same array.

Example (AutoSales) - Translating between subscript and data ranges

Indexes in other ranges. If the index data is in a range far from zero, eg auto sales by year, translate the index by subtracting the minimum value. For example,
   
// File   : data-arrays/autoSales/AutoInfo.java
// Purpose: Demonstrates use of arrays to hold values associated
//          with integer values that don't start at zero.
// Author : Fred Swartz - 2006-01-15 - Placed in public domain.

import java.util.*;

public class AutoInfo {
    //======================================================== constants
    static final int FIRST_YEAR = 1900;
    static final int LAST_YEAR  = 2020;
    
    //============================================================= main
    public static void main(String[] args) {
        int[] autoSales = new int[LAST_YEAR - FIRST_YEAR + 1]; 
        
        Scanner in = new Scanner(System.in);
        
        //... Read data as pairs of year and sales values.
        while (in.hasNextInt()) {
            int year  = in.nextInt();
            int sales = in.nextInt();
            autoSales[year - FIRST_YEAR] = sales;
        }
        
        //... Here's where code to process this data belongs.
        
        //... Print year and sales for all non-zero values.
        for (int year = FIRST_YEAR; year <= LAST_YEAR; year++) {
            int sales = autoSales[year - FIRST_YEAR];
            if (sales > 0) {
                System.out.println(year + " " + sales);
            }
        }
    }
}
Alternate loop to display values. Another way to write the above output is to loop over index values, then translate these to the appropriate data range.
//... Print year and sales for all non-zero values.
for (int i = 0; i < autoSales.length; i++) {
    int sales = autoSales[i];
    int year  = FIRST_YEAR + i;
    if (sales > 0) {
        System.out.println(year + " " + sales);
    }
}

Common array problems

Some common array programming mistakes are:
Runtime error: Forgetting that array subscripts start with zero.
Compile-time error: Writing a.length() instead of a.length. The length() method is used with Strings, not arrays.
Compile-time error: Declaring an array with a size. Eg,         int[100] a; instead of int[] a = new int[100];.

Thursday, 19 March 2015

Polymorphism




The word ‘polymorphism’ literally means ‘a state of having many shapes’ or ‘the capacity to take on different forms’. When applied to object oriented programming languages like Java, it describes a language’s ability to process objects of various types and classes through a single, uniform interface.

Polymorphism in Java has two types: Compile time polymorphism (static binding) and Runtime polymorphism (dynamic binding). Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism.
An important example of polymorphism is how a parent class refers to a child class object.  In fact, any object that satisfies more than one IS-A relationship is polymorphic in nature.
For instance, let’s consider a class Animal and let Cat be a subclass of Animal. So, any cat IS animal. Here, Cat satisfies the IS-A relationship for its own type as well as its super class Animal.
Note: It’s also legal to say every object in Java is polymorphic in nature, as each one passes an IS-A test for itself and also for Object class.

Static Polymorphism:


In Java, static polymorphism is achieved through method overloading. Method overloading means there are several methods present in a class having the same name but different types/order/number of parameters.
At compile time, Java knows which method to invoke by checking the method signatures.  So, this is called compile time polymorphism or static binding. The concept will be clear from the following example:

class DemoOverload{

    public int add(int x, int y){  //method 1

    return x+y;

    }

    public int add(int x, int y, int z){ //method 2

    return x+y+z;

    }

    public int add(double x, int y){ //method 3

    return (int)x+y;

    }

    public int add(int x, double y){ //method 4

    return x+(int)y;

    }

}

class Test{

    public static void main(String[] args){

    DemoOverload demo=new DemoOverload();

    System.out.println(demo.add(2,3));      //method 1 called

    System.out.println(demo.add(2,3,4));    //method 2 called

    System.out.println(demo.add(2,3.4));    //method 4 called

    System.out.println(demo.add(2.5,3));    //method 3 called

    }

}
In the above example, there are four versions of add methods. The first method takes two parameters while the second one takes three. For the third and fourth methods there is a change of order of parameters.  The compiler looks at the method signature and decides which method to invoke for a particular method call at compile time.

Dynamic Polymorphism:


Suppose a sub class overrides a particular method of the super class. Let’s say, in the program we create an object of the subclass and assign it to the super class reference. Now, if we call the overridden method on the super class reference then the sub class version of the method will be called.
Have a look at the following example.

class Vehicle{

    public void move(){

    System.out.println(“Vehicles can move!!”);

    }

}

class MotorBike extends Vehicle{

    public void move(){

    System.out.println(“MotorBike can move and accelerate too!!”);

    }

}

class Test{

    public static void main(String[] args){

    Vehicle vh=new MotorBike();

    vh.move();    // prints MotorBike can move and accelerate too!!

    vh=new Vehicle();

    vh.move();    // prints Vehicles can move!!

    }

}

It should be noted that in the first call to move(), the reference type is Vehicle and the object being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to determine which object is actually being pointed to by the reference.  In this case, the object is of the class MotorBike. So, the move() method of MotorBike class will be called. In the second call to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called.
As the method to call is determined at runtime, this is called dynamic binding or late binding.

Summary:


An object in Java that passes more than one IS-A tests is polymorphic in nature
Every object in Java passes a minimum of two IS-A tests: one for itself and one for Object class
Static polymorphism in Java is achieved by method overloading
Dynamic polymorphism in Java is achieved by method overriding