Sunday, December 21, 2014

Java static class

In this example, we will discuss about static classes in Java. First of all, let’s give a short explanation of the static modifier. For example, if a field or a method in a class has the static modifier in its declaration , then it is always associated with the class as a whole, rather than with any object of the class.

In the code below we have declared a class named Vehicle, a class field member named vehicleType and a method named getVehicleType(), both declared as static.

ONLY nested classes can be static

The main difference is that inner class requires instantiation of the outer class so as to be initialized and it is always associated with an instance of the enclosing class. On the other hand nested static class is not associated with any instance of the enclosing class. Nested static classes are declared with the static keyword, which means than can be accessed like any other static member of class, as we shown before.

http://stackoverflow.com/questions/7486012/static-classes-in-java

Why should I use the keyword “final” on a method parameter in Java?

Sometimes its nice to be explicit(for readability) that the variable doesn't change. Here's a simple example where using final can save some possible headaches

public void setTest(String test) {
    test = test;
}
if you forget the 'this' keyword on a setter the variable you want to set doesn't get set. However if you used the final keyword on the parameter then the bug would be caught at compile time.

http://stackoverflow.com/questions/500508/why-should-i-use-the-keyword-final-on-a-method-parameter-in-java

Difference Between String , StringBuilder and StringBuffer Classes

String

String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
String  once assigned can not be changed .

String  demo = " hello " ;
// The above object is stored in constant string pool and its value can not be modified.


demo="Bye" ;     //new "Bye" string is created in constant pool and referenced by the demo variable          
 // "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the  "hello"string

StringBuffer

StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap .  StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
String Buffer can be converted to the string by using
toString() method.

StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe.
StringBuilder is fast as it is not thread safe .


StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuilder


http://javahungry.blogspot.com/2013/06/difference-between-string-stringbuilder.html

Saturday, December 20, 2014

String pool

As the name suggests, String Pool is a pool of Strings stored in Java Heap Memory. We know that String is special class in java and we can create String object using new operator as well as providing values in double quotes. Here is a diagram which clearly explains how String Pool is maintained in java heap space and what happens when we use different ways to create Strings.


String Pool is possible only because String is immutable in Java and it’s implementation of String interning concept. String pool is also example of Flyweight design pattern.

Object, classes, reference

If you like housing metaphors:

a class is like the blueprint for a house. Using this blueprint, you can build as many houses as you like.
each house you build (or instantiate, in OO lingo) is an object, also known as an instance.
each house also has an address, of course. If you want to tell someone where the house is, you give them a card with the address written on it. That card is the object's reference.
If you want to visit the house, you look at the address written on the card. This is called dereferencing.
You can copy that reference as much as you like, but there's just one house -- you're just copying the card that has the address on it, not the house itself. Java methods are always pass-by-value, but the value could be an object's reference. So, if I have:

Foo myFoo = new Foo();     // 1
callBar(myFoo);            // 2
myFoo.doSomething()        // 4

void callBar(Foo foo) {
    foo = new Foo();       // 3
}
Then let's see what's happening.

Several things are happening in line 1. new Foo() tells the JVM to build a new house using the Foo blueprint. The JVM does so, and returns a reference to the house. You then copy this reference to myFoo. This is basically like asking a contractor to build you a house. He does, then tells you the house's address; you write this address down.
In line 2, you give this address to another method, callBar. Let's jump to that method next.
Here, we have a reference Foo foo. Java is pass-by-value, so the foo in callBar is a copy of the myFoo reference. Think of it like giving callBar its very own card with the house's address on it. What does callBar do with this card? It asks for a new house to be built, and then uses the card you gave it to write that new house's address. Note that callBar now can't get to the first house (the one we built in line 1), but that house is unchanged by the fact that a card that used to have its address on it, now has some other house's address on it.
Back in the first method, we dereference myFoo to call a method on it (doSomething()). This is like looking at the card, going to the house whose address is on the card, and then doing something in that house. Note that our card with myFoo's address is unchanged by the callBar method -- remember, we gave callBar a copy of our reference.
The whole sequence would be something like:

Ask JVM to build a house. It does, and gives us the address. We copy this address to a card named myFoo.
We invoke callBar. Before we do, we copy the address written on myfoo to a new card, which we give to callBar. It calls that card foo.
callBar asks the JVM for another house. It creates it, and returns the new house's address. callBar copies this address to the card we gave it.
Back in the first method, we look at our original, unchanged card; go to the house whose address is on our card; and do something there.

http://stackoverflow.com/questions/9224517/what-is-a-class-reference-and-an-object

Java is always pass-by-value

http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value

== vs equals(). with Strings

== tests for reference equality.

.equals() tests for value equality.

Consequently, if you actually want to test whether two strings have the same value you should use .equals() (except in a few situations where you can guarantee that two strings with the same value will be represented by the same object eg: String interning).

== is for testing whether two strings are the same object.

// These two have the same value
new String("test").equals("test") // --> true

// ... but they are not the same object, not the same instance because they have different refferences.
new String("test") == "test" // --> false

// ... neither are these
new String("test") == new String("test") // --> false

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object
"test" == "test" // --> true

// concatenation of string literals happens at compile time,
// also resulting in the same object
"test" == "te" + "st" // --> true

// but .substring() is invoked at runtime, generating distinct objects
"test" == "!test".substring(1) // --> false

// interned strings can also be recalled by calling .intern()
"test" == "!test".substring(1).intern() // --> true

-----
== tests object references, .equals() tests the string values.
Sometimes it looks as if == compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object.



Inmutable Objects in Java

final (detailed article) keyword is used in implementing immutable primitive types and object references,[3] but it itself cannot make other objects immutable. See below examples:

Primitive type variables (int, long, short, etc.) can be reassigned after being defined. We can prevent this using final.

int i = 42; //int is of primitive type
i = 43; // OK

final int j = 42;
j = 43; // does not compile. j is final so can't be reassigned

Reference types cannot be made immutable just by using the final keyword. final only prevents reassignment.

final MyObject m = new MyObject(); //m is of reference type
m.data = 100; // OK. We can change state of object m (m is mutable and final doesn't change this fact)
m = new MyObject(); // does not compile. m is final so can't be reassigned

Benefits

https://www.linkedin.com/pulse/20140528113353-16837833-6-benefits-of-programming-with-immutable-objects-in-java

Why String is immutable in Java?

A classic example of an immutable object is an instance of the Java String class.

    String s = "ABC";
    s.toLowerCase();

The method toLowerCase() will not change the data "ABC" that s contains. Instead, a new String object is instantiated and given the data "abc" during its construction. A reference to this String object is returned by the toLowerCase() method. To make the String s contain the data "abc", a different approach is needed.

     s = s.toLowerCase();

Now the String s references a new String object that contains "abc". There is nothing in the syntax of the declaration of the class String that enforces it as immutable; rather:

   ----> none of the String class's methods ever affect the data that a String object contains, thus making it INMUTABLE.

1) Imagine String pool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say


Read more: http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html#ixzz3MUEvTdDI

2. In case, if String is not immutable, this would lead serious security threat , I mean some one can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file.

Read more: http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html#ixzz3MUFPxTaH

3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java,

Read more: http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html#ixzz3MUFkRtwj

4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.

Read more: http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html#ixzz3MUFsc4AI

5) "The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter""

Read more: http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html#ixzz3MUKGdd2h

http://javarevisited.blogspot.sg/2012/07/when-class-loading-initialization-java-example.html


Also to be immutable you have to be final, so that your subclass doesn't break immutability

Read more: http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html#ixzz3MULmh42T

Friday, December 19, 2014

Java elements

0. Static means that can be access in an static way (that not need to instanced the class like new ExampleClass)
You can treat static as a global variable which has scope. It basically means if you change it for one object it will be changed for all just like a global variable(limited by scope).

1. public static final:
final indicates a variable who's value can't be modified after it is declared.

Use public final static String when you want to create a String that belongs to the class (no instance necessary to use it), and that won't change, for instance when you want to define a String constant that will be available to all instances of the class, and to other objects using the class, depending on the access modifier:

public final static String MY_CONSTANT = "SomeValue";

It isn't required to use final, but it keeps a constant from being changed inadvertently during program execution, and serves as an indicator that the variable is a constant.

Even if the constant will only be used - read - in the current class and/or in only one place, it's clearer to declare all constants as final, and still good practice, since during the lifetime of the code the constant may end up being used in more than one place.

Furthermore using final may allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.
http://stackoverflow.com/questions/11677670/when-exactly-are-we-supposed-to-use-public-static-final-string

2. The java.lang.Class.getSimpleName() returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous.
http://www.tutorialspoint.com/java/lang/class_getsimplename.htm


Java theory

It is also possible to look up the definition of a class given a string containing its name. This means that you can compute a data type name and have it easily dynamically-linked into the running system.

When you statically link a file into an executable, the contents of that file are included at link time. In other words, the contents of the file are physically inserted into the executable that you will run.

When you link dynamically, a pointer to the file being linked in (the file name of the file, for example) is included in the executable and the contents of said file are not included at link time. It's only when you later run the executable that these dynamically linked files are bought in and they're only bought into the in-memory copy of the executable, not the one on disk.

http://www.cafeaulait.org/slides/hope/16.html
http://stackoverflow.com/questions/311882/what-do-statically-linked-and-dynamically-linked-mean