Blog provide core concept of Java , J2ee , Struts Framework, Spring, Hibernate, apache ofbiz,Hybris e-commerce suit.Net4.0 framework,Websphere Application Server (WAS), DB2, WSAD and JavaScript. Also covers Tips and Tricks , Codes , Tutorials , Solutions for Developers , latest Interview Questions & Answers
Object constructor concept in Java | can we write a method name same as constructor name in class definition
Concept 1: can we write a method same name as constructor in class definition.
Exp: Yes we can write a method same name as constructor in java class definition.
Code :
Above code compile without Error
Exp: Yes we can write a method same name as constructor in java class definition.
Code :
package com.threadTest;
public class constructorTest {
public void constructorTest()
{
System.out.println("Inside the constructor");
return;
}
public static void main(String[] args)
{
constructorTest ct=new constructorTest();
}
}
public class constructorTest {
public void constructorTest()
{
System.out.println("Inside the constructor");
return;
}
public static void main(String[] args)
{
constructorTest ct=new constructorTest();
}
}
Above code compile without Error
Object wait() method concept in java multithread enviornment
Object method wait() in multithread enviornment
wait()
wait(long timeout)
wait(long timeout, int nanos)
the timeout is measured in milliseconds
nanos is measured in nanoseconds
the specified wait() time elapses
Throws
the wait() method throws three exceptions
IllegalArgumentException - if the timeout value passed is invalid
IllegalMonitorStateException - if the current thread does not own the object's lock
InterruptedException - if another thread interrupts the current thread. The interrupted status of the current thread is cleared
- the wait() method causes a thread to release the lock it is holding on an object; allowing another thread to run
- the wait() method is defined in the Object class
- wait() can only be invoked from within synchronized code
- it should always be wrapped in a try block as it throws IOExceptions
wait()
wait(long timeout)
wait(long timeout, int nanos)
the timeout is measured in milliseconds
nanos is measured in nanoseconds
- wait() can only invoked by the thread that own's the lock on the object
- when wait() is called, the thread becomes disabled for scheduling and lies dormant until one of four things occur:
- another thread invokes the notify() method for this object and the scheduler arbitrarily chooses to run the thread
- another thread invokes the notifyAll() method for this object
the specified wait() time elapses
- when one of the above occurs, the thread becomes re-available to the Thread scheduler and competes for a lock on the object once it regains the lock on the object, everything resumes as if no suspension had occurred
- if the thread was interrupted by another thread, an InterruptedException is thrown BUT not until after the thread regains it's lock on the object
Throws
the wait() method throws three exceptions
IllegalArgumentException - if the timeout value passed is invalid
IllegalMonitorStateException - if the current thread does not own the object's lock
InterruptedException - if another thread interrupts the current thread. The interrupted status of the current thread is cleared
Static keyword concept in Java |
Static keyword concept in Java
concept 1 : When we use Static keyword in class definition then JVM will allocate only one memory location for that and all object will take copy of that i.e. for each object there is no own property of that define static in class definition.
Code : package com.stat;
public class staticTest {
public int k=9;
public int getNum()
{
return this.k;
}
public void setNum(int a)
{
this.k=a;
}
public static void main(String [] args)
{
staticTest st1= new staticTest();
staticTest st2= new staticTest();
System.out.println("the value of k ="+st1.k);
st2.setNum(27);
System.out.println("the value of k ="+st2.k);
System.out.println("the value of k ="+st1.k);
}
}
Output :
the value of k =9
the value of k =27
the value of k =9
Exp: here from object st1 coming value 9 , after modify value to 27 . again it value comes 9 i.e. for each object there is own copy of int k.Code :
package com.stat;
public class staticTest {
public static int k=9;
public int getNum()
{
return this.k;
}
public void setNum(int a)
{
this.k=a;
}
public static void main(String [] args)
{
staticTest st1= new staticTest();
staticTest st2= new staticTest();
System.out.println("the value of k ="+st1.k);
st2.setNum(27);
System.out.println("the value of k ="+st2.k);
System.out.println("the value of k ="+st1.k);
}
}
output:
the value of k =9
the value of k =27
the value of k =27
Exp : when we declare int k to staic the JVM will allocate memory once for K and all object created of class will copy of that k , so when we modify the value will effect for every object.
Will default constructor is run When we deserialized of serialized object that implements serializable interface ?
Concept : Answer will NO, when we deserialized the object that implements serializable interface Default constructor will not run
Code :class SerializationBox implements Serializable {
public int a=900;
private int serializableProp = 100;
private transient int b=800;
private int c;
private static String st;
private String st1;
public SerializationBox()
{
System.out.println("The Default constructor running");
}
public SerializationBox(int a)
{
this.c=a;
System.out.println("The constructor running");
}
public int getSerializableProp() {
return serializableProp;
}
public int getStaticValue() {
return b;
}
}
public class SerializationSample {
public static void main(String args[]) throws IOException, FileNotFoundException, ClassNotFoundException
{
SerializationBox serialB = new SerializationBox(10);
serialize("C:\\Temp\\kumud.txt", serialB);
System.out.println("After Serialize");
SerializationBox sb = (SerializationBox) deSerialize("C:\\Temp\\kumud.txt");
System.out.println(sb.getSerializableProp());
System.out.println("Static Value"+sb.getStaticValue());
}
public static void serialize(String outFile, Object serializableObject) throws IOException {
FileOutputStream fos = new FileOutputStream(outFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serializableObject);
}
public static Object deSerialize(String serilizedObject) throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(serilizedObject);
ObjectInputStream ois = new ObjectInputStream(fis);
return ois.readObject();
}
}
Output :
The constructor running
After Serialize
100
Static Value0
Concept :After Serialize
100
Static Value0
In above output when object desrialized default constructor will not run
Serialization concept in java | how serialization work in java
Serialization in JAVA
Serialization in JAVA
Definition : java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again
Code :
package core;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class SerializationBox implements Serializable {
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class SerializationBox implements Serializable {
private int serializableProp = 100;
public int getSerializableProp() {
public int getSerializableProp() {
return serializableProp;
}
}
public class SerializationSample {
public static void main(String args[]) throws IOException, FileNotFoundException, ClassNotFoundException
{
SerializationBox serialB = new SerializationBox(10);
// serialization
serialize("C:\\Temp\\kumud.txt", serialB);
System.out.println("After Serialize");
{
SerializationBox serialB = new SerializationBox(10);
// serialization
serialize("C:\\Temp\\kumud.txt", serialB);
System.out.println("After Serialize");
//deserialization
SerializationBox sb = (SerializationBox) deSerialize("C:\\Temp\\kumud.txt");
System.out.println(sb.getSerializableProp());
System.out.println("Static Value"+sb.getStaticValue());
SerializationBox sb = (SerializationBox) deSerialize("C:\\Temp\\kumud.txt");
System.out.println(sb.getSerializableProp());
System.out.println("Static Value"+sb.getStaticValue());
}
public static void serialize(String outFile, Object serializableObject) throws IOException {
FileOutputStream fos = new FileOutputStream(outFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serializableObject);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serializableObject);
}
public static Object deSerialize(String serilizedObject) throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(serilizedObject);
ObjectInputStream ois = new ObjectInputStream(fis);
return ois.readObject();
FileInputStream fis = new FileInputStream(serilizedObject);
ObjectInputStream ois = new ObjectInputStream(fis);
return ois.readObject();
}
}
Output :
After Serialize
100
100
in above code when we serialize object and save into file C:\\Temp\\kumud.txt file and when desrialize agiain readObject convert into object and return function value 100
Concept : when you want to prevent to save the state during searialization , use Transient and static Key
package core;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class SerializationBox implements Serializable {
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class SerializationBox implements Serializable {
private int serializableProp = 100;
private transient int b=800;
public int getSerializableProp() {
private transient int b=800;
public int getSerializableProp() {
return serializableProp;
}
public int getNontransientValue() {
public int getNontransientValue() {
return b;
}
}
public class SerializationSample {
public static void main(String args[]) throws IOException, FileNotFoundException, ClassNotFoundException
{
SerializationBox serialB = new SerializationBox(10);
serialize("C:\\Temp\\kumud.txt", serialB);
System.out.println("After Serialize");
SerializationBox sb = (SerializationBox) deSerialize("C:\\Temp\\kumud.txt");
System.out.println(sb.getSerializableProp());
System.out.println("Transient Value"+sb. getNontransientValue);
{
SerializationBox serialB = new SerializationBox(10);
serialize("C:\\Temp\\kumud.txt", serialB);
System.out.println("After Serialize");
SerializationBox sb = (SerializationBox) deSerialize("C:\\Temp\\kumud.txt");
System.out.println(sb.getSerializableProp());
System.out.println("Transient Value"+sb. getNontransientValue);
}
public static void serialize(String outFile, Object serializableObject) throws IOException {
FileOutputStream fos = new FileOutputStream(outFile);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serializableObject);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serializableObject);
}
public static Object deSerialize(String serilizedObject) throws FileNotFoundException, IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(serilizedObject);
ObjectInputStream ois = new ObjectInputStream(fis);
return ois.readObject();
FileInputStream fis = new FileInputStream(serilizedObject);
ObjectInputStream ois = new ObjectInputStream(fis);
return ois.readObject();
}
}
Output :
After Serialize
100
Transient Value 0
After Serialize
100
Transient Value 0
Concept :
In above transient value does not save , so when we deserialize the coming value is 0,
so there is question coming in mind that is constructor is run during deserializtion
so there is question coming in mind that is constructor is run during deserializtion
How will you write an own immutable class in java ?
Writing an immutable class is generally easy but there can be some tricky situations. Follow the following guidelines:
1. A class is declared final (i.e. final classes cannot be extended).
public final class MyImmutable { ? }
2. All its fields are final (final fields cannot be mutated once assigned).
private final int[] myArray; //do not declare as Æ private final int[] myArray = null;
3. Do not provide any methods that can change the state of the immutable object in any way ? not just setXXX
methods, but any methods which can change the state.
4. The ?this? reference is not allowed to escape during construction from the immutable class and the immutable
class should have exclusive access to fields that contain references to mutable objects like arrays, collections
and mutable classes like Date etc by:
Declaring the mutable references as private.
Not returning or exposing the mutable references to the caller (this can be done by defensive copying)
Wrong way to write a constructor:
public final class MyImmutable {
private final int[] myArray;
public MyImmutable(int[] anArray) {
this.myArray = anArray; // wrong
}
public String toString() {
StringBuffer sb = new StringBuffer("Numbers are: ");
for (int i = 0; i < myArray.length; i++) {
sb.append(myArray[i] + " ");
}
return sb.toString();
}
}
// the caller could change the array after calling the
constructor.
int[] array = {1,2};
MyImmutable myImmutableRef = new MyImmutable(array) ;
System.out.println("Before constructing " + myImmutableRef);
array[1] = 5; // change (i.e. mutate) the element
System.out.println("After constructing " + myImmutableRef);
Out put:
Before constructing Numbers are: 1 2
Right way is to copy the array before assigning in the constructor.
public final class MyImmutable {
private final int[] myArray;
public MyImmutable(int[] anArray) {
this.myArray = anArray.clone(); // defensive copy
}
public String toString() {
StringBuffer sb = new StringBuffer("Numbers are: ");
for (int i = 0; i < myArray.length; i++) {
sb.append(myArray[i] + " ");
}
return sb.toString();
}
}
// the caller cannot change the array after calling the constructor.
int[] array = {1,2};
MyImmutable myImmutableRef = new MyImmutable(array) ;
System.out.println("Before constructing " + myImmutableRef);
array[1] = 5; // change (i.e. mutate) the element
System.out.println("After constructing " + myImmutableRef);
Out put:
Before constructing Numbers are: 1 2
As you can see in the output that the ?MyImmutable? object
has been mutated. This is because the object reference gets
After constructing Numbers are: 1 2
As you can see in the output that the ?MyImmutable? object has not
been mutated.
As you can see in the output that the ?MyImmutable? object has not
been mutated.
Wrong way to write an accessor. A caller could get the array
reference and then change the contents:
public int[] getArray() {
return myArray;
}
Right way to write an accessor by cloning.
public int[] getAray() {
return (int[]) myArray.clone();
}
Concept : Beware of using the clone() method on a collection like a Map, List, Set etc because they are not only difficult
to implement but also the default behavior of an object?s clone() method automatically
yields a shallow copy. You have to deep copy the mutable objects referenced by your immutable class.
section for deep vs. shallow cloning and for why you will be modifying the original object if you do not
deep copy.
Subscribe to:
Posts (Atom)