Saturday, October 12, 2013

SCJP Questions


1)


class Mammal{
String name="furry";
String makeNoise(){ return "generic noise";}

}
class Zebra extends Mammal{

Sring name="stripes";
String makeNoise(){return "bray";}

}

public class ZooKeeper{
public static void main(String [] args){ new ZooKeeper().go();}

void go(){

Mammal m = new Zebra();
System.out.println(m.name + m.makeNoise());
}

}

What is the Result ?
2)SCJP:

public class Dark{

    int x =3;
    public static void main(String[] args){

        new Dark().go1();
    }

   void go1(){

       int x;
       go2(++x);
   }

  void go2(int y ){

     int x = ++y;
    System.out.println(x);
  }

}

What is the Result ?

3)
import java.io.*;
class Player {
Player() { System.out.print("p"); }
}
class CardPlayer extends Player implements Serializable {
CardPlayer() { System.out.print("c"); }
public static void main(String[] args) {
CardPlayer c1 = new CardPlayer();
try {
FileOutputStream fos = new FileOutputStream("play.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(c1);
os.close();
FileInputStream fis = new FileInputStream("play.txt");
ObjectInputStream is = new ObjectInputStream(fis);
CardPlayer c2 = (CardPlayer) is.readObject();
is.close();
} catch (Exception x ) { }
}
}
4)
import java.io.*;

class Keyboard { }
public class Computer implements Serializable {
  private Keyboard k = new Keyboard();
  public static void main(String[] args) {
    Computer c = new Computer();
    c.storeIt(c);
  }
  void storeIt(Computer c) {
    try {
      ObjectOutputStream os = new ObjectOutputStream(
         new FileOutputStream("myFile"));
      os.writeObject(c);
      os.close();
      System.out.println("done");
    } catch (Exception x) {System.out.println("exc"); }
  }
}
 
5)
What is output ?

class Cat { }
class Dog {
public static void main(String [] args) {
Dog d = new Dog();
System.out.println(d instanceof Cat);
}
}
 
6)
 

class Boxing2 {
static Integer x;
public static void main(String [] args) {
doStuff(x);
}
static void doStuff(int z) {
int z2 = 5;
System.out.println(z2 + z);
} }
 
7)
package javaimp;
   class Ouch {
   static int ouch = 7;
    public static void main(String[] args) {
     new Ouch().go(ouch);
      System.out.print(" " + ouch);
    }
    void go(int ouch) {
     ouch++;
     for(int ouch = 3; ouch < 6; ouch++)
       ;
     System.out.print(" " + ouch);
   }
 }
What is the result?
  1. 5 7
  2. 5 8
  3. 8 7
  4. 8 8
  5. Compilation fails

8)

class MyOuter2{
private String x = "Outer2";
void doStuff(){
String z = " local variable";
class MyInner{

public void seeOuter(){

System.out.println("Outer x is "+x);
System.out.println("Local var z is "+z);
}
}
}
}

What is the result ?
 
 
 

Concepts on String,StringBuffer,StringBuilder and String Pool ?

String:
-----------
String is immutable object that means the string content in the String object can't be modified....
String s = "anil";
s = s+"kumar";
But beginners may think that... String s is modified... But what really happens is
original String s doesn't get modified... A new String will be created with "anil" and "kumar"
and the original reference s will be set to new object.Only reference variable is getting modified
but not the contents in the original object.
So the drawback is many intermediate objects get created and it will be a problem if you are doing
multiple concatenations.
 
 String Buffer:
------------------------
When you are doing multiple concatenations use StringBuffer instead of String.
 StringBuffer is synchronized.
StringBuilder:StringBuilder is same as... StringBuffer.Difference is StringBuilder is not 
synchronized.So performance will be more than StringBuffer.But you have to be careful
while using StringBuilder in multithreaded programmes.
 
 
What is string pool ?
------------------------

When you say new String("Anil");

It always creates an object with content String.

Suppose... if you create new String("Anil") in a for loop
with 1000 iterations.. it will create 1000 string objects.

----------------------------------------------------------------

Above thing is waste of memory.
So java people decided to create a pool of string objects.

So they given another way to create String objects.

You can create String object with content "Anil" even
in the following manner.

String name = "Anil";

If you write syntax like this... internally java checks if this string
is already in String pool. If it is there.... it returns the reference
to existing String object.

If the object you are trying to create is not existing it will try to
create.... String "Anil" in String pool....

In this case only one object gets created whereas in the first
scenario 1000 object gets created... So you can imagine
how much memory will be saved with this concept....
------------------------------------------------------------------------------

So Finally if you say new String("Anil") always object gets
created

If you say String name = "Anil"; It will be checked in string pool
if the object doesn't exist then only String object with content "Anil" gets
created.

Tuesday, October 8, 2013

Encapsulation

Encapsulation is the ability to hide and protect data stored in Java objects. You may ask, "Who are the bad guys who want to illegally access my data?" It's not about bad guys. When a developer creates a Java class, he or she plans for a certain use pattern of this code by other classes. For example, the variable grossIncome should not be modified directly, but via a method that performs some validation procedures to ensure that the value to be assigned meets application-specific rules.

Encapsulation mechanisms enable the programmer to group data and the subroutines that operate on them together in one place, and to hide irrelevant details from the users of an abstraction

Encapsulation and Access Control

An OOP principle, encapsulation is a mechanism that protects parts of an object that need to be secure and exposes only parts that are safe to be exposed. A television is a good example of encapsulation. Inside it are thousands of electronic components that together form the parts that can receive signals and decode them into images and sound. These components are not to be exposed to users, however, so Sony and other manufacturers wrap them in a strong metallic cover that does not break easily. For a television to be easy to use, it exposes buttons that the user can touch to turn on and off the set, adjust brightness, turn up and down the volume, and so on.
Back to encapsulation in OOP, let's take as an example a class that can encode and decode messages. The class exposes two methods called encode and decode, that users of the class can access. Internally, there are dozens of variables used to store temporary values and other methods that perform supporting tasks. The author of the class hides these variables and other methods because allowing access to them may compromise the security of the encoding/decoding algorithms. Besides, exposing too many things makes the class harder to use. As you can see later, encapsulation is a powerful feature.

Java supports encapsulation through access control. Access control is governed by access control modifiers. There are four access control modifiers in Java: public, protected, private, and the default access level. Access control modifiers can be applied to classes or class members. We'll look at them in the following subsections.

Tight Encapsulation

Encapsulation refers to the combining of fields and methods together in a class such that the methods operate on the data, as opposed to users of the class accessing the fields directly. The term tight encapsulation refers to using encapsulation every time on all the fields of a class, and only providing access to the fields via methods. With tight encapsulation, no fields of an object can be modified or accessed directly; you can only access the fields through a method call.
To implement tight encapsulation, make the fields of a class private and provide public accessor (“getter”) and mutator (“setter”) methods. Because a mutator or accessor method must be invoked to access the fields of the object, tight encapsulation has several key benefits:
  • You can monitor and validate all changes to a field.
  • Similarly, you can monitor and format all access to a field.
  • The actual data type of a field can be hidden from the user, allowing you to change the data type without affecting the code that uses the object, as long as you do not alter the signatures of the corresponding accessor and mutator method.
To demonstrate, let's first look at a class that does not implement tight encapsulation. The following class, named Student1, represents a student with fields for the year (Freshman, Sophomore, Junior, Senior) and percentage grade of a student. The fields of Student1 are public and can be accessed directly:
public class Student1 {
    public String year;
    public double grade;
}
Because the class does not implement tight encapsulation, the fields of a Student1 object can take on any values. The following code is valid, although from an application point of view the values do not make sense:
Student1 s = new Student1();
s.year = "Memphis, TN";
s.grade = -24.5;
The string “Memphis, TN” is not a valid year, and we can assume that a student's grade should never be negative. With tight encapsulation, these issues can easily be avoided because users of the class cannot access its fields directly. By forcing a method call to change a value, you can validate any changes to the fields of the object.
The following Student2 class is similar to Student1 but implements tight encapsulation. It is not possible for year to be an invalid value or grade to be negative or greater than 105.0:
1. public class Student2 {
2.     private String year;
3.     private double grade;
4.
5.     public void setYear(String year) {
6.         if(!year.equals("Freshman")  &&
7.            !year.equals("Sophomore") &&
8.            !year.equals("Junior")    &&
9.            !year.equals("Senior")) {
10.              throw new IllegalArgumentException(
11.                               year + " not a valid year");
12.        } else {
13.            this.year = year;
14.        }
15.    }
16.
17.    public String getYear() {
18.        return year;
19.    }
20.
21.    public void setGrade(double grade) {
22.        if(grade < 0.0 || grade > 105.0) {
23.            throw new IllegalArgumentException(
24.                             grade + " is out of range");
25.        } else {
26.            this.grade = grade;
27.        }
28.    }
29.
30.    public double getGrade() {
31.        return grade;
32.    }
33. }
See if you can determine the result of the following statements:
Student2 s2 = new Student2();
s2.setYear("Junior");
s2.setGrade(-24.5);
Invoking setYear with the argument “Junior” changes the year field to “Junior”. Invoking setGrade with the argument 24.5 causes an IllegalArgumentException to be thrown on line 23. Due to tight encapsulation, it is not possible for the values of Student2 to contain invalid values.
The benefits of encapsulation outweigh any overhead of the additional method calls, and any good OO design uses tight encapsulation in all classes. The next section discusses another important objectoriented design concept: loose coupling.

In the preceding section, you learned that you should hide instance variables by making them private. Why would a programmer want to hide something? In this section we discuss the benefits of information hiding.
The strategy of information hiding is not unique to computer programming—it is used in many engineering disciplines. Consider the electronic control module that is present in every modern car. It is a device that controls the timing of the spark plugs and the flow of gasoline into the motor. If you ask your mechanic what is inside the electronic control module, you will likely get a shrug.
The module is a black box, something that magically does its thing. A car mechanic would never open the control module—it contains electronic parts that can only be serviced at the factory. In general, engineers use the term "black box" to describe any device whose inner workings are hidden. Note that a black box is not totally mysterious. Its interface with the outside world is well-defined. For example, the car mechanic understands how the electronic control module must be connected with sensors and engine parts.
The process of hiding implementation details while publishing an interface is called encapsulation. In Java, the class construct provides encapsulation. The public methods of a class are the interface through which the private implementation is manipulated.
Why do car manufacturers put black boxes into cars? The black box greatly simplifies the work of the car mechanic. Before engine control modules were invented, gasoline flow was regulated by a mechanical device called a carburetor, and car mechanics had to know how to adjust the springs and latches inside. Nowadays, a mechanic no longer needs to know what is inside the module.
Similarly, a programmer using a class is not burdened by unnecessary detail, as you know from your own experience. In Chapter 2, you used classes for strings, streams, and windows without worrying how these classes are implemented.
Encapsulation also helps with diagnosing errors. A large program may consist of hundreds of classes and thousands of methods, but if there is an error with the internal data of an object, you only need to look at the methods of one class. Finally, encapsulation makes it possible to change the implementation of a class without having to tell the programmers who use the class.

INTERFACES VERSUS ABSTRACT CLASSES

The next question is when should you use interfaces and when should you use abstract classes. If two or more classes have lots of common functionality, but some methods should be implemented differently, you can create a common abstract ancestor and as many subclasses inheriting this common behavior as needed. Declare in the superclass as abstract those methods that subclasses should implement differently, and implement these methods in subclasses.
If several classes don't have common functionality but need to exhibit some common behavior, do not create a common ancestor, but have them implement an interface that declares the required behavior. This scenario was not presented in the "Interfaces" section of Lesson 6, but it's going to be a part of the hands-on exercise in the Try It section of this lesson.
Interfaces and abstract classes are similar in that they ensure that required methods will be implemented according to required method signatures. But they differ in how the program is designed. While abstract classes require you to provide a common ancestor for the classes, interfaces don't.
Interfaces could be your only option if a class already has an ancestor that cannot be changed. Java doesn't support multiple inheritance — a class can have only one ancestor. For example, to write Java applets you must inherit your class from the class Applet, or in the case of Swing applets, from JApplet. Here using your own abstract ancestor is not an option.
While using abstract classes, interfaces, and polymorphism is not a must, it certainly improves the design of Java code by making it more readable and understandable to others who may need to work on programs written by you.

Cloning in Java


Cloning: Cloning means creating the new object with the same state as the object you are cloning.

Default Cloning in Java: Shallow Cloning

I will explain Shallow Cloning with an example.

Suppose if I have StudentShallowEx class with following members

a)sid(1)
b)sname(String)("Anil")
c)address (This is an instance of class Address)

Address class has following members:

a)city(String)

When you clone the StudentShalloEx object(one in the following code) by calling clone() method,
new  StudentShalloEx will be created with the state of the original object you are trying to clone.
The drawback of this... is referenes will be copied to cloned object.So if you change the state
of the address object in cloned object,original object will be affected.

1)sid same as in  original object i.e 1
2)and sname as "Anil"
3)and the address reference in original object is copied to address reference in cloned object,so the
   address reference in original object and cloned object points to the same Address object thereby
   any changes you make to address reference in cloned will affect the original object.....

So,if you modify the address reference in cloned object it will change the address in
the original object.

But even if you change the sid in cloned object it won't affect the sid in the original object.

Imp Point: So if your object has only primitives and immutable objects like String,shallow
copy will be sufficient.

But if you have other class objects which are mutable like address in our example you have
to create deep copy.... so that changes you make to cloned object will not affect the original
object...





ShallowCloning Example Code:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package corejava;

/**
 *
 * @author Rishitha
 */
public class Address {
    private String city;
   
    Address(){
       
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

  
   
   
   
}
 


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package corejava;

/**
 *
 * @author Rishitha
 */
public class StudentShallowEx implements Cloneable{
  
    private int sid;
    private String sname;
    private Address address;

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public StudentShallowEx() {
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }
  
  
    public static void main(String args[])throws CloneNotSupportedException{
      
        StudentShallowEx one = new StudentShallowEx();
        one.sid=1;
        one.sname="Anil";
        Address add1 = new Address();
        add1.setCity("HYD");
        one.setAddress(add1);
        System.out.println(one.sid);
        System.out.println(one.getAddress().getCity());
        StudentShallowEx two = (StudentShallowEx)one.clone();
        two.getAddress().setCity("HYD is modified because it is shallow copying");
        two.setSid(2);
        System.out.println(one.sid);
        System.out.println(one.getAddress().getCity());
    }
  
  
}

DeepCloning:

When you do the deep clone of the Student,when you change the address in cloned object
it won't affect the address state in the original object.

In shallow cloning if you change the state of the address in cloned object,it will change
the address state in original object

To do deep cloning you have to do the following changes
--------------------------------------------------------------------------
1)Address class should implement Cloneable
2)It should override the clone method
3)StudentDeepCopy should override the clone method.

Deep Cloning code:


 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package corejava;

/**
 *
 * @author Rishitha
 */
public class Address implements Cloneable{
    private String city;
   
    Address(){
       
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
   
   
   
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package corejava;

/**
 *
 * @author Rishitha
 */
public class StudentDeepEx implements Cloneable{
   
    private int sid;
    private String sname;
    private Address address;

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public StudentDeepEx() {
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

  
    protected Object clone() throws CloneNotSupportedException {
       StudentDeepEx cloneOb = (StudentDeepEx)super.clone();
       cloneOb.address = (Address)cloneOb.getAddress().clone();
       return cloneOb;
    }
   
   
    public static void main(String args[])throws CloneNotSupportedException{
       
        StudentDeepEx one = new StudentDeepEx();
        one.sid=1;
        one.sname="Anil";
        Address add1 = new Address();
        add1.setCity("HYD");
        one.setAddress(add1);
        System.out.println(one.sid);
        System.out.println(one.getAddress().getCity());
        StudentDeepEx two = (StudentDeepEx)one.clone();
        two.getAddress().setCity("HYD is modified because it is shallow copying");
        two.setSid(2);
        System.out.println(one.sid);
        System.out.println(one.getAddress().getCity());
    }
   
   
}











Monday, October 7, 2013

Interview Questions

1)What is difference between comparable and comparator interface ?Why you need comparator when you have comparable interface ?

2)What is difference between ArrayList and Vector and LinkedList ?
You should be able to explain... the difference between them
and in what situation you prefer ArrayList over Vector.... or
When to use ArrayList over LinkedList ?
3)What is default cloning and difference between shallow and deep cloning in java ?
4)Why string is immutable and how to create immutable class in java ? 
5)What is concurrentHashmap ?
6)How hashing related collections work ?
7)Difference between hashtable and hashmap, can we use hashmap in multithreaded scenario ?
 
 
 
 
 

Monday, September 30, 2013

Interface Points

  • All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract.
  • All variables defined in an interface must be public, static, and final—in other words, interfaces can declare only constants, not instance variables.
  • Interface methods must not be static.
  • Because interface methods are abstract, they cannot be marked final, strictfp, or native. (More on these modifiers later.)
  • An interface can extend one or more other interfaces.
  • An interface cannot extend anything but another interface.
  • An interface cannot implement another interface or class.
  • An interface must be declared with the keyword interface.
  • Interface types can be used polymorphically

Thursday, September 26, 2013

About Static variables and Static Methods...

Static Variable:


Let me give you an example....

class Student{
      
         int sid;



}

Suppose... if you create 2 objects or instances for the student...

Student one = new Student();
Student two = new Student();

Student object one will have the sid
and Student object two will have its own sid..

So if you change the sid of one..,sid in two won't be changed... because
they both are different.........

Static variable:
----------------

class Student{
     static int counter;


}


 Now assume you created... 3 student objects

 Student one = new Student();
Student  two = new Student();
Student three = new Student();

As counter is declared as... static... all 3 student objects refer to same... counter variable...
Static means per class.... so... all the objects or instances of that class will have only counter
which is unique per class...

Even if you create 10000 student objects there will be only one counter variable.... and all
10000 students have access to.. that counter variable... if any student object changes the counter
variable that change will be reflected to alll the objects........

Example of non static and static variables...
--------------------------------------------

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package corejava;

/**
 *
 * @author Rishitha
 */
public class StaticEx {
   
    static int counter;
    int nonstatic;
   
   
    public static void main(String args[]){
        //non static variable
       
       
       
       
       
        StaticEx one = new StaticEx();
        one.counter = 10;
        one.nonstatic = 20;
        StaticEx two = new StaticEx();
        System.out.println(two.counter);//output is 10...
        //because... there is only one copy of counter per
        //class...
       
        System.out.println(two.nonstatic);//output is 0
        //because... I have assigned 20 to only one object
        //as I didn't assign any value to nonstatic variable
        //its default value is printed which is zero...
       
       
        //To access... static variable... you need not object...
        //In the previous example... i have used.. one.counter...
        //but you can use counter by writing
        //Classname.counter also...
        //That means... StaticEx.counter
       
        System.out.println(StaticEx.counter);
       
       
       
       
       
       
       
    }
   
   
   
   
   
   
   
}