Friday 22 April 2011

Example code --How to copy elements of Arraylist to vector

Method to copy elements from Arraylist to Vector-- Collections.copy(v,arrayList);
  1. /*
  2. Copy Elements of ArrayList to Java Vector Example
  3. This java example shows how to copy elements of Java ArrayList to Java Vector using
  4. copy method of Collections class.
  5. */
  6. import java.util.ArrayList;
  7. import java.util.Collections;
  8. import java.util.Vector;
  9. public class CopyElementsOfArrayListToVectorExample {
  10. public static void main(String[] args) {
  11. //create an ArrayList object
  12. ArrayList arrayList = new ArrayList();
  13. //Add elements to Arraylist
  14. arrayList.add("1");
  15. arrayList.add("4");
  16. arrayList.add("2");
  17. arrayList.add("5");
  18. arrayList.add("3");
  19. //create a Vector object
  20. Vector v = new Vector();
  21. //Add elements to Vector
  22. v.add("A");
  23. v.add("B");
  24. v.add("D");
  25. v.add("E");
  26. v.add("F");
  27. v.add("G");
  28. v.add("H");
  29. /*
  30. To copy elements of Java ArrayList to Java Vector use,
  31. static void copy(List dstList, List sourceList) method of Collections class.
  32. This method copies all elements of source list to destination list. After copy
  33. index of the elements in both source and destination lists would be identical.
  34. The destination list must be long enough to hold all copied elements. If it is
  35. longer than that, the rest of the destination list's elments would remain
  36. unaffected.
  37. */
  38. System.out.println("Before copy, Vector Contains : " + v);
  39. //copy all elements of ArrayList to Vector using copy method of Collections class
  40. Collections.copy(v,arrayList);
  41. /*
  42. Please note that, If Vector is not long enough to hold all elements of
  43. ArrayList, it throws IndexOutOfBoundsException.
  44. */
  45. System.out.println("After Copy, Vector Contains : " + v);
  46. }
  47. }
  48. /*
  49. Output would be
  50. Before copy Vector Contains : [A, B, D, E, F, G, H]
  51. After Copy Vector Contains : [1, 4, 2, 5, 3, G, H]
  52. */

how to make class Singleton

Singleton Design Pattern Example Program
>> Monday, April 18, 2011

Singleton Design pattern will allow only one object per Class(JVM).

Before Writing Singleton Design pattern you should follow these steps.

#1). create an instance as static and return type as The same class, and it should be assigned as null.

private static Singletonn instance = null;



#2). "Create a Constructor as private" to deny the creation of object from other class.

private Singletonn(){
       
    }



#3). Write a static method to create object for our class.It should be Once for a class.

public static Singletonn getInstance(){

}



#4). At last return the class Object.


Here We are creating the object once only not again and again.The first time created object is returning again when you called.

package javabynataraj.basic;

class Singletonn {
    private static Singletonn instance = null;
    private Singletonn(){
       
    }
    public static Singletonn getInstance(){
        if(instance==null){
            instance = new Singletonn();
        }
        return instance;
    }
}

public class Singleton{
    public static void main(String[] args) {
        System.out.println("before calling ...");
        System.out.println(Singletonn.getInstance());
        System.out.println("Once Called");
        System.out.println(Singletonn.getInstance());
        System.out.println("Second time called");
    }
}

why String is immutable?

Interview question on String in Java which starts with discussion of What is immutable object , what are the benefits of immutable object , why do you use it and which scenarios do you use it.

It can also come once interviewee answers some preliminarily strings questions e.g. What is String pool , What is the difference between String and StringBuffer , What is the difference between StringBuffer and StringBuilder etc.

Though there could be many possible answer for this question and only designer of String class can answer this , I think below two does make sense

1)Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

String A = "Test"
String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

2)String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as stirng , you can pass database URL as string for opening database connection, you can open any file by passing name of file as argument to File I/O classes.

In case if String is not immutable , this would lead serious security threat , I mean some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file.

3)Since String is immutable it can safely shared between many threads ,which is very
important for multithreaded programming.

I believe there could be some more very convincing reasons also , Please post those reasons as comments and I will include those on this post.

Monday 18 April 2011

multithreading


How does multithreading improve the performance of Java?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
Since multiple actions happen parallel (almost/virtually) to one another rather than one after the other, multithreading improves performance.

Ex: lets say there are three actions each that will take 5 seconds.

so, in a single threaded environment it will take atleast 15 seconds if they happen one after the other.

But, if we spawn three threads and have these actions started at the same time, all 3 will complete probably in around 6 or 7 seconds which is much faster than the earlier 15 seconds it took.

What advantages of multithreading in java?

http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
The advantage is the fact that multiple threads run parallel to one another and hence things happen faster than they would if they run one after the other

What is the Life cycle diagram of Thread in Java? Different states of thread?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
Different states of a thread are :

New state - After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.

Runnable (Ready-to-run) state - A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.

Running state - A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.

Dead state - A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.

Bocked - A thread can enter in this state because of waiting the resources that are hold by another thread.

Sunday 17 April 2011

Difference between class variable and instance variable


What is Difference between class variable and instance variable with example?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
Well, at the basic level, class fields, or static fields, as they are called sometimes, belong to the class and not to any particular instance of the class. Class fields can be assigned without instantiation of instance objects of a class. For example:

public class ExampleClass {
public static String classField = "";
public String instanceField = "";
}

I can assign a value to classField just like that:

ExampleClass.classField = "new value";

Instance fields, on the other hand, belong to a particular instance of the class. Thus, to assign an instance field a value, you have to first instantiate an object of the class just like that:

ExampleClass obj1 = new ExampleClass();
obj1.instanceField = "new value";

What is the difference between static global and local global variable?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
From Java point of view, static global class members are shared among all class instances and can be accessed from any class member [Methods]. While local global [attributes] can be accessed from any class member [method] but not shared with other class instances

Answer

The global variable can be shared across multiple files. But the global static variable cannot be shared across multiple files. Hence if you want the variable should be modified in some other file, you can make it a global variable and if you want a global variable only in the file you are declaring and not to shared across, you make it static global.
the following code snippet should be useful. //ext2.c int a=10; static int s_b=89;
//ext.c extern int a; extern int s_b; int main() { printf("a = %d\n",a); printf("static b = %d\n",s_b); return 0; }
then build the exe with ext.o and ext2.o and try running.. you will encounter an error like this "./ext.o(.text+0x20): undefined reference to `s_b'"
What is the difference between declaring static variable as local and global?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319

Answer

There are two ways to declare varibles.
1. Locally
2. Globally
When you declare a variable locally in any function that means it is only accessible by that function.
When you declare a variable globally so it is accessible by all the functions in the program.
Declaring variables with static keyword means you are setting its value null.

Difference between global variables and local variables?

http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
Global Variable
It is a variable which is declared outside all the functions
It is a variable which is declared with in a function or with in a compound statement
Local Variable
It is accessible throughout the program
It is accessible only within a function/compound statement in which it is declared

Difference between Reference and object



What is difference between reference and object?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
References are stored in stack while objects are stored in heap.
Reference holds the memory address of an object, that’s why they are called reference. If they don’t refer to any object in heap, they hold 'null', meaning nothing.

Objects hold the actual data in them. This data is accessed (either read, or written) through reference. An object may be referenced by zero or more references.

For example, consider a class Person, which can hold 'name'.
I create 2 reference variables of Person type.
Person p1;
Person p2;

at this moment both references contain 'null'. An attempt to access 'name' data will throw an error. Now assigning new object to 'p1'.
p1 = new Person();
this causes an object to be created in heap, and its reference(memory address) is stored in p1. Now I can access 'name' data of this object created through p1.

p1.name = "Tom";

Assigning p2 to p1, will make p2 pointing the same object in the heap as p1 is pointing to. Thus if you change 'name' through p2, you are actually changing the same object as p1 is pointing to.

p2 = p1;
p2.name = "Sam";
both p1 and p2 reference variables that are in stack, are pointing to the same object that is in heap.

What is difference between instance and object in Java?


The definition of an instance in an occurrence of something. Since an object in Java is an occurrence of a class, I would say that an object and an instance are one and the same.
In java what is the difference between class variable and instance variable?

The main difference between the class variable and Instance variable is,
first time, when class is loaded in to memory, then only memory is allocated for all class variables. Usually static variables are called class variables. These variables are available throughout the execution of the application and the values are common to the class. You can access them directly without creating an object of the class.

Instance variables are normal variables declared in a class, that would get initialized when you create an instance of the class. Every instance of the class would have a copy of the variable and you need a class instance (object) to access these variables

Difference Between Instance variable and Static Variable?

http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
In java, any variable marked as a static is considered a variable owned by the class. Even if you have a bunch of instances of this class, you only will have one copy of your static variable shared by all the instances.

This is the main difference with instance variables where each instance of your class have his own variables.

Example, if you have a class like this:

public class SoldCar{
public String model; //instance variable - each soldCar have its model
public int cost; //instance variable - each soldCar have its cost
public static int count; //class variable - all soldCars share this count

public SoldCar(){
count ++;
}

public static void main(String[] args){
SoldCar ferrari = new SoldCar();
ferrari.model = "fiorano";
ferrari .cost = 999999;

SoldCar beetle = new SoldCar();
beetle.model = "new beetle";
beetle.cost = 2222;

System.out.println( ferrari.model + "," + ferrari.count );
System.out.println( beetle.model + "," + beetle.count );
}
}

The output of this program is :
fiorano,2
new beetle,2

In oops what is the difference between class variable and variable?
http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
Class Variable is a subset of Variables.

Difference between global variables and local variables?

http://en.site2.answcdn.com/templates/icons/abar_a.gif?v=82319
Global Variable Local Variable 2
It is a variable which is declared outside all the functions
It is a variable which is declared with in a function or with in a compound statement
l It is accessible throughout l It is accessible only within a function/
the program compound statement in which it is
declared