What is the approximate output of the following:
private ByteArrayOutputStream baos;
private ObjectOutputStream out;
baos=new ByteArrayOutputStream(10000000);
out = new ObjectOutputStream(baos);
for(int i=0;i<1000;i++)
out.writeObject("Madhu");
System.out.println("Size = " + baos.size());
Hopefully it should print 1000*5(length of "Madhu").
But it prints a number <100.
Why .............................?????????
Because OOO has a lot of optimizations techniques. It knows that we are writing the same object again and again, so it just increases a count of the object written.
So, be careful with java....
Sunday, February 22, 2009
Be careful with collection operations
Set set = new SomeSet();
short i=7;
set.add(i);
set.remove(i-1+1);
System.out.println("Size = " + set.size());
It prints 1 not 0.
Note i is short variable.
set.add(i) -> you are inserting short Object (auto boxing enters the picture).
set.remove(i-1+1) -> Here - operation promotes i to int and returns the result as int.
Finally we are trying to remove integer object (auto unboxing enters the picture).
Hence the answer is 1.
short i=7;
set.add(i);
set.remove(i-1+1);
System.out.println("Size = " + set.size());
It prints 1 not 0.
Note i is short variable.
set.add(i) -> you are inserting short Object (auto boxing enters the picture).
set.remove(i-1+1) -> Here - operation promotes i to int and returns the result as int.
Finally we are trying to remove integer object (auto unboxing enters the picture).
Hence the answer is 1.
What is the output of the following program?
public class dsj {
public static void main(String args[]) {
Number ding = (true || !true) ? new Integer(7) : new Float(16);
System.out.println(ding);
}
}
It is 7.0.
? : operator is not so direct to understand.
Avoid using it, if you are mixing types such as int,float or float,long etc....
Use if...else... control structure.
public class dsj {
public static void main(String args[]) {
Number ding = (true || !true) ? new Integer(7) : new Float(16);
System.out.println(ding);
}
}
It is 7.0.
? : operator is not so direct to understand.
Avoid using it, if you are mixing types such as int,float or float,long etc....
Use if...else... control structure.
Wednesday, February 18, 2009
Subscribe to:
Posts (Atom)