Difference between “aString” and new String(“aString”)

This is another classic interview question – is a String declared –

[sourcecode language=”java”]String s1 = "aString";[/sourcecode]

The same as –

[sourcecode language=”java”]String s2 = new String("aString");[/sourcecode]

Lets test it –

[sourcecode language=”java”] String test1 = "test"; – String test2 = "test";
System.out.println(" \"test\" == \"test\" " + (test1 == test2)); // true
String test3 = new String("test");
System.out.println(" \"test\" == new String(\"test\") – " + test1 == test3); // false
System.out.println(" \"test\".equals( new String(\"test\") ) – " + test1.equals(test3)); // true
[/sourcecode]

The Output is –

[sourcecode language=”java”] "test" == "test" true – "test" == new String("test") – false
"test".equals( new String("test") ) – true
[/sourcecode]

The first comparison shows that test1 and test2 both share the same object String in the String Pool, the second comparison shows that although the String’s look the same – they do not point to the same memory location and exists on a different location of the String pool

Whats the point?

The next question is why/when would you use a String constructor. The most useful time is when using substring. A look at the substring source code, prior to Java 7, shows that it passes the original String’s character array. So if I have a 1GB long String, and am extracting the first letter I am still storing a copy of the original character array. Pretty innefficient, but Im pretty sure the current version of Java has done some work to fix this (need to check up).

If the following structure –

[sourcecode language=”java”] String extractedSubString = "extremely…long…string".substring( 0, 1 );
[/sourcecode]

Is changed to –

[sourcecode language=”java”] String extractedSubString = new String ( "extremely…long…string".substring( 0, 1 ) );
[/sourcecode]

This will create a String with a new character array the size of the substring.

Object Oriented Principles

I was interviewing some students for a placement, and asked the standard “What are the four principles of OO development?” question as a warm-up. I was surprised that they struggled to name all four principles off the top of their head. In their defence the courses they came from were not purely software driven, and also would have covered other programming styles like procedural.

Lets start – the four principles of OOP are –

  • Abstraction
  • Encapsulation
  • Polymorphism
  • Inheritance

Abstraction

Abstraction is about exposing just enough information or functions, while hiding the complexity. This can be seen in Java through the external methods (public methods) in classes and interfaces, for example –

[sourcecode language=”java”]

String encapsulationExample = "encapsulation".substring(0, 6);

[/sourcecode]

The developer only needs to know what the substring method does, and doesn’t need to understand how it does it. The implementation is “encapsulated”.

Encapsulation

This is the flipside of abstraction. With encapsulation we hide the implementation of the abstracted methods. This means the internal implementation of the external methods. An example of this is getter/setter methods to access private members of a class

Polymorphism

Polymorphism in coding terms can be summed up as “one method, many implementations”. A literal definition is “of many forms” (“many” – poly, “forms” – morph). It allows us to define specialisms of methods in subclasses through overloading and overriding

I could waste my time coming up with an example of polymorphism in practice, but the best example Ive found is from stackoverflow (http://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading/154939#154939).

[sourcecode language=”java”] public abstract class Human {

public abstract void goPee();

}
[/sourcecode] [sourcecode language=”java”] public class Male extends Human {

@Override
public void goPee() {
System.out.println("Stand Up");
}

}
[/sourcecode] [sourcecode language=”java”] public class Female extends Human {

@Override
public void goPee() {
System.out.println("Sit Down");
}

}

public static void main(String args) {

ArrayList<Human> group = new ArrayList<Human>();

group.add(new Male());
group.add(new Female());
// … add more…

// tell the class to take a pee break
for (Human person : group) {
person.goPee();
}

}
[/sourcecode]

Output –
Stand Up
Sit Down

Inheritance

Inheritance is the process where a classes behaviour is derived from an existing superclass. This allows the developer to have common code contained in the superclass, and specialisms in the subclasses. A subclass inherits in java using the extends keyword.

References

http://stackoverflow.com/questions/154577/polymorphism-vs-overriding-vs-overloading/154939#154939

What is immutability?

The freedictionary (http://www.thefreedictionary.com/immutability) defines immutable as – “Not subject or susceptible to change.”

In code terms this means we cannot alter an object once it has been created. You will mostly hear the term discussed in conjunction with java.lang.String

So what does an immutable class look like?

Consider this example –

[sourcecode language=”java”] public final class ImmutableObject {

private final String imVar;

public ImmutableObject(String imVar) {

this.imVar = imVar;

}

public String getImVar() {

return this.imVar;

}

}
[/sourcecode]

No setter method – You can only set imVar thru the constructor, and access it thru getImVar

This class also demonstrates some rules of thumb for creating immutable objects –

  • Class is final
  • Variables are final and private
  • No setter methods – variables populated thru constructor

Why would I use this?

  • Data cannot be changed – encapsulation means that other people cannot
  • Change your objects state Thread safety – since the variables cannot
  • Be changed once set then there are no issues with thread safety
  • Re-usability – you can cache objects and reuse them

Sounds good, anything else?

You can circumvent immutability in java using reflection – but if your aim is to make use of the advantages immutable objects give you then you should avoid this. There may be times when this is a genuine requirement, but if your intention is to be clever then the best way to demonstrate your prowess is to KISS (Keep it Simple, Stupid)

What is String immutability?

The most common example of immutability in java is the String class –

[sourcecode language=”language="java'”] String s1 = "sample text";

s1.substring(0,6);

System.out.println(s1); // s1 – "sample text"

String s2 = s1.substring(0, 6);

System.out.println(s2); // s1 – "sample text", s2 – "sample"

s1 = s2;

System.out.println(s1); // s1 – "sample", s2 – "sample"
[/sourcecode]

The example above shows the initial text “sample text” remains unchanged inspite of the operations on s1, and when we create a new object s2 a new String is created. We then assign s2 to s1, and note that s1 is now “sample”. This is because the value has not changed but the reference has

Why are Strings immutable in java?

  • String Pool – Java stores all Strings in a String pool of the Java
  • Heap. When a String is created the JVM will check the String pool to see if it exists, and if so it will link to that instance
[sourcecode language=”java”] String s1 = "test";

String s2 = "test"; // this will link to s1

System.out.println(s1 == s2); // true
[/sourcecode]

Immutability is key to this functionality –

  • Hashcode – The hashcode of a String is used in HashMaps, and
  • Immutability guarantees that it will always be the same
  • Security – It is common to see a database connection passed as a String. String pooling guarantees this cannot be changed
  • Concurrency – Immutable objects are threadsafe by design

References

http://programmers.stackexchange.com/questions/195099/why-is-string-immutable-in-java

http://java.dzone.com/articles/why-string-immutable-java

http://stackoverflow.com/questions/20945049/is-a-java-string-really-immutable

Are Strings truly immutable?

I was on stackoverflow recently and noticed this question asking if Strings are truly immutable. The user provides this example code –

[sourcecode language=”java”] String s1 = "Hello World";

String s2 = "Hello World";

String s3 = s1.substring(6);

System.out.println(s1); // Hello World

System.out.println(s2); // Hello World

System.out.println(s3); // World

Field field = String.class.getDeclaredField("value");

field.setAccessible(true);

char[] value = (char[])field.get(s1);

value[6] = ‘J’;

value[7] = ‘a’;

value[8] = ‘v’;

value[9] = ‘a’;

value[10] = ‘!’;

System.out.println(s1); // Hello Java!

System.out.println(s2); // Hello Java!

System.out.println(s3); // World
[/sourcecode]

On the surface of it looks like our clever user has found a flaw in the String classes immutability, as they have replaced ‘World’ with ‘Java!’. The substring s3 is unchanged, when you might expect it to output ‘Java!’

So, whats the story?

Well the answer is in 2 parts –

1. Immutability – The above example suggests that String objects are not immutable. This is sort of correct, but the true nature of the String objects immutablity is that the String object is only immutable on the public interface.

2. Reflection – Reflection can be used to “tinker around under the hood” of the String object. It is advisable not to do this under normal circumstances – in fact I cannot think of an instance where you would want to add code like the above into your codebase.

Coding To Interfaces

Coding to interfaces is common in Java, for example –

List<String> stringList = new ArrayList<String>();

Here the reference type List is the interface, and it uses the concrete class ArrayList(which implements the List interface) as its implementation.

So why do we do this?

Consider two classes –

class Bicycle {
   void pedal() {
    System.out.println("Bike - Woohoo - Im pedalling");
  }
}
class Car {
  void drive() {
    System.out.println("Car - Oh no - stuck in traffic");
  }
}

These are similar, and poorly designed as the calling class would look similar to –

class RoadTrafficSimulator {
   List<Bicycle> bicycleList = new ArrayList<Bicycle> ();
   List<Car> carList = new ArrayList<Car> ();
   public RoadTrafficSimulator() {
      bicycleList.add( new Bicycle() );
      carList .add( new Car () );
   }
   public void simulateRoad() {
      for ( Bicycle b : this.bicycleList ) {
         b.pedal();
     }
     for ( Car c : carList ) {
        c.drive();
     }
   }
   public static void main(String args[]) {
      RoadTrafficSimulator roadTrafficSimulator = new RoadTrafficSimulator();
      roadTrafficSimulator.simulateRoad();
   }
}

Output –

Bike – Woohoo – Im pedalling
Car – Oh no – stuck in traffic

If we consider both the Bike and Car as having a shared function to move, we can create an interface, IVehicle, to define this contract –

interface IVehicle {
   void move();
}
class Bicycle implements IVehicle {
   public void move() {
      pedal();
   }
   void pedal() {
      System.out.println("Bike - Woohoo - Im pedalling");
   }
}
class Car implements IVehicle {
   public void move() {
      drive();
   }
   void drive() {
      System.out.println("Car - Oh no - stuck in traffic");
   }
}

The calling class could then be written as –

class RoadTrafficSimulator {
   List<IVehicle> iVehicleList = new ArrayList<IVehicle>();
   public RoadTrafficSimulator() {
      iVehicleList.add(new Bicycle());
      iVehicleList.add(new Car());
   }
   public void simulateRoad() {
      for (IVehicle b : this.iVehicleList) {
         b.move();
      }
   }
   public static void main(String args[]) {
      RoadTrafficSimulator roadTrafficSimulator = new RoadTrafficSimulator();
         roadTrafficSimulator.simulateRoad();
      }
   }
}

This means the iVehicleList only requires the objects it stores to implement the IVehicle interface contract, and is now more flexible. The code is also more loosely coupled as we only require implementations of IVehicle, instead of individual lists for each object type

Why not use a class?

This example is good for demonstrating why you would chose to use an interface rather than a class for IVehicle. Its clear that both the bicycle and car do move, but the nature of their movement is different(the bicycle is pedalled, and the car is driven). Other than that there is little in common – so an interface is the better choice. It would also allow us to extend the Bicycle and Car classes to further specialisms (eg ElectricCar) which could still populate Ivehicle provided they implement the move() contract

Conclusion

To summarize, the advantages of coding to interfaces are –

  • Software easier to extend
  • Only concerned with API and not implementation
  • Loosely coupled

The RoadTrafficSimulator now uses a single iVehicleList to store all objects implementing IVehicle. This has made the code more flexible, because as long as the objects conform to the IVehicle contract we can call the associated move() method.

Interfaces vs Abstract Classes

Why write another article on the differences between java interfaces and abstract classes? Well I’m getting used to using WordPress so thought it was a good place to start.

The key differences are –

abstract class – IS-A

  • IS-A relationship
  • Cannot be instantiated
  • Uses abstract keyword
  • Abstract methods must use abstract keyword
  • Used when you want the programmer to complete the implementation
  • Faster in JVM does not have to lookup

interface – CAN-DO

  • CAN-DO relationship
  • Cannot be instantiated
  • No implementation
  • Polymorphism
  • public abstract by default
  • public static final by default
  • Provides a contract/rules – idea of what needs to be done, not how
  • Slower in JVM as extra indirection looking up implementation

When to use an interface and abstract class?

The advantage of an interface is that you have a contract which any class can conform to, including existing classes. The advantage of an abstract class is that you can implement and encapsulate some core logic for your application, leaving the developer to code there own implementation

You may also want to use both, for example java.util.List is the interface, and java.util.AbstractList contains a core. You can also see this approach used in frameworks

Reference
http://mindprod.com/jgloss/interfacevsabstract.html

1 10 11 12