Tuesday, May 30, 2006

Date and Time code

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Locale;

class DateTimeUtil {
public static void main(String[] args) {

Locale currentLocale = new Locale("en","IN","WINDOWS");
DateFormat dateformat = DateFormat.getDateInstance(DateFormat.SHORT,
currentLocale);
Date currdate = new Date();
String dateResult = dateformat.format(currdate);
System.out.println("Date: " + dateResult);

SimpleDateFormat simpletimeformat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
Date date = new Date();
String timeResult = simpletimeformat.format(date);
System.out.println("Time: " + timeResult);
}
}

Saturday, May 27, 2006

try/catch

we are supposed to use the most appropriate exception in the catch clause.

for example

try{
FileInputStream fin = new FileInputStream("A.java");
}catch(FileNotFoundException exp1){
System.out.println("file not found");
}

Why it's NOT advisable to use something like

try{
FileInputStream fin = new FileInputStream("A.java");
}catch(Exception exp1){
System.out.println("file not found");
}

kindly explain.

Ans:

Well the class Exception is much wider than FileNotFoundException, and will catch every subclass of Exception.

One reason people cast the net wide with an overly general catch block is because code may throw several different exceptions:

code:

try {
...
}
catch (ClassNotFoundException e) {...}
catch (InstantiationException e) {...}
catch (IllegalAccessException e) {...}
catch (EtcException e) {...}

don't just catch "Exception" unless you really don't what to know or care what went wrong.

Can we Skip finally block?

Is it possible to skip the 'finally' block even though its present after a try/catch block. i.e

try{
...//write some code here to make finally never execute.
}finally{
...
}

Give me some possible ways to achieve this?

Ans:

1. System.exit(1);
2. Thread - wait() strategy.

try {
final Object o = new Object();
synchronized(o) {
o.wait();
}
}
finally {
System.out.println("blah");
}

My point being that this -- and any number of other "solutions" -- isn't actually skipping the finally at all; just delaying -- perhaps for an infinite time -- reaching it. There really is no way to skip it (unless you want to count System.exit() -- even that is cheating, really, as you're only skipping it by terminating the program. Truly "skipping it" would mean continuing the same thread in the same program after the try block completes, and that's not possible.


Using System.exit() doesn't skip anything, it merely terminates the entire JVM before the code is executed. If you consider the termination of a JVM before the execution of a finally block "skipping" the finally block then by that definition all code is skipped. It is impossible to skip a finally block.

Object v/s instance?
An object is a specific form of an instance: the instance of a class.

What is an object?

* It's a thing with state and behavior, of course.
* Its an instance of a class

What is a class?

* A class is the definition of some object data type.

What is a JVM?

JVM is Java Virtual Machine, which provides a layer of abstraction. It acts as a interface between the compiled class file and the underlying OS. The java in bin directory is nothing but JVM. It interprets the class file and provides instruction always in same format. That's why we say java is platform independent.

Java - Strongly Typed Language

The Java programming language is a strongly typed language ? what does it mean ?

In javascript u can create variables using "var"

ex: var a;

here variable "a" can hold char,int,float,etc so many types.

but in Java u need to declare the type of variable before using it & also u cannot directly assign variable of one type into another, u need to do casting.

strong vs. weak typing

This distinction refers to the behavior of the language when values are operated on. In a strongly typed language, operations must match the types of the values operated on (addition must be performed on numbers, for example). In weakly typed languages operations might be made on values which are inappropriate.

Example of typical weak-type language is PHP (also many other script languages):

$variable_one="hallo";
$variable_two=10;
$variable_three=$variable_two+"15";
$variable_four=$variable_one+"20";
echo $variable_three; //will result 25, the string "15" will be automatically casted to integer
echo $variable_four; //will result 20, the interpreter is confused how to handle the string "hallo"

As you can see the weak-type language has its advantages and disadvantages:
Advantages:
1. easier for beginner
2. faster to develop

Disadvantages:
1. nightmare to debug (especially if it is a large app)
2. give more tolerance for failure or wrong understanding (which could lead to serious security issues)
3. Can be a source of memory/performance hog

This big tolerance for failure which could lead to disaster is also an argument why many say JEE or .Net(C#) is much more scalable than PHP or some other weak-type script languages.

Thursday, May 25, 2006

Serialization Concepts

System property

How to know the OS name on which my Java application is running?

System.out.println(System.getProperty("user.name" ));

How can I learn the various keys in System property?

Enumeration en = System.getProperties().propertyNames();

while(en.hasMoreElements()){
System.out.println("Result : " + en.nextElement());
}

Garbage Collection

What happens when JVM runs out of memory?How does it communicate this to java Application?

An OutOfMemoryError exception is thrown.

How much memory is allocated to JVM? Is it same under all platforms.

It depends on the configuration that you set when you run the JVM. The java application launcher let you set a couple of flags to control that:

-Xmsn: Specify the initial size, in bytes, of the memory allocation pool. The default value is 2MB.

-Xmxn: Specify the maximum size, in bytes, of the memory allocation pool. The default value is 64MB.

How to create mutable and im-mutable class

Wrapper Class

check out the following code:-

Integer i=Integer.valueOf(1);
Integer j=Integer.valueOf("1");
System.out.println(i==j);
Boolean b1=Boolean.valueOf(true);
Boolean b2=Boolean.valueOf("true");
System.out.println(b1==b2);

output is :-false true. why?


The valueOf() method in Integer class returns distinct objects. Hence the first result is FALSE.

But, the interesting part with Boolean class is that, it returns a reference to Boolean.TRUE (or) Boolean.FALSE objects.

Notes from API:


public static Boolean valueOf(boolean b)
value is Returns a Boolean instance representing the specified boolean value. If the specified booleantrue, this method returns Boolean.TRUE; if it is false, this method returns Boolean.FALSE. If a new Boolean instance is not required, this method should generally be used in preference to the constructor Boolean(boolean), as this method is likely to yield significantly better space and time performance.

public static Boolean valueOf(String s)

Returns a Boolean with a value represented by the specified String. The Boolean returned represents the
value true if the string argument is not null and is equal, ignoring case, to the string "true".

Example: Boolean.valueOf("True") returns true.
Example: Boolean.valueOf("yes") returns false.

Programming problem

1. String score = "2,2,2,3";
Write a program to add the numbers and print the sum.

import java.io.*;

public class Splits{
public static void main(String[] args) {

String score = "2,2,2,3";
PrintWriter out = new PrintWriter(System.out, true);
String sc[] = score.split(",");

int in = 0;

for(int i=0;i
out.println(sc[i]);
in = in + Integer.parseInt(sc[i]);
}
out.println("Total: " + in);
}
}

2. Write a program to reverse the following string.
String s = "abc xyz";

StringBuffer sb = new StringBuffer(s);
System.out.println(sb.reverse());

Difference between length variable and length() method

For String you use "length()", for an array you use just "length".

The reasoning is that String is just a class. You could make one similar yourself if you want. Therefore operations on it should be methods like "length()". To work out the length of a String it might be necessary to go through and count all the characters.

An array is really a built-in data structure. The nember of slots in an array is set when it is created, and can never change without creating a whole new array, so it is reasonable to put that value in a member variable.

NOTE:

length is a final member of all arrays.



Explain System.out.println()

The System class contains several useful class fields and methods. It cannot be instantiated(Private Constructor). It is a final class.

A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.

err ==> The "standard" error output stream.
in ==> The "standard" input stream.
out ==> The "standard" output stream.

All the three fields final and returns PrintStream.

* Unlike other output streams, a PrintStream never throws an IOException;
* Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.

All characters printed by a PrintStream are converted into bytes using the platform's default character encoding.

print() and println() are methods of PrintStream class.

Wednesday, May 24, 2006

Programming Problem

We have a java program(Read only) and lets name it A.java, and this program is compiler error free. Now lets make certain changes to it(delete/comment) some logic and print statements and store it as B.java.

Since B.java is a new program there are possibilities for compiler errors in it. Now without compiling B.java we should figure out if there are any syntax errors in it.

Clue: Your program can take only B.java and find the solution (or) both A.java and B.java do some comparison (or) other logic and should print there is no error (or) error in the new program.

Ans:

class A {
public static void main(String[] args) {
System.out.println("Hello");
System.out.println(" World!");
}
}

class B {
public static void main(String[] args) {
int i='a'; // condition 1
int i="a"; // condition 2
// System.out.println("Hello");
System.out.println(" World!");
}
}

public class CTest {
public static void main(String[] args) throws Exception {
Process p = Runtime.getRuntime().exec("javac A2.java");
p.waitFor();
System.out.println(p.exitValue() == 0 ? "no error" : "error");
}
}

OUTPUT:

For condition 1 in B.java:
no error: since int accepts char value


For condition 2 in B.java:
error: since int doesn't accepts String

There is another tool that checks syntax but does not generate byte code. It is JavaDoc

Size of a serialized java object using core java

I don't know of any easy way to find out how much memory an object in memory uses in Java. It is not in the standard API. If you really want to know, there might be a way using the debugger APIs, but it won't be easy. Note that the amount of memory an object occupies is implementation dependent - it might be different on different JVMs and on different platforms.

To find out the size of a serialized object: you could write the object to a file and see how large the file is. But the size of an object in serialized form is something different from the size an object occupies while it is "live" in memory.

Tuesday, May 23, 2006

Overriding and throws clause

Overriding and throws clause

The finalize() method in Object can throw any Throwable Object. Overriding methods can limit the range of throwables to unchecked exceptions. Further Overridden definitions of this method in subclasses will not be able to throw checked exceptions.

Ans: Yes

public class Runner {

public static void main(String[] args) {

MyType myType = new MyType();

myType=null; // Line 1
java.util.ArrayList arrayList = new java.util.ArrayList(); //line 5

while(true) {
arrayList.add(new String("waste"));

}
}
}

class MyType{
protected void finalize() throws Exception{
System.out.println("bye");
}
}

How do u say "yes". In the above example I used an "Exception" in the throws clause which is a "checked Exception". The compiler didn't complain about any thing.

Let's look again at the second and third sentences you quoted: "Overriding methods can limit the range of throwables to unchecked exceptions. Further Overridden definitions of this method in subclasses will not be able to throw checked exceptions." Now I assumed that these two sentences went together. That is when they talk about "further overridden definitions", they mean further after you've already overridden with a method that limits the range of throwables to unchecked exceptions. You haven't done that, so you're getting different results than they describe.

Try this:

code:

class Foo {
protected void finalize() {
System.out.println("finalize in Foo");
}
}


class Bar extends Foo {
protected void finalize() throws Exception {
System.out.println("finalize in Bar");

}
}

This won't compile, because Foo overrides finalize() in a way that limits the range to only unchecked exceptions. And Bar extends Foo. So finalize() in Bar can't throw any new checked exceptions. That's what the quoted text is talking about.

Instance Initializer Blocks in Anonymous classes.

import java.io.*;

public class Check {

public static void main(String[] args) {
Clock c = new Clock();
c.call();
}

void result() {
System.out.println("Hello");
}
}

class Clock {

public void call() {
try{
Check ck = new Check() {
// FileInputStream fis = new FileInputStream("file.txt");

{
FileInputStream fis = new FileInputStream("file.txt");
}

void result() {
System.out.println("Hello World!" );
}
};
ck.result();
}catch(Exception ie) { }
}
}

/*

"Instance initializers in annonymous classes can throw any uncaught checked exception."
The Constructor of FileInputStream produces FileNotFoundException which is an checked exception.
This is an example of the above statement. This compiles fine.

In case of normal classes, the only checked exceptions allowed to be thrown by instance initializers are those that have been delcared to be thrown by each constructor. Furthermore, the class has to have at least one explicit constructor. Anonymous classes don't have explicit constructors so the rule that applies here is that their initializers can throw any exception without the need for declaring it.

*/

Instance Initializer Blocks in Normal Classes

import java.io.*;

class Checkep {

{
FileInputStream fis = new FileInputStream("file.txt"); System.out.println("instance block");
}

public static void main(String[] args) {
try {
Checkep c = new Checkep();
}catch(IOException ie) { }

System.out.println("main method");
}

Checkep() throws IOException {
System.out.println("constructor");
}
}

/*

Refer Khalid Mugal Book page: 341

In case of normal classes, the execution of instance initializer blocks can result in uncaught checked exception. The only checked exceptions allowed to be thrown by instance initializers are those that have been delcared to be thrown by every constructor in th class. Furthermore, the class has to have at least one explicit constructor. Anonymous classes don't have explicit constructors so the rule that applies in anonymous classes is that their instance initializers can throw any exception without the need for declaring it.

*/

Marker Interface

The Purpose of the Marker Interface
One of the "clean" features of the Java programming language is that it mandates a separation between interfaces (pure behavior) and classes (state and behavior). Interfaces are used in Java to specify the behavior of derived classes.

Often you will come across interfaces in Java that have no behavior. In other words, they are just empty interface definitions. These are known as marker interfaces. Some examples of marker interfaces in the Java API include:


- java,lang.Cloneable
indicates that the objects clone method may be called

- java,io.Serializable
asserts that objects that implement it may be serialized using java.io.ObjectOutputStream.
- java.util.EventListener
is used for event listener classes

- javax.servlet.SingleThreadModel
states that this class should not be called for multiple threads concurrently
Marker interfaces are also called "tag" interfaces since they tag all the derived classes into a category based on their purpose. For example, all classes that implement the Cloneable interface can be cloned (i.e., the clone() method can be called on them). The Java compiler checks to make sure that if the clone() method is called on a class and the class implements the Cloneable interface. For example, consider the following call to the clone() method on an object o:

SomeObject o = new SomeObject();
SomeObject ref = (SomeObject)(o.clone());
If the class SomeObject does not implement the interface Cloneable (and Cloneable is not implemented by any of the superclasses that SomeObject inherits from), the compiler will mark this line as an error. This is because the clone() method may only be called by objects of type "Cloneable." Hence, even though Cloneable is an empty interface, it serves an important purpose.

Ken Arnold, who was/is behind several Java APIs at Sun, sounds off on marker interfaces here, noting that they should rarely be used.

With the advent of annotations in Java 5 -which are a generic mechanism of adding metadata to a class-, marker interfaces have become obsolete, and no new ones should be defined.

Excerpt from Ken Arnold:

I mentioned the term contract a couple times in this discussion. To me, object design is a design of contracts. Contracts define what you are allowed to rely on.

Java has types as well as methods. There are contracts for entire types and contracts for methods. The contract for the whole class or interface, then, says if you implement this interface, you will have, in general, the following kinds of behaviors.

To me, a marker interface isn't wrong. It is a general case in the sense that it has no methods, so the whole contract is associated with the class and says what things of that type do. As a degenerate case, a marker interface probably shouldn't occur often. But on the other hand, there are times when a marker interface is a legitimate way to express that if you implement this interface, then you are have certain relationships.

Serializable might be a good example. None of the methods related to serialization belong as methods in the Serializable interface itself. For example, readObject should not be a public method in the Serializable interface. It is an implementation detail. At the same time, Serializable is a behavioral contract that says you do expect your state shipped up in little bits and then those bits deconstructed into another copy of you. Serializable says that you have written the associated code to make sure serialization works right. So now I know I can use the object in a certain way--I can serialize and deserialize it. That is a real contract about an object that has a Serializable marker interface. I do think marker interfaces are rarely correct. But I don't think they are incorrect in principle.

Java Collections

Disadvantages with Java

In the quest for portability Java deliberately left out access to system-specific things. You can't directly call Windows APIs or COM or DDE or 3rd party DLLs.

This is true in general, but Sun and other third parties are striving to provide JNI or similar interfaces to allow such access... take JavaSound: there's a Java abstraction on top of the native OS hardware communication, but you can still do practically everything you can with a C/C++ application (but in a much more elegant way). Same with the addition of some classes in the Image I/O which make use of graphics cards and their hardware acceleration.

Another new example of this (which I only found out about a couple of weeks ago) is the addition of the java.lang.Process and ProcessBuilder classes which enable you to start and control processes directly in the OS (outside the JVM)... this is incredibly useful, and prior to J2SE 5.0 would have most likely required a native driver program.

Link-I

Link-II

Difference between System.out and System.err

The first writes to "standard output". The second writes to "standard error". These two streams are setup by the operating system when the Java program is executed... And can be redirected with the uses of "|", ">", etc. on the command line.

Thursday, May 18, 2006

why does java doesn't support multiple inheritance

One big problem with mulitple inheritance is what to do when both base classes implement a particular method differently. If the subclass doesn't override this method, what code should be called? This situation often arises when both base classes themselves extend from a common ancestor. In this case, a class hierarchy diagram would show a diamond pattern of classes.

This conflict doesn't exist for interfaces, because they don't provide implementations. It is perfectly acceptable for a class to implement two interfaces that define the same method. However, if the interfaces defined methods with identical signatures, but differing return types, there would still be a conflict.

Friday, May 12, 2006

static final methods

class A {
public static void isNotFinal() {}
public static final void isFinal() {}
}

class B extends A {
public static void isNotFinal() {} //ok
public static void isFinal() {} //error!
}


It stops you from declaring a static method with the same name and parameter types in a derived class.