Stateless vs Stateful and Mutable vs Immutable

Stateless means there is no memory of the past. Every transaction is performed as if it were being done for the very first time.

Stateful means that there is memory of the past. Previous transactions are remembered and may affect the current transaction.

       //The state is derived by what is passed into the function
        function int addOne(int number)
          return number + 1;

        //The state is maintained by the function
        private int _number = 0; //initially zero
        function int addOne()
         return _number++;


Mutable Objects: When you have a reference to an instance of an object, the contents of that instance can be altered.

Immutable Objects: When you have a reference to an instance of an object, the contents of that instance cannot be altered.

        Point myPoint = new Point( 0, 0 );//mutable
	System.out.println( myPoint );//print out 0, 0
	myPoint.setLocation( 1.0, 0.0 );
	System.out.println( myPoint ); //print out 1.0, 0.0

	String myString = new String( "old String" );//immutable
	System.out.println( myString );//print out old String
	myString.replaceAll( "old", "new" );
	System.out.println( myString );//print out old String



Exception: Checked vs Unchecked

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

Unchecked Exception: exception in runtime or error can’t be recovered in runtime, like dividing by zero.

Checked Exception: exception can be handled by code try catch statement, like invalid input.

Because the Java programming language does not require methods to catch or to specify unchecked exceptions (RuntimeException, Error, and their subclasses), programmers may be tempted to write code that throws only unchecked exceptions or to make all their exception subclasses inherit from RuntimeException. Both of these shortcuts allow programmers to write code without bothering with compiler errors and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for others using your classes.

Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any Exception that can be thrown by a method is part of the method’s public programming interface. Those who call a method must know about the exceptions that a method can throw so that they can decide what to do about them. These exceptions are as much a part of that method’s programming interface as its parameters and return value.

The next question might be: “If it’s so good to document a method’s API, including the exceptions it can throw, why not specify runtime exceptions too?” Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program’s clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

One case where it is common practice to throw a RuntimeException is when the user calls a method incorrectly. For example, a method can check if one of its arguments is incorrectly null. If an argument is null, the method might throw a NullPointerException, which is an unchecked exception.

Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don’t want to be bothered with specifying the exceptions your methods can throw.

Here’s the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.




OOP Concepts

An object is a software bundle of related state (attributes) and behavior (methods). Software objects are often used to model the real-world objects that you find in everyday life.

Object-Oriented Programming is just a programming paradigm based on this concept of ‘”everything is object”. A class is a blueprint or prototype from which objects are created. A class models the state and behavior of a real-world object.

In definition of a class, we can decide which attributes or methods are only locally used, i.e. private, which can be exposed to others, i.e. public. This is called data encapsulation. It allows data hiding and protection of coding corruption.

For example, a car can be described as a specific implementation of a more general ‘class’ of a thing, called a vehicle. We model this relationship in software with classes by defining a Vehicle class and a Car class. In class Vehicle, we have speed, carry of people, etc.which would be all the behaviors common to most of different types of vehicles, e.g. planes, trains, etc.. It might not make sense in our software to redefine the basic essence of speed over and over again for each different type of vehicle. Instead, we define it once in Vehicle, and then when we define Car (child class), we simply indicates that it inherits (extends) the base definition from Vehicle (parent class). Car is said to specialize the general Vehicle definition. This is how inheritance works in class definition.

Another key concept is polymorphism, which describes the idea that a general behavior from a parent class can be overridden in a child class to give it more specifics. Say we define a method StartEngine() in Vehicle, the same named method should be implemented differently in Car and Plane, since each starts engine differently.



2. wikipedia: oop



Method Parameter Passing: by Value vs by Reference

Pass by value: The local parameters are copies of the original arguments passed in. Changes made in the function to these variables do not affect originals. 

Pass by reference: The local parameters are references to the storage locations of the original arguments passed in. Changes to these variables in the function will affect the originals. No copy is made, so overhead of copying (time, storage) is saved.

The Java Spec says that everything in java is pass-by-value. There is no such thing as “pass-by-reference” in java.

The key to understanding this is that something like

Dog myDog;

is not a Dog; it’s actually a pointer to a Dog.

What that means, is when you have

Dog myDog = new Dog("Rover");

you’re essentially passing the address of the created Dog object to the foo method.

(I say essentially because Java pointers aren’t direct addresses, but it’s easiest to think of them that way)

Suppose the Dog object resides at memory address 42. This means we pass 42 to the method.

if the Method were defined as

public void foo(Dog someDog) {
    someDog.setName("Max");     // AAA
    someDog = new Dog("Fifi");  // BBB
    someDog.setName("Rowlf");   // CCC

let’s look at what’s happening.

  • the parameter someDog is set to the value 42
  • at line “AAA”
    • someDog is followed to the Dog it points to (the Dog object at address 42)
    • that Dog (the one at address 42) is asked to change his name to Max
  • at line “BBB”
    • a new Dog is created. Let’s say he’s at address 74
    • we assign the parameter someDog to 74
  • at line “CCC”
    • someDog is followed to the Dog it points to (the Dog object at address 74)
    • that Dog (the one at address 74) is asked to change his name to Rowlf
  • then, we return

Now let’s think about what happens outside the method:

Did myDog change?

There’s the key.

Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it’s still pointing to the original Dog (but note that because of line “AAA”, its name is now “Max” – still the same Dog; myDog‘s value has not changed.)

It’s perfectly valid to follow an address and change what’s at the end of it; that does not change the variable, however,

Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, you cannot change where that pointer points.

In C++, Ada, Pascal and other languages that support pass-by-reference, you can actually change the variable that was passed.

If Java had pass-by-reference semantics, the foo method we defined above would have changed where myDog was pointing when it assigned someDog on line BBB.

Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in.

Copy Rights @

Keywords static and final in Java

static means the variable/method belongs to the class not an instance, so there is only one copy of this data shared between instances.
final is a method to define the variable/method having only one initialization, either in initializing or within a constructor.
A note on final methods and final classes, this is a way of explicitly stating that the method or class can not be overridden / extended respectively.

static variable:
1. A variable which belongs to the class and not to object (instance).
2. It is initialized only once at the start of the execution, before the initialization of any instance variables.
3. Syntax: Class.variable (no need to new an object)

static method:
1. It belongs to the class and not the object (instance)
2. A static method can access only static data unless it uses an instance of some class to indirectly access the instance variable.
3. A static method can call only other static methods  unless it uses an instance of some class to indirectly access the instance method.
4. Syntax: Class.methodName() (no refer to this or super keywords)

static class:
There is a static nested class in java. When you declare a nested class static, it automatically becomes a stand alone class which can be instantiated without having to instantiate the outer class it belongs to.

public class A
 public static class B

Because class B is declared static you can explicitly instantiate as:

B b = new B();

Note if class B wasn’t declared static to make it stand alone, an instance object call would’ve looked like this:

A a= new A();
B b = B();

static block codes:
It’s a static initializer. It’s executed when the class is loaded (or initialized).

static {
        private static Name = "blog";

final keyword
A final class cannot be subclassed.  All methods in a final class are implicitly final. This is done for security and efficiency reasons.

A final method can’t be overridden by subclasses. This is  used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.

A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a blank final variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error will occur.

public class Shirt {
static final String color = "Black";
public class Test {

public static void main(String args[]) {
    System.out.println(Shirt.color); //should provide output as "Black"
            Shirt.color = "white"; //Error because the value of color is fixed.  
    System.out.println(Shirt.color); //Code won't execute.

final static String a = “test” or static final String a = “test” ? 
They are the same as order in keyword doesn’t affect the functionality.