Following xml fragments will give an idea of how to use multiple dtd's in xml and also the workaround of specifying namespace in dtd
File : s.dtd
============
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT computer (ns1:address) >
<!ELEMENT ns1:address (type, ipaddress)>
<!ELEMENT type (#PCDATA)>
<!ELEMENT ipaddress (#PCDATA)>
File : s1.dtd
==============
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT ns2:student (name, ns2:address, computer) >
<!ATTLIST ns2:student xmlns:ns2 CDATA #FIXED "http://krishna/ns2">
<!ELEMENT ns2:address (#PCDATA) >
<!ELEMENT name (#PCDATA) >
File:student.xml
================
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ns2:student SYSTEM "s1.dtd" [<!ENTITY % s SYSTEM "s.dtd">
%s;
]>
<ns2:student xmlns:ns2="http://krishna/ns2">
<name >krishna</name>
<ns2:address>unknown</ns2:address>
<computer>
<ns1:address>
<type></type>
<ipaddress></ipaddress>
</ns1:address>
</computer>
</ns2:student>
Wednesday, June 21, 2006
Monday, June 19, 2006
Anonymous array declaration
Anonymous arrays have to be assigned to the variables at the time of declaration of varaible itself. Assigning to the variable after variable declaration is not possible
ie.,
int[] i = {1,2,3} is fine.
But,
int[] i;
i = {1,2,3} is compiler error.
This restriction at the time of method invocation is valid, since we don't know the type of array(overloading issue). But for assignment the left side variable type is known. So, why should it be not possible to cast the anonymous array {1,2,3} to int[] and assign to variable.
ie.,
int[] i = {1,2,3} is fine.
But,
int[] i;
i = {1,2,3} is compiler error.
This restriction at the time of method invocation is valid, since we don't know the type of array(overloading issue). But for assignment the left side variable type is known. So, why should it be not possible to cast the anonymous array {1,2,3} to int[] and assign to variable.
Sunday, June 18, 2006
i=i++ produces the output "0" instead of "1".
The code
int i = 0;
i = i++;
System.out.println(i);
produces the output "0" instead of "1".
"i = i++" roughly translates to
int oldValue = i;
i = i + 1;
i = oldValue;
int i = 0;
i = i++;
System.out.println(i);
produces the output "0" instead of "1".
"i = i++" roughly translates to
int oldValue = i;
i = i + 1;
i = oldValue;
Are string literals garbage collected?
The answer is no. String class maintain a list of references to string(in heap) in the constant pool. When new is used to create string, then a new string object is created in heap and the reference to this object is returned to the code. Thus, we will have two string objects. If intern() method is called on this object, then the reference to the other string object(whose reference is maintained in literal pool) is returned to the code and the string object created using new will be garbage collected. Even when there are no references to the string literal object, string literal will not be garbage collected, because the reference to this object is still maintained in the string literal pool
Saturday, June 17, 2006
My Notes from JLS 3.0
Lexical Structure
1. Legal code point is U+0000 to U+10FFFF. Code points greater than U+FFFF are supplementary characters. Supplementary characters are stored as pairs of two 16-bit code units. (High Surrogate range: U+DB80 to U+DBFF and Low Surrogate Range : U+DC00 to U+DFFF).
2. Line Terminator is the ASCII character CR(“return”) followed by LF(“new line”).
3. Input Elements are : Whitespace(space, horizontal tab, form feed), comment(/* .. */ and //) and token(Identifiers, keyword, literal, separator and operator).
4. Comments do not nest.(/* and */ do not have special meaning inside // and // has no special meaning in comments that begin with /* or /**).
5. Identifier : Identifierchars but not a keyword or BooleanLiteral or NullLiteral).
6. Identifiers begin with JavaLetter(Character.isJavaIdentifierStart(int)) followed by JavaLetterOrDigit(Character.isJavaIdentifierPart(int)).
7. Literals : Integer(Decimal, octal and hexadecimal), Floating point(decimal or hexadecimal), Boolean(true & false), Character, String and Null literal.
8. This assignment String s1 = "\u000a"; will cause compiler error. Because \u000a is line feed character. Hence, within string literal to use line feed use “\n”
9. Literal Strings refer to the same string object. Strings computed by constant expressions are computed at compile time and then treated as if they are literals. String hello = "Hello", lo = "lo"; ((hello == ("Hel"+"lo")) is true.
10. Strings computed by concatenation at run time are newly created and therefore distinct. Thus, (hello == “Hel” + lo) will be false.
11. Escape sequence : b,t,n,f, r, “,’,\ and octal escape( \ followed by one to three octal digits).
Types, Values and Variables
1. Strongly Typed language: Every variable and every expression has a type that is known at compile time.
2. Integer operators throw NPE if unboxing conversion of a null reference is required. In divide and remainder operator, they throw Arithmetic exception, if right-hand operator is zero. OutofMemoryError in case of ++ and – if boxing conversion is required and there is not sufficient memory for conversion.
3. Floating Point : Positive zero and negative zero compare equal.
4. NaN is unordered, so the numerical comparison operators <, <=, >, >= return false if either or both the operands are NaN. Equality operator returns false if either operand is NaN. Inequality operator return true if either operand is NaN.
5. The language uses round toward zero when converting a floating value to an integer
6. An operation that overflows produces a signed infinity, an operation that underflows produces a denormalized value or a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result.
7. Heap pollution : List l = new ArrayList(); List ls = l; // unchecked warning. Heap pollution arises, as the variable ls, declared to be a List, refers to a value that is not in fact a List.
Conversions and Promotions
1. Five Conversion Contexts : Assignment Conversions, Method Invocation Conversions, Casting conversion, String conversion, Numeric conversion
2. 11 Conversion categories : Identity conversion, Widening primitive conversion, Narrowing Primitive Conversion, Widening and Narrowing primitive conversion, widening reference conversion, narrowing reference conversion, boxing conversion, Unboxing conversion, Unchecked conversion(raw type to generic type), capture conversion
3. Narrowing primitive conversion : short to char is also narrowing primitive conversion(cause char is unsigned while short is signed. So short to char loses precision).
4. Widening and Narrowing primitive conversion : byte to char. Here byte is first widened to int and then narrowed to char
5. Assignment Conversions allows the following: identity, widening primitive, widening reference, boxing, unboxing.
6. If the expression is a constant expression of type byte, short, char or int:
a. Narrowing primitive conversion if type of variable is byte, short or char and the value of constant expression is representable in the type of variable.
b. Narrowing primitive conversion followed by boxing conversion if type of variable is Byte, Short or Character and the value of constant expression is representable in byte, short or char respectively.
7. Implicit narrowing of integer constants is not available in Method invocation conversions. (Reason being it will add complexity to the overloaded method resolution process).
Names
1. Obscured declarations : a simple name may occur in contexts where it may potentially be interpreted as the name of variable, type or package. In this case, variable will be chosen in preference to a type, and that a type will be chosen in preference to a package.
2. Members of package : sub package, top level class types and top level interface types
3. Members of class type : classes, interface, fields and methods.
4. A class or interface may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any of the fields by its simple name results in a compile-time error.
5. Members of array type : public final field length, public method clone and members inherited from Object(except method clone).
Packages
1. A package may not contain two members of the same name, or a compile-time error results.
2. package names mightg contain Unicode characters. If the host OS doesn’t support Unicode characters(\uxxxx) in their file system name, then the file name can be named by replacing the unicode characters as @xxxx. Java will map the Unicode character(\uxxxx) to the letters @xxxx in the file name.
3. An implementation of the Java platform must support at least one unnamed package; it may support more than one unnamed package but is not required to do so. Which compilation units are in each unnamed package is determined by the host system.
4. In implementations of the Java platform that use a hierarchical file system for storing packages, one typical strategy is to associate an unnamed package with each directory; only one unnamed package is observable at a time, namely the one that is associated with the "current working directory." The precise meaning of "current working directory" depends on the host system.
Classes
1. Newly declared fields can hide fields declared in a superclass or superinterface.
2. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.
3. A compile-time error occurs if a class has the same simple name as any of its enclosing classes or interfaces.
4. Enum types must not be declared abstract; doing so will result in a compile-time error.
5. It is a compile-time error for an enum type E to have an abstract method m as a member unless E has one or more enum constants, and all of E's enum constants have class bodies that provide concrete implementations of m.
6. It is a compile-time error for the class body of an enum constant to declare an abstract method.
7. Inner classes may not declare static initializers or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields.
8. Member interfaces (§8.5) are always implicitly static so they are never considered to be inner classes.
9. When an inner class refers to an instance variable that is a member of a lexically enclosing class, the variable of the corresponding lexically enclosing instance is used. A blank final (§4.12.4) field of a lexically enclosing class may not be assigned within an inner class.
10. It is a compile-time error if the evaluation of a variable initializer for a static field of a named class (or of an interface) can complete abruptly with a checked exception
11. The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
a. The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
b. The usage is not on the left hand side of an assignment.
c. The usage is via a simple name.
d. C is the innermost class or interface enclosing the usage.
Interfaces
1. It is a compile-time error to refer to a type parameter of an interface I anywhere in the declaration of a field or type member of I.
2. All interface members are implicitly public. They are accessible outside the package where the interface is declared if the interface is also declared public or protected,
3. If the interface declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superinterfaces of the interface.
4. It is a compile-time error for the body of an interface declaration to declare two fields with the same name.
5. A compile-time error occurs if an initialization expression for an interface field contains a reference by simple name to the same field or to another field whose declaration occurs textually later in the same interface.
6. If the keyword this or the keyword super occurs in an initialization expression for a field of an interface, then unless the occurrence is within the body of an anonymous class, a compile-time error occurs.
7. A method declared in an interface must not be declared strictfp or native or synchronized, or a compile-time error occurs, because those keywords describe implementation properties rather than interface properties.
8. It is a compile-time error if an annotation type T contains an element of type T, either directly or indirectly.
Arrays
1. Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion and become int values.
2. An attempt to access an array component with a long index value results in a compile-time error.
3. All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.
4. ArrayStoreException : An assignment to an element of an array whose type is A[], where A is a reference type, is checked at run-time to ensure that the value assigned can be assigned to the actual element type of the array, where the actual element type may be any reference type that is assignable to A.
Exceptions
1. If a try or catch block in a try-finally or try-catch-finally statement completes abruptly, then the finally clause is executed during propagation of the exception, even if no matching catch clause is ultimately found. If a finally clause is executed because of abrupt completion of a try block and the finally clause itself completes abruptly, then the reason for the abrupt completion of the try block is discarded and the new reason for abrupt completion is propagated from there.
1. Legal code point is U+0000 to U+10FFFF. Code points greater than U+FFFF are supplementary characters. Supplementary characters are stored as pairs of two 16-bit code units. (High Surrogate range: U+DB80 to U+DBFF and Low Surrogate Range : U+DC00 to U+DFFF).
2. Line Terminator is the ASCII character CR(“return”) followed by LF(“new line”).
3. Input Elements are : Whitespace(space, horizontal tab, form feed), comment(/* .. */ and //) and token(Identifiers, keyword, literal, separator and operator).
4. Comments do not nest.(/* and */ do not have special meaning inside // and // has no special meaning in comments that begin with /* or /**).
5. Identifier : Identifierchars but not a keyword or BooleanLiteral or NullLiteral).
6. Identifiers begin with JavaLetter(Character.isJavaIdentifierStart(int)) followed by JavaLetterOrDigit(Character.isJavaIdentifierPart(int)).
7. Literals : Integer(Decimal, octal and hexadecimal), Floating point(decimal or hexadecimal), Boolean(true & false), Character, String and Null literal.
8. This assignment String s1 = "\u000a"; will cause compiler error. Because \u000a is line feed character. Hence, within string literal to use line feed use “\n”
9. Literal Strings refer to the same string object. Strings computed by constant expressions are computed at compile time and then treated as if they are literals. String hello = "Hello", lo = "lo"; ((hello == ("Hel"+"lo")) is true.
10. Strings computed by concatenation at run time are newly created and therefore distinct. Thus, (hello == “Hel” + lo) will be false.
11. Escape sequence : b,t,n,f, r, “,’,\ and octal escape( \ followed by one to three octal digits).
Types, Values and Variables
1. Strongly Typed language: Every variable and every expression has a type that is known at compile time.
2. Integer operators throw NPE if unboxing conversion of a null reference is required. In divide and remainder operator, they throw Arithmetic exception, if right-hand operator is zero. OutofMemoryError in case of ++ and – if boxing conversion is required and there is not sufficient memory for conversion.
3. Floating Point : Positive zero and negative zero compare equal.
4. NaN is unordered, so the numerical comparison operators <, <=, >, >= return false if either or both the operands are NaN. Equality operator returns false if either operand is NaN. Inequality operator return true if either operand is NaN.
5. The language uses round toward zero when converting a floating value to an integer
6. An operation that overflows produces a signed infinity, an operation that underflows produces a denormalized value or a signed zero, and an operation that has no mathematically definite result produces NaN. All numeric operations with NaN as an operand produce NaN as a result.
7. Heap pollution : List l = new ArrayList
Conversions and Promotions
1. Five Conversion Contexts : Assignment Conversions, Method Invocation Conversions, Casting conversion, String conversion, Numeric conversion
2. 11 Conversion categories : Identity conversion, Widening primitive conversion, Narrowing Primitive Conversion, Widening and Narrowing primitive conversion, widening reference conversion, narrowing reference conversion, boxing conversion, Unboxing conversion, Unchecked conversion(raw type to generic type), capture conversion
3. Narrowing primitive conversion : short to char is also narrowing primitive conversion(cause char is unsigned while short is signed. So short to char loses precision).
4. Widening and Narrowing primitive conversion : byte to char. Here byte is first widened to int and then narrowed to char
5. Assignment Conversions allows the following: identity, widening primitive, widening reference, boxing, unboxing.
6. If the expression is a constant expression of type byte, short, char or int:
a. Narrowing primitive conversion if type of variable is byte, short or char and the value of constant expression is representable in the type of variable.
b. Narrowing primitive conversion followed by boxing conversion if type of variable is Byte, Short or Character and the value of constant expression is representable in byte, short or char respectively.
7. Implicit narrowing of integer constants is not available in Method invocation conversions. (Reason being it will add complexity to the overloaded method resolution process).
Names
1. Obscured declarations : a simple name may occur in contexts where it may potentially be interpreted as the name of variable, type or package. In this case, variable will be chosen in preference to a type, and that a type will be chosen in preference to a package.
2. Members of package : sub package, top level class types and top level interface types
3. Members of class type : classes, interface, fields and methods.
4. A class or interface may have two or more fields with the same simple name if they are declared in different interfaces and inherited. An attempt to refer to any of the fields by its simple name results in a compile-time error.
5. Members of array type : public final field length, public method clone and members inherited from Object(except method clone).
Packages
1. A package may not contain two members of the same name, or a compile-time error results.
2. package names mightg contain Unicode characters. If the host OS doesn’t support Unicode characters(\uxxxx) in their file system name, then the file name can be named by replacing the unicode characters as @xxxx. Java will map the Unicode character(\uxxxx) to the letters @xxxx in the file name.
3. An implementation of the Java platform must support at least one unnamed package; it may support more than one unnamed package but is not required to do so. Which compilation units are in each unnamed package is determined by the host system.
4. In implementations of the Java platform that use a hierarchical file system for storing packages, one typical strategy is to associate an unnamed package with each directory; only one unnamed package is observable at a time, namely the one that is associated with the "current working directory." The precise meaning of "current working directory" depends on the host system.
Classes
1. Newly declared fields can hide fields declared in a superclass or superinterface.
2. Newly declared methods can hide, implement, or override methods declared in a superclass or superinterface.
3. A compile-time error occurs if a class has the same simple name as any of its enclosing classes or interfaces.
4. Enum types must not be declared abstract; doing so will result in a compile-time error.
5. It is a compile-time error for an enum type E to have an abstract method m as a member unless E has one or more enum constants, and all of E's enum constants have class bodies that provide concrete implementations of m.
6. It is a compile-time error for the class body of an enum constant to declare an abstract method.
7. Inner classes may not declare static initializers or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields.
8. Member interfaces (§8.5) are always implicitly static so they are never considered to be inner classes.
9. When an inner class refers to an instance variable that is a member of a lexically enclosing class, the variable of the corresponding lexically enclosing instance is used. A blank final (§4.12.4) field of a lexically enclosing class may not be assigned within an inner class.
10. It is a compile-time error if the evaluation of a variable initializer for a static field of a named class (or of an interface) can complete abruptly with a checked exception
11. The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
a. The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
b. The usage is not on the left hand side of an assignment.
c. The usage is via a simple name.
d. C is the innermost class or interface enclosing the usage.
Interfaces
1. It is a compile-time error to refer to a type parameter of an interface I anywhere in the declaration of a field or type member of I.
2. All interface members are implicitly public. They are accessible outside the package where the interface is declared if the interface is also declared public or protected,
3. If the interface declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superinterfaces of the interface.
4. It is a compile-time error for the body of an interface declaration to declare two fields with the same name.
5. A compile-time error occurs if an initialization expression for an interface field contains a reference by simple name to the same field or to another field whose declaration occurs textually later in the same interface.
6. If the keyword this or the keyword super occurs in an initialization expression for a field of an interface, then unless the occurrence is within the body of an anonymous class, a compile-time error occurs.
7. A method declared in an interface must not be declared strictfp or native or synchronized, or a compile-time error occurs, because those keywords describe implementation properties rather than interface properties.
8. It is a compile-time error if an annotation type T contains an element of type T, either directly or indirectly.
Arrays
1. Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion and become int values.
2. An attempt to access an array component with a long index value results in a compile-time error.
3. All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown.
4. ArrayStoreException : An assignment to an element of an array whose type is A[], where A is a reference type, is checked at run-time to ensure that the value assigned can be assigned to the actual element type of the array, where the actual element type may be any reference type that is assignable to A.
Exceptions
1. If a try or catch block in a try-finally or try-catch-finally statement completes abruptly, then the finally clause is executed during propagation of the exception, even if no matching catch clause is ultimately found. If a finally clause is executed because of abrupt completion of a try block and the finally clause itself completes abruptly, then the reason for the abrupt completion of the try block is discarded and the new reason for abrupt completion is propagated from there.
Tuesday, June 13, 2006
Uninstalling Oracle 10g Manually from Windows XP
List of additional steps to do for cleaning the system completely after uninstall using universal installer.
# Stop any Oracle services that have been left running.
Start->Settings->Control Panel->Services
Look for any services with names starting with 'Oracle' and stop them.
# Run regedit and delete the following keys (some may have slightly different names in your registry):
HKEY_CURRENT_USER\SOFTWARE\ORACLE
HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\EventLog\Application\Oracle.oracle
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\OracleDBConsole
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\Oracle10g_home
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\OraclService
Note that the services control panel will still show the old services until you reboot.
# Delete the Oracle home directory
C:\Oracle
# Delete the Oracle Program Files directory:
C:\Program Files\Oracle
# Delete the Oracle Start Menu shortcuts directory:
C:\Documents and Settings\All Users\Start Menu\Programs\Oracle*
Where * indicates the name of your install. Look for and remove all Oracle directories from that location.
# Remove Oracle refereces from the path. To edit your path go to:
Start->Settings->Control Panel->System->Advanced->Environment Variables
Edit both of the environment variables user PATH and system PATH. Remove any Oracle references in them.
# Remove Oracle.DataAccess and any Polic.Oracle files from the GAC which is at:
C:\Windows\assembly\
# Stop any Oracle services that have been left running.
Start->Settings->Control Panel->Services
Look for any services with names starting with 'Oracle' and stop them.
# Run regedit and delete the following keys (some may have slightly different names in your registry):
HKEY_CURRENT_USER\SOFTWARE\ORACLE
HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\EventLog\Application\Oracle.oracle
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\OracleDBConsole
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\Oracle10g_home
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet Services\OraclService
Note that the services control panel will still show the old services until you reboot.
# Delete the Oracle home directory
C:\Oracle
# Delete the Oracle Program Files directory:
C:\Program Files\Oracle
# Delete the Oracle Start Menu shortcuts directory:
C:\Documents and Settings\All Users\Start Menu\Programs\Oracle*
Where * indicates the name of your install. Look for and remove all Oracle directories from that location.
# Remove Oracle refereces from the path. To edit your path go to:
Start->Settings->Control Panel->System->Advanced->Environment Variables
Edit both of the environment variables user PATH and system PATH. Remove any Oracle references in them.
# Remove Oracle.DataAccess and any Polic.Oracle files from the GAC which is at:
C:\Windows\assembly\
Monday, June 12, 2006
Extending Inner Class
Another good thread from javaranch.
At line 1, basically two objects are created.
First of class A, then of class B. So basically we have two instances here and instance of A act as a subobject which is actually wrapped within intstance of subclass. So, when extending the inner class, an instance of InheritInner must have an instance of Inner class and Inner class always require an instance of Outer class. So, to the constructor of InheritInner which extends Outer.Inner we must also pass the enclosing outer instance of inner class and call the super constructor of enclosing outer instance which will take care of instantiating the inner instance.
If the inner class was static(nested class), then calling o.super() is not required, since the inner class will be instantiated without an enclosing outer class instance.
class A{}
class B extends A{
public static void main(String args[]){
B b=new B(); // Line 1
}
}
At line 1, basically two objects are created.
First of class A, then of class B. So basically we have two instances here and instance of A act as a subobject which is actually wrapped within intstance of subclass. So, when extending the inner class, an instance of InheritInner must have an instance of Inner class and Inner class always require an instance of Outer class. So, to the constructor of InheritInner which extends Outer.Inner we must also pass the enclosing outer instance of inner class and call the super constructor of enclosing outer instance which will take care of instantiating the inner instance.
class Outer {class Inner {}}
public class InheritInner extends Outer.Inner {
InheritInner(Outer o) {
o.super();
}
public static void main (String[] args){
Outer o = new Outer();
InheritInner ii = new InheritInner(o);
}
}
If the inner class was static(nested class), then calling o.super() is not required, since the inner class will be instantiated without an enclosing outer class instance.
Sunday, June 11, 2006
Learnings from javaranch
1. Unreachable statement compile error is only for the loop statements(while) and not for conditional statement(if). while(false){..} will cause code not reachable error. But if(false){..} will not cause error. the conditions of course should be compile time constants.
2. "final variable in for loop". for(final int i:some iterable){print i..} will not error because the enhanced for loop is rewritten in basic for loop as for(int j=0; i < iterator.count;j++){final int i = iterator.next()...} so, the scope of variable is within one loop of the for. Instead within the for loop, if we tried to modify the final variable, it will error.
3. static variable and static fields are initialized in the order in which they are declared. so in the static block if we assign a variable which is declared down the line to another variable it will error. However this doesn't hold good for static methods. In the static methods, the variable which are declared down the line can be still be accessed and assigned to. Issue only for static initializers.
4. Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals. Strings computed by concatenation at run time are newly created and therefore distinct.
5. a private method in super class and same method name in child class. If some other method in parent class invoked by the child object calls the private method, it is the private method of the super class which is called and not the polymorphic method in child. polymorphic invocation doesn't apply if the super class method is private.
2. "final variable in for loop". for(final int i:some iterable){print i..} will not error because the enhanced for loop is rewritten in basic for loop as for(int j=0; i < iterator.count;j++){final int i = iterator.next()...} so, the scope of variable is within one loop of the for. Instead within the for loop, if we tried to modify the final variable, it will error.
3. static variable and static fields are initialized in the order in which they are declared. so in the static block if we assign a variable which is declared down the line to another variable it will error. However this doesn't hold good for static methods. In the static methods, the variable which are declared down the line can be still be accessed and assigned to. Issue only for static initializers.
4. Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals. Strings computed by concatenation at run time are newly created and therefore distinct.
5. a private method in super class and same method name in child class. If some other method in parent class invoked by the child object calls the private method, it is the private method of the super class which is called and not the polymorphic method in child. polymorphic invocation doesn't apply if the super class method is private.
Saturday, June 10, 2006
Java Thread : notify and notifyAll
Had this question : "notify results in a single thread acquiring a lock whereas notifyAll results in all the threads competing for the lock and one of them acquiring it so any way only one thread is able to acquire the lock, so why do we need notfyAll at all."
The answer lies in : Even though in the first case only one thread gets the lock, the problem occurs in that there may be no other threads to notify the other threads which called wait() earlier. So, if we call notifyAll, all the threads will be waken up and will be competing for the lock. So, to compete for the lock, first step is to get woken up by getting a notification from another thread that is going to release the lock.
Got the above content from this link
The answer lies in : Even though in the first case only one thread gets the lock, the problem occurs in that there may be no other threads to notify the other threads which called wait() earlier. So, if we call notifyAll, all the threads will be waken up and will be competing for the lock. So, to compete for the lock, first step is to get woken up by getting a notification from another thread that is going to release the lock.
Got the above content from this link
Saturday, June 03, 2006
Resulting type in conditional operator
If one expression is a primitive type and the other can be unboxed to become a compatible primitive type, then the unboxing occurs and the expressions are reconsidered.
If both expressions are numeric primitive types then the resulting type is also a numeric primitive type, obtained by numeric promotion if needed.
If one expression is an int constant, and the other is byte, short, or char, and the int value can fit in the smaller type, then the resulting type is that smaller type.
If one of the expressions is a primitive type and the other is a reference type that can't be unboxed to get a compatible value, or both expressions are primitive but incompatible, then the primitive type is boxed so that we have two reference types.
Given two reference types that are different, the type of the expression is the first common parent type. For example, if both expressions were unrelated class types that implemented Cloneable then Cloneable would be the type of the expression; if one expression was int while the other was String, then Object would be the resulting type.
If both expressions are numeric primitive types then the resulting type is also a numeric primitive type, obtained by numeric promotion if needed.
If one expression is an int constant, and the other is byte, short, or char, and the int value can fit in the smaller type, then the resulting type is that smaller type.
If one of the expressions is a primitive type and the other is a reference type that can't be unboxed to get a compatible value, or both expressions are primitive but incompatible, then the primitive type is boxed so that we have two reference types.
Given two reference types that are different, the type of the expression is the first common parent type. For example, if both expressions were unrelated class types that implemented Cloneable then Cloneable would be the type of the expression; if one expression was int while the other was String, then Object would be the resulting type.
Widen, boxing, varargs
widen and then boxing not allowed. But widen and then var-args allowed. This will
be the last priority match. Boxing and then widen will win over widen and then var-args.
be the last priority match. Boxing and then widen will win over widen and then var-args.
Implicit casting of primitives
Implicit casting of primitives happens only in assignment and not in method argument passing.
Short s = 7;(fine)
public void junk(short s){} and junk(7) will error. This is fine because in former case, we know the target type to which the casting is to be done. But in the latter case we don't know the target type to be casted to(in case there are multiple overloaded junk methods).
Short s = 7;(fine)
public void junk(short s){} and junk(7) will error. This is fine because in former case, we know the target type to which the casting is to be done. But in the latter case we don't know the target type to be casted to(in case there are multiple overloaded junk methods).
Widening Wins Boxing when alone: Causes confusion combined with Var-args
For the following methods:
public void test(long... l)
{
System.out.println("Widen varargs");
}
public void test(Integer... i)
{
System.out.println("Boxed and vararg'ed");
}
invocation of int i =5; test(i) will cause confusion to compiler. However if the methods are changed from varargs to normal parameters(long and Integer), then widening method will win over the Boxing parameter method. So, widening wins boxing when alone. But not when combined with var-args.
public void test(long... l)
{
System.out.println("Widen varargs");
}
public void test(Integer... i)
{
System.out.println("Boxed and vararg'ed");
}
invocation of int i =5; test(i) will cause confusion to compiler. However if the methods are changed from varargs to normal parameters(long and Integer), then widening method will win over the Boxing parameter method. So, widening wins boxing when alone. But not when combined with var-args.
Subscribe to:
Posts (Atom)