Thursday, April 4, 2013

Calculate Haversine Distance in Java


The haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical triangle

The hav­er­sine formula is used to cal­cu­late the dis­tance between two points on the Earth’s surface spe­cified in lon­gitude and latitude. It is a special case of a more general formula in spherical trigonometry, the law of haversines, relating the sides and angles of spherical "triangles".




d is the dis­tance between two points with lon­gitude and lat­itude (ψ,φ) and r is the radius of the Earth.

public class HaversineDistance {

public static double haversineDistance(double lat1,double lat2,double lon1,double lon2) {
           double deltaLat = Math.toRadians(lat1 - lat2);
           double deltaLong = Math.toRadians(lon1 - lon2);
           double lat1R = Math.toRadians(lat1);
           double lat2R = Math.toRadians(lat2);
           double a = (Math.sin(deltaLat/2.0) * Math.sin(deltaLat/2.0)) +
                      (Math.sin(deltaLong/2.0) * Math.sin(deltaLong/2.0) *
                      Math.cos(lat1R) * Math.cos(lat2R));
           double c = 2.0*Math.atan2(Math.sqrt(a), Math.sqrt(1.0 - a));
           double d = 3959.0*c;
           return d;
         }

         public static void main(String[] args) {
           System.out.println(haversineDistance(21.7679,40.4230,78.8718,98.7372));
         }

}

Thinking In Java


1)       Main class (filename) cannot be private/protected/static.
2)       Main class has to be public/abstract/final.
3)       Method cannot be Abstract and final at the same time.
4)       Abstract class need not have a single abstract method.
5)       Methods cannot be overridden to be more private.
6)       Final method should not be overridden.
7)       Final object reference variable cannot be changed.
8)       Any number of null elements can be added to Vector/Linked List.
9)       A variable cannot be volatile and final at the same time.???
10)   Methods in an interface cannot be final as they need to be overridden by class implementing the interface. They are public by default.
11)   This’ keyword cannot be used with respect to static methods and variables.
12)   Static methods cannot be overridden to be non-static.
13)   Static variables and static initializer blocks are loaded before main.
14)   Top level classes and methods can never be private and abstract at the same time.
15)   Inner class variables cannot be ‘Static’ unless the class itself is declared as ‘Static’.
16)   Inner class can be a subclass of an outer class and can implement interfaces.
17)   Any component size changes from platform to platform.
18)   It is not necessary that if finalize() method is invoked the object will be garbage collected, also it is not absolutely necessary for it to perform clean-up operations
19)   String Buffer class does not override equals method of the Object class, hence it performs a shallow compare on Object references.
20)   Variables cannot be declared STATIC within any method. This is because lifetime and scope of local
21)   variables is restricted to that of the method in which they are declared whereas static variables are
22)   class variables and they are loaded when the class is loaded, and exist in memory till the class is unloaded.
23)   Anonymous classes cannot have any constructors.
24)   Garbage collector thread is the least priority thread, and it does “NOT” ensure that the program will not run out of memory.
25)   Variable Assignment is allowed during creation of an array. e.g. :
int I = 4;
       int a[] [] [] = new int [I] [I=3][I] ;
is perfectly legal. 
26)   Non – static methods can call static members of a class.
27)   Writer classes (PrintWriter , FileWriter etc.) are more oriented towards Unicode characters
28)   Finalize() method can be overloaded and made public
29)   Equals () method of Object class by default compares only references to objects.
30)   All method binding in Java uses late binding unless method unless the method is declared FINAL.
31)   An Interface can have a static inner class in its namespace
32)   Inner classes cannot be overridden like methods.
33)   In the derived class constructor one should only call private/final methods of base class.
34)   Comments cannot be nested in Java.
35)   Positive and negative zeroes are EQUAL.
36)   Floating-point operations never throw exceptions.
37)   All arrays in Java are objects. Each is associated with a class, which can be retrieved by getClass() method.
38)   An interface cannot have the same name as any of its enclosing class/interface.
Class Myclass {
interface Myclass // Compiler error
{ ….. }
}
39)   Methods in interfaces should NOT be declared static.
40)   Methods in an interface must NOT be declared native/strictfp/synchronized/final, but class
41)   implementing the interface can declare the method as native/synchronized/strictfp/final.
42)   Local variables cannot be referenced by ‘this’.
43)   Static inner class is also referred to as “Top-level nested class
44)   Static method CANNOT have a static inner class.
Public static method() {
static class Myclass //compile error
{
}
}
45)   Non-static inner class cannot have static variables unless they are declared FINAL.
46)   Map and Set cannot have duplicate elements.
47)   ToString () method is NEVER called on a NULL.
e.g. : Object o = null;
System.out.println(o);
will not throw NullPointerException.
48)   Division by 0 on float will NEVER throw ArithmeticException.
49)   Hashcode() method of Object class is Native method and can be overridden.
50)   Fields in an Interface can never be Transient.
51)   An instance of object class can be assigned to any valid class file.
E.g. : Object o = String.class is perfectly valid.
52)   Static block cannot make a forward reference to static variables defined after its definition.
53)   A.equals(B) will return true if and only if the 2 objects A and B are of the same class.
54)   Null literal does not have any type, hence it cannot be cast to any other type.
55)   Blank final variables have to be initialized. If they are class members, they can be initialized only in initializer blocks/constructors.
E.g.:
Class A
{
final int var;
{
var = 10;
} // Initializer block
}
56)   Initializer blocks are loaded only when object is created.
57)   Keywords like this/super CANNOT be used in initializer expressions of class Variables.
e.g. :
class A
{
int a = 10;
}
class B extends A
{
static int a = super.a; // COMPILE ERROR
}
58)   Abstract method CANNOT be synchronized.
59)   Method declaring a non-void return type in its header may not provide a return statement in its body
if it declares to throw an Exception.
e.g :
int method ()
{
throw new RuntimeException();
}
OR
Int method () throws Exception
{
throw new Exception();
}
are valid.
60)   Lock acquired on the object by a synchronized method is released if the method throws an Exception
61)   If an instance initializer block throws a checked Exception during its execution, which it does not catch, then the Exception must be declared in the throws clause of every constructor of the class.
e.g. :
class Test
{
{
if(true) throw new Exception();
}
Test () throws Exception
{ }
Test (int a) throws Exception
{ }
There can be no statement in a method body after a throw statement.
e.g. :
class NewClass
{
private void method () throws Exception
{
throw new Exception();
return; // COMPILE error Statement not reachable
}
}
62)   Constructors can have classes defined in their scope.
e.g. :
class Myclass
{
Myclass ()
{
class Constclass ()
{}
}
}
63)   Calling a private superclass constructor in the derived class is not allowed.
64)   A thread can be called daemon if and only if the creating thread is daemon.
65)   PrintStream class methods never throw IOException.
66)   Constructors can have empty return statements.
e.g. :
class A
{
A ()
{
return;
}
67)   Local class is implicitly STATIC if it is defined in static method/ static initializer.
e.g. :
private static void method ()
{
class Innclass
{}
}
is legal and Innclass is implicitly static.But it should NOT be explicitly prefixed with static keyword.
private static void method ()
{
static class Innclass //COMPILE ERROR
{}
}
68)   Static local class can only access ‘STATIC’ members of enclosing class
69)   An object is eligible for Garbage collection if the only references to the object are from other which are also eligible for GC.
70)   GridBagLayout honours preferred width of a component if Component fill is either NONE or VERTICAL.
71)   Null values cannot be added to a Hashtable.
72)   Thread object set to Null will not stop the thread from execution.
73)   If a method declares to throw a checked Exception, it must be caught by the catch block of the Exception or a superclass of the Exception. Peer class of Exception in the catch block does not satisfy the requirement and will flag a compiler error.
74)   In GridLayout constructor, both rows and columns cannot be simultaneously zero, else RuntimeException is thrown.
75)   GridLayout g = new GridLayout(0,0) will throw RuntimeException.
76)   Casting an NAN to an int or long will result in value zero.
77)   Following code will throw an ArraystoreException.
Point [] p = new Point [10];
P[0] = new Point ();
78)   Calling yield () in synchronized method or block does NOT relinquish the lock.???
79)   When argument to Math.abs method is of Integer.MIN_VALUE or Long.MIN_VALUE, the value remains the same.
80)   Accessing elements of an uninitialized array will cause NullPointerException to be thrown.
e.g. :
int a[] = new int[10];
System.out.println (a[0]); //NullPointerException.
81)   Final static variables can be initialized only in static initializer blocks or during assignment.
82)   Local variables are always thread-safe.
83)   Anonymous class is implicitly final.
84)   Abstract method in superclass cannot be accessed in the subclass using super.
e.g. :
abstract class A
{
abstract void method () ;
}
class B extends A
{
public void method()
{
super.method(); // COMPILER ERROR
}
}
85)   Local variables which are final CAN remain uninitialized.
Void method()
{
final int var;
}
is perfectly legal

The Style object : Apply CSS attributes from Javascript


The Style object represents an individual style statement.

Syntax for using the Style object properties: 
document.getElementById("id").style.property="value"

Background properties
Background Sets all background properties in one
backgroundAttachment Sets whether a background-image is fixed or scrolls with the page
backgroundColor Sets the background-color of an element
backgroundImage Sets the background-image of an element
backgroundPosition Sets the starting position of a background-image
backgroundPositionX Sets the x-coordinates of the backgroundPosition property
backgroundPositionY Sets the y-coordinates of the backgroundPosition property
backgroundRepeat Sets if/how a background-image will be repeated

Border and Margin properties
Border Sets all properties for the four borders in one
borderBottom Sets all properties for the bottom border in one
borderBottomColor Sets the color of the bottom border
borderBottomStyle Sets the style of the bottom border
borderBottomWidth Sets the width of the bottom border
borderColor Sets the color of all four borders (can have up to four colors)
borderLeft Sets all properties for the left border in one
borderLeftColor Sets the color of the left border
borderLeftStyle Sets the style of the left border
borderLeftWidth Sets the width of the left border
borderRight Sets all properties for the right border in one
borderRightColor Sets the color of the right border
borderRightStyle Sets the style of the right border
borderRightWidth Sets the width of the right border
borderStyle Sets the style of all four borders (can have up to four styles)
borderTop Sets all properties for the top border in one
borderTopColor Sets the color of the top border
borderTopStyle Sets the style of the top border
borderTopWidth Sets the width of the top border
borderWidth Sets the width of all four borders (can have up to four widths)
Margin Sets the margins of an element (can have up to four values)
marginBottom Sets the bottom margin of an element
marginLeft Sets the left margin of an element
marginRight Sets the right margin of an element
marginTop Sets the top margin of an element
Outline Sets all outline properties in one
outlineColor Sets the color of the outline around an element
outlineStyle Sets the style of the outline around an element
outlineWidth Sets the width of the outline around an element
Padding Sets the padding of an element (can have up to four values)
paddingBottom Sets the bottom padding of an element
paddingLeft Sets the left padding of an element
paddingRight Sets the right padding of an element
paddingTop Sets the top padding of an element

Layout properties
Clear Sets on which sides of an element other floating elements are not allowed
Clip Sets the shape of an element
Content Sets meta-information
counterIncrement Sets a list of counter names, followed by an integer. The integer indicates by how much the
counter is incremented for every occurrence of the element. The default is 1
counterReset Sets a list of counter names, followed by an integer. The integer gives the value that the
counter is set to on each occurrence of the element. The default is 0
cssFloat Sets where an image or a text will appear (float) in another element
Cursor Sets the type of cursor to be displayed
Direction Sets the text direction of an element
Display Sets how an element will be displayed
Height Sets the height of an element
markerOffset Sets the distance between the nearest border edges of a marker box and its principal box
Marks Sets whether cross marks or crop marks should be rendered just outside the page box edge
maxHeight Sets the maximum height of an element
maxWidth Sets the maximum width of an element
minHeight Sets the minimum height of an element
minWidth Sets the minimum width of an element
Overflow Specifies what to do with content that does not fit in an element box
verticalAlign Sets the vertical alignment of content in an element
Visibility Sets whether or not an element should be visible
Width Sets the width of an element

List properties
listStyle Sets all the properties for a list in one
listStyleImage Sets an image as the list-item market
listStylePosition Positions the list-item marker
listStyleType Sets the list-item marker type

Positioning properties
Bottom Sets how far the bottom edge of an element is above/below the bottom edge of the parent
Left Sets how far the left edge of an element is to the right/left of the left edge of the parent
Position Places an element in a static, relative, absolute or fixed position
Right Sets how far the right edge of an element is to the left/right of the right edge of the parent
Top Sets how far the top edge of an element is above/below the top edge of the parent element
Zindex Sets the stack order of an element

Printing properties
Orphans Sets the minimum number of lines for a paragraph that must be left at the bottom of a page
Page Sets a page type to use when displaying an element
pageBreakAfter Sets the page-breaking behavior after an element
pageBreakBefore Sets the page-breaking behavior before an element
pageBreakInside Sets the page-breaking behavior inside an element
Size Sets the orientation and size of a page
Widows Sets the minimum number of lines for a paragraph that must be left at the top of a page

Table properties
borderCollapse Sets whether the table border are collapsed into a single border or detached
borderSpacing Sets the distance that separates cell borders
captionSide Sets the position of the table caption
emptyCells Sets whether or not to show empty cells in a table
tableLayout Sets the algorithm used to display the table cells, rows, and columns

Text properties
Color Sets the color of the text
Font Sets all font properties in one
fontFamily Sets the font of an element
fontSize Sets the font-size of an element
fontSizeAdjust Sets/adjusts the size of a text
fontStretch Sets how to condense or stretch a font
fontStyle Sets the font-style of an element
fontVariant Displays text in a small-caps font
fontWeight Sets the boldness of the font
letterSpacing Sets the space between characters
lineHeight Sets the distance between lines
Quotes Sets which quotation marks to use in a text
textAlign Aligns the text
textDecoration Sets the decoration of a text
textIndent Indents the first line of text
textShadow Sets the shadow effect of a text
textTransform Sets capitalization effect on a text
whiteSpace Sets how to handle line-breaks and white-space in a text
wordSpacing Sets the space between words in a text

Textarea Object Properties
accessKey Sets or returns the keyboard key to access a textarea
Cols Sets or returns the width of a textarea
defaultValue Sets or returns the default text in a textarea
Disabled Sets or returns whether or not a textarea should be disabled
Form Returns a reference to the form that contains the textarea
Id Sets or returns the id of a textarea
Name Sets or returns the name of a textarea
readOnly Sets or returns whether or not a textarea should be read-only
Rows Sets or returns the height of a textarea
tabIndex Sets or returns the tab order for the textarea
Type Returns the type of the form element
Value Sets or returns the text in a textarea