Friday, 27 May 2016

Access Modifiers In Java

Access modifiers specifies who can access them. There are four access modifiers used in java. They are public, private, protected, no modifer (declaring without an access modifer). Using ‘no modifier’ is also sometimes referred as ‘package-private’ or ‘default’ or ‘friendly’ access. Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers.

I) Class level access modifiers (java classes only)

Only two access modifiers is allowed, public and no modifier
  • If a class is ‘public’, then it CAN be accessed from ANYWHERE.
  • If a class has ‘no modifer’, then it CAN ONLY be accessed from ‘same package’.

II) Member level access modifiers (java variables and java methods)

All the four public, private, protected and no modifer is allowed.
  • public and no modifier – the same way as used in class level.
  • private – members CAN ONLY access.
  • protected – CAN be accessed from ‘same package’ and a subclass existing in any package can access.
For better understanding, member level access is formulated as a table:

Access Modifiers

Same Class Same Package Subclass Other packages
public Y Y Y Y
protected Y Y Y N
no access modifier Y Y N N
private Y N N N
First row {public Y Y Y Y} should be interpreted as:
  • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same class’.
  • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same package’.
  • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘subclass’.
  • Y – A member declared as ‘public’ CAN be accessed from ‘Other packages’.

Second row {protected Y Y Y N} should be interpreted as:
  • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same class’.
  • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same package’.
  • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘subclass’.
  • N – A member declared with ‘protected’ access modifier CANNOT be accessed by the members of the ‘Other package’.
similarly interpret the access modifiers table for the third (no access modifier) and fourth (private access modifier) records.

SOURCE

Java Pass By Value and Pass By Reference

Java uses pass by value. There is no pass by reference in Java. This Java tutorial is to walk you through the difference between pass by value and pass by reference, then explore on how Java uses pass by value with examples. Most importantly we need to be clear on what we mean by using the terminology “pass by value” and “pass by reference”. Some people are saying that in Java primitives are passed by value and objects are passed by reference. It is not correct.

Pass by Value

Let us understand what is pass by value. Actual parameter expressions that are passed to a method are evaluated and a value is derived. Then this value is stored in a location and then it becomes the formal parameter to the invoked method. This mechanism is called pass by value and Java uses it.

Pass by Reference

In pass by reference, the formal parameter is just an alias to the actual parameter. It refers to the actual argument. Any changes done to the formal argument will reflect in actual argument and vice versa.

Java Language Specification Says

In Java Language Specification 8.4.1. Formal Parameters section it is stated that,
“When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor.”
It is clearly evident that the actual argument expressions are evaluated and values given to the method body as formal parameters. When an object is passed as argument, that object itself is not passed as argument to the invoked method. Internally that object’s reference is passed as value and it becomes the formal parameter in the method.
Java uses JVM Stack memory to create the new objects that are formal parameters. This newly created objects scope is within the boundary of the method execution. Once the method execution is complete, this memory can be reclaimed.

Test Pass by Value vs Pass by Reference

We can run a simple swap test and check for pass by value vs pass by reference. Let us pass two arguments and swap them inside the invoked method, then check if the actual arguments are swapped. If the actual arguments are affected then the mechanism used is pass by reference otherwise it is pass by value.
public class Swap {

 public static void main(String args[]) {
  Animal a1 = new Animal("Lion");
  Animal a2 = new Animal("Crocodile");

  System.out.println("Before Swap:- a1:" + a1 + "; a2:" + a2);
  swap(a1, a2);
  System.out.println("After Swap:- a1:" + a1 + "; a2:" + a2);
 }

 public static void swap(Animal animal1, Animal animal2) {
  Animal temp = new Animal("");
  temp = animal1;
  animal1 = animal2;
  animal2 = temp;
 }

}

class Animal {
 String name;

 public Animal(String name) {
  this.name = name;
 }

 public String toString() {
  return name;
 }
}

Example Output:

Before Swap:- a1:Lion; a2:Crocodile
After Swap:- a1:Lion; a2:Crocodile
Objects are not swapped because Java uses pass by value.

Swap in C++:

Same code will swap the objects in C++ since it uses pass by reference.
void swap(Type& arg1, Type& arg2) {
    Type temp = arg1;
    arg1 = arg2;
    arg2 = temp;
}

Does Java Passes the Reference?

Everything is simple and then why is this topic so hot? Now let us look at the following code where we able to change the property of a passed argument object inside a method and it gets reflected in the actual argument.
public class Swap {

 public static void main(String args[]) {
  Animal a = new Animal("Lion");

  System.out.println("Before Modify: " + a);
  modify(a);
  System.out.println("After Modify: " + a);
 }

 public static void modify(Animal animal) {
  animal.setName("Tiger");
 }

}

class Animal {
 String name;

 public Animal(String name) {
  this.name = name;
 }

 public String toString() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}

Example Output:

Before Modify: Lion
After Modify: Tiger
If the arguments are passed by value then how we are able to change an attribute of the passed argument? This is because Java passes the object reference ‘by value’. When an object is passed as argument to a method, actually the reference to that object is passed. The formal parameter is a mapping of the reference to the actual parameter.

Java Passes Reference by Value

Following figures explains method scope for variables with respect to call by value. Consider the numbers 100, 200, 600 and 700 as pointers to memory location, these are logical only and for your understanding.
call-by-value-calling-method
In figure 1, there are two objects with variable name a1, a2 which references the location 100 and 200 respectively.
call-by-value-called-method-scope
In figure 2, there are two objects named formal-arg1, formal-arg2 which references location 600 and 700 respectively. Here is the catch, contents of the location 600, 700 are again references to another location 100 and 200. So the called method has got the reference of the passed arguments. Using the reference it can manipulate only the contents of the actual argument object. But it cannot change the fact that a1 points to 100 and a2 points to 200, that’s what we are trying to do when we swap the objects.
Important point to note is that “the reference is copied as a value” to a new variable and it is given as formal parameter to the called method. It does not get a1 variable which is the actual argument in scope. This is the key difference between pass by value and pass by reference.

SOURCE

Java Variable

Java variables can be categorized into the following seven types:
  1. Class Variable
  2. Instance Variable
  3. Array Component Variable
  4. Method Parameter Variable
  5. Constructor Parameter Variable
  6. Exception Handler Parameter Variable
  7. Local Variable
1) Class Variable
A java class variable is a field declared using the keyword static within a java class, or with or without the keyword static within a java interface declaration.
2) Instance Variable
Java variables that are declared without static keyword are instance variables.
3) Array Component
Array components are unnamed java variables that are created and initialized to default values whenever a new java array object is created.
4) Method Parameter
Java variables declared in the method declaration signature are method parameter variables. Whenever a java method is invoked a variable is created in the same name as it is declared.
5) Constructor Parameter
This is similar to the java method parameter variable. The same way, for all the java variables declared in the constructor a variable is created whenever it is invoked.
6) Exception Handler Parameter
Java variables that are declared in the catch clause of a java exception handling mechanism. Whenever a java exception is caught, exception handler parameter variable is created.
7) Local Variable
Java variables that are declared in a block inside a java method or for loop is called a java local variable.
Reference: Java Language Specification 4.12.3

SOURCE

Java Primitive

As of the Java Virtual Machine Specification second edition, numeric types, the boolean type (§3.3.4), and the returnAddress type are the three java primitive types supported by JVM.
Most of you may get annoyed, we all know about the primitives of java. That is where from we all started it. But, you may not be aware of a primitive called returnAddress. Surprise isn’t it? This post serves just to bring that primitive to your notice. It is not part of the language construct / api and is not of direct use to an application programmer. But it is good to be aware of the primitive for the sake of completeness.

1) Numeric Types

Numeric types are classified as integral primitive and floating point type primitives
Integral type primitive:
byte –  8-bit signed two’s complement integers: -128 to 127 (-2power7 to 2power7 – 1)
short – 16-bit signed two’s complement integers: -32768 to 32767 (-2power15 to 2power15 – 1)
int – 32-bit signed two’s complement integers
long – 64-bit signed two’s complement integers
char – 16-bit unsigned integers representing Unicode characters (§2.1)
Value ranges from -2power(N-1) to 2power(N-1) – 1 ; where N is the bit size like 8 or 16,…
In the above, two’s complement means, a negative number will be denoted by the two’s complent of its absolute value. Most significat digit (MSB) will denote if the number is positive or negative. MSB will be 0 if the number is positive and 1 if it is negative.


Floating-point primitives are float and double
  • positive and negative sign-magnitude numbers
  • positive and negative zeros
  • positive and negative infinities
  • a special Not-a-Number value (used to represent zero/zero kind of numbers).

2) boolean type primitive

encode the truth values true and false. Even booleans are in turn processed using int instructions.

3) returnAddress type primitive

returnAddress types are pointers to the opcodes of JVM instructions like jsr, ret, and jsr_w

SOURCE

Java Array

Array is used to store same ‘type’ of data that can be logically grouped together. Array is a fundamental construct in any programming languages. This Java tutorial is planned to provide comprehensive information about Java arrays.

Array is one among the many beautiful things in a programming language. Easy to iterate, easy to store and retrieve using their index. In Java, a beginner starts with public static void main(String args[]). The argument for the main method is an array. We encounter arrays early on.

Java Arrays

In java arrays are objects. All methods of an Object can be invoked on an array. Arrays are stored in heap memory.

Logical view of an Array

java array logical view
Though we view the array as cells of values, internally they are cells of variables. A java array is a group of variables referenced by a common name. Those variables are just references to a address and will not have a name. These are called the ‘components’ of a java array. All the components must be of same type and that is called as ‘component type’ of that java array.

Physical view of an Array

java array - physical view

Array Declaration

int []marks;
or
int marks[];

Array Instantiation

marks = new int[5];
5 inside the square bracket says that you are going to store five values and is the size of the array ‘n’. When you refer the array values, the index starts from 0 ‘zero’ to ‘n-1’. An array index is always a whole number and it can be a int, short, byte, or char.
Once an array is instantiated, it size cannot be changed. Its size can be accessed by using the length field like .length Its a java final instance field.
All java arrays implements Cloneable and Serializable.

Java array initialization and instantiation together

int marks[] = {98, 95, 91, 93, 97};

ArrayIndexOutOfBoundsException

One popular exception for java beginners is ArrayIndexOutOfBoundsException. You get ArrayIndexOutOfBoundsException when you access an array with an illegal index, that is with a negative number or with a number greater than or equal to its size. This stands second next to NullPointerException in java for popularity.

Java Array Default Values

After you instantiate an array, default values are automatically assigned to it in the following manner.
  • byte – default value is zero
  • short – default value is zero
  • int – default value is zero
  • long – default value is zero, 0L.
  • float – default value is zero, 0.0f.
  • double – default value is zero, 0.0d.
  • char – default value is null, ‘\u0000’.
  • boolean – default value is false.
  • reference types – default value is null.
Notice in the above list, the primitives and reference types are treated differently. One popular cause of NullPointerException is accessing a null from a java array.

Iterating a Java Array

public class IterateJavaArray {
 public static void main(String args[]) {
  int marks[] = {98, 95, 91, 93, 97};
  //java array iteration using enhanced for loop
  for (int value : marks){
   System.out.println(value);
  }
 }
}
In language C, array of characters is a String but this is not the case in java arrays. But the same behaviour is implemented as a StringBuffer wherein the contents are mutable.
ArrayStoreException – When you try to store a non-compatible value in a java array you get a ArrayStoreException.

Multidimensional Arrays

When a component type itself is a array type, then it is a multidimensional array. Though you can have multiple dimension nested to n level, the final dimension should be a basic type of primitive or an Object.
int[] marks, fruits, matrix[];
In the above code, matrix is a multidimensional array. You have to be careful in this type of java array declaration.
Internally multidimensional java arrays are treated as arrays of arrays. Rows and columns in multidimensional java array are completely logical and depends on the way you interpret it.
Note: A clone of a java multidimensional array will result in a shallow copy.

Iterate a java multidimensional array

Following example source code illustrates on how to assign values and iterate a multidimensional java array.
public class IterateMultiDimensionalJavaArray {
 public static void main(String args[]) {

  int sudoku[][] = { { 2, 1, 3 }, { 1, 3, 2 }, { 3, 2, 1 } };

  for (int row = 0; row < sudoku.length; row++) {
   for (int col = 0; col < sudoku[row].length; col++) {
    int value = sudoku[row][col];
    System.out.print(value);
   }
   System.out.println();
  }
 }
}

Sort a Java array

java api Arrays contains static methods for sorting. It is a best practice to use them always to sort an array.
import java.util.Arrays;

public class ArraySort {
 public static void main(String args[]) {
  int marks[] = { 98, 95, 91, 93, 97 };
  System.out.println("Before sorting: " + Arrays.toString(marks));
  Arrays.sort(marks);
  System.out.println("After sorting: " + Arrays.toString(marks));
 }
}
//Before sorting: [98, 95, 91, 93, 97]
//After sorting: [91, 93, 95, 97, 98]

Copy a Java array

You can use the following options to copy a java array:
  • As illustrated above you can use the util calls Arrays. It contains copyOf method for different java types.
  • The most used class by a java beginner 'System' has a static method to copy an array.
  • Using its clone method you can copy a java array. If the java array is multidimensional, it will be a shallow copy.
  • Write your own for loop iterating through the java array and copy elements yourself. (least preferred)
SOURCE

System.out.println

This Java tutorial is to explain what System.out.println is and how it works. It is love at first type. How many times have we used System.out.println till now? It is one of the most number of times compiled statement in the history of java. We shortly call it SOP.
Along with Java’s System.out.println(), at the end of this tutorial I have given a list of popular languages and their equivalent of it.
System-out-println-block-diagram

What is System.out.println

System.out.println is a Java statement that prints the argument passed, into the System.out which is generally stdout.
  • System – is a final class in java.lang package. As per javadoc, “…Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array
  • out – is a static member field of System class and is of type PrintStream. Its access specifiers are public final. This gets instantiated during startup and gets mapped with standard output console of the host. This stream is open by itself immediately after its instantiation and ready to accept data.
  • println – is a method of PrintStream class. println prints the argument passed to the standard console and a newline. There are multiple println methods with different arguments (overloading). Every println makes a call to print method and adds a newline. print calls write() and the story goes on like that.

Structure of System.out.println

Following is the skeletal structure of System.out.println in the JDK source. Through this code snippet the essential parts are highlighted and its given for better understanding.
System-out-println-class-diagram
public final class System {
    static PrintStream out;
    static PrintStream err;
    static InputStream in;
    ...
}

public class PrintStream extends FilterOutputStream {
    //out object is inherited from FilterOutputStream class
    public void println() {
    ...
}

Change out of System.out.println

‘out’ object can be customized. out gets initialized by java runtime environment at startup and it can be changed by developer during execution. Instead of standard output, in default cases when you run a program through command line, the output is printed in the same command window. We can change that behavior using setOut method as below. In the following example, I have redirected the output to a text file in the same directory.
public class ChangeOut {
 public static void main(String args[]) {
  try {
   System.setOut(new PrintStream(new FileOutputStream("log.txt")));
   System.out.println("Now the output is redirected!");
  } catch(Exception e) {}
 }
}

System.out.println vs loggers like Log4j

Log4J has mulitple levels for logging. If we are writing a real short program, just for experimental/learning purposes SOPs are fine. When we are developing a production quality software, we should be aware that a logging component should be used and System.out.println should be avoided. Why?
  • Flexibility: a logger like log4j provides different levels for logging. We can separate the log messages accordingly. For example, X messages should be printed only on PRODUCTION, Y messages should be printed on ERROR, etc.
  • Reconfigurability: in just one parameter change we can switch off all the logging statements.
  • Maintainability: imagine if we have hundreds of System.out.println littered all through the application, it would be difficult to maintain the program over a period.
  • Granularity: In an application, every single class can have a different logger and controlled accordingly.
  • Utility: Option for redirecting the message is limited in System.out, but in case of a logger you have appenders which provides numerous options. We can even create a custom output option and redirect it to that.
Having said all the above, we still use System.out.println for logging and debugging. Which should be strictly avoided. This is driven by (bad)habit.
I want to share how a habit became a convention. Its using ‘i’, ‘j’ as index in for-loop. In FORTRAN language, we need not declare integer variables. Variable names that start with i, j, k, l, m and n are integer variables. So, FORTRAN developers named for-loop index with i,j,k and that habit carried on to other languages.

System.out.println and Performance

There is a general notion that System.out.println are bad for performance. When we analyze deeply, the sequence of calls are like println -> print -> write() + newLine(). This sequence flow is an implementation of Sun/Oracle JDK. Both write() and newLine() contains a synchronized block. Synchronization has a little overhead, but more than that the cost of adding characters to the buffer and printing is high.
When we run a performance analysis, run multiple number of System.out.println and record the time, the execution duration increases proportionally. Performance degrades when we print more that 50 characters and print more than 50,000 lines.
It all depends on the scenario we use it. Whatever may be the case, do not use System.out.println for logging to stdout.

Static Import to Shorten System.out.println()

Sometimes we feel System.out.println is a long statement to print. static import may shorten it a bit but it is not recommended, because it results in poor readability. I am just using this situation to explain static import and avoid using it in the below scenario.
import static java.lang.System.out;

public class ShortSOP {
public static void main(String[] args) {
out.println("Hello, world");
}
}
In Eclipse you have programmed shortcuts like ctrl + spac to help you out.

System.err and System.in

As a related section, I wish to discuss about ‘err’ and ‘in’. ‘in’ is associated with InputStream. Opposite to ‘out’, ‘in’ is used to get input from standard console generally keyboard.
‘err’ is associated with PrintStream and prints the argument to the standard error output stream. When you use eclipse kind of IDE you can see the difference in ouput between ‘out’ and ‘err’.
public class InOutErr {
public static void main(String args[]) {
try {

BufferedReader reader = new BufferedReader(System.in);
String filename = reader.readLine();

  InputStream input = new FileInputStream(filename);
  System.out.println("File opened...");

} catch (IOException e){
  System.err.println("Where is that file?");
}
}
}

System.out.println Equivalent in other Languages

DBASE III+
? "Hello World"
C
 #include 
 #include 

 int main(void)
 {
  printf("Hello, world");
  return EXIT_SUCCESS;
 }
CPP
 #include 

 int main()
 {
  std::cout << "Hello, World." << std::endl;
 }
BASIC
10 PRINT "HELLO WORLD"
FORTRAN
 PROGRAM HELLOWORLD
 10 FORMAT (1X,11HHELLO WORLD)
 WRITE(6,10)
 END
COBOL
 IDENTIFICATION DIVISION.
 PROGRAM-ID. Hello.
 ENVIRONMENT DIVISION.
 DATA DIVISION.
 PROCEDURE DIVISION.
 Display 'Hello, World'.
 STOP RUN.
LISP
 (DEFUN HELLO-WORLD ()
 (PRINT (LIST 'HELLO 'WORLD)))
PROLOG
go :-
 writeln('Hello World').
System.out.println("Bye");

SOURCE

Tuesday, 24 May 2016

Setting locale for fmt tags.

Add the following just above header.
<c:set var="language" value="${not empty param.language ? param.language : not empty language ? language : pageContext.request.locale}" scope="session" />
<fmt:setLocale value="${language}" />
<html lang="${language}">

Add the following where ever you require the local drop down to appear.
<form>
                        <select id="language" name="language" onchange="submit()">
                            <option value="en" ${language == 'en' ? 'selected' : ''}>English</option>
                            <option value="es" ${language == 'es' ? 'selected' : ''}>EspaƱol</option>
                        </select>
                    </form>