Friday, 27 May 2016

Java This

Definition for java this keyword:
Java this keyword is used to refer the current instance of the method on which it is used.

Following are the ways to use java this

1) To specifically denote that the instance variable is used instead of static or local variable.That is,
private String javaFAQ;
void methodName(String javaFAQ) {
this.javaFAQ = javaFAQ;
}
Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the “this” denotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective of this is used or not it denotes the instance variable.
2) Java This is used to refer the constructors
public JavaQuestions(String javapapers) {
this(javapapers, true);
}
Java This invokes the constructor of the same java class which has two parameters.
3) Java This is used to pass the current java instance as parameter
obj.itIsMe(this);
4) Similar to the above, java this can also be used to return the current instance
CurrentClassName startMethod() {
return this;
}
Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.
5) Java This can be used to get the handle of the current class
Class className = this.getClass(); // this methodology is preferable in java
Though this can be done by, Class className = ABC.class; // here ABC refers to the class name and you need to know that!
As always, java this is associated with its instance and this will not work in static methods.
How is(java) this?


SOURCE

Java Numeric Promotion

This Java article is to discuss about the numeric promotion that happens when using operators. Similar to the last Java puzzle on floating point precision, this article will also make raise some eyebrows. Last week a regular reader of Javapapers Palani Kumar wrote to me and asked a question,
Why I cannot add two byte and short data type in Java?” Thanks Palani, this article is the response to your question :-)
Can you guess the output of the following Java program?
public class NumericPromotion {
 public static void main(String... args){
  //part 1
  final byte a = 1;
  final byte b = 2;
  byte c = a + b;
  System.out.println(c);

  //part 2
  byte i = 1;
  byte j = 2;
  byte k = i + j;
  System.out.println(k);
 }
}
Promotion

Decoding the Puzzle

There are two parts to it. Absolutely no problem with the first part. Two Java final byte variables are created. Then they are added into a byte variable. This addition statement gets processed at compile time and since both its operands are final variables, the ‘byte c’ is instantiated and the constant value ‘3’ is assigned.
So what we have here is a narrowing conversion and it is possible, if all the operands are constant values in an expression. As per Java Language Specification (JLS),
In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int: – A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable

Problem Area

Now to part 2. Here we got problem! We get the following error on compilation of the above Java program.
NumericPromotion.java:10: error: possible loss of precision
                byte k = i + j;
                           ^
  required: byte
  found:    int
1 error
The statement where the Java compiler complains about is a normal arithmetic statement. We are adding two byte variables and assigning it to another byte variable. Whats wrong with this? The error says, “required: byte and found: int”. How come, it found ‘int’? We have never declared anything as int in this program.

Numeric Promotion by Operator

Here is what happens. There is no addition operator for byte. This addition operator used here promotes its operands to ‘int’ automatically. After promoted it becomes addition of two int values and so the result is an int value. Now the issue is, this result int value cannot be assigned to a byte variable k.
Narrowing conversion is not done automatically by the Java runtime. We need to explicitly cast the value to byte. If you want to know about narrowing conversion and cast in Java, please go read this previous tutorial. It is a comprehensive tutorial and I seriously recommend it to you as I am sure you will find something new there. As per JLS,
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:
  • If any of the operands is of a reference type, unboxing conversion
    (§5.1.8) is performed. Then:
  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to
    float.
  • Otherwise, if either operand is of type long, the other is converted to
    long.
  • Otherwise, both operands are converted to type int.


SOURCE

Java Cast and Conversions

In this Java fundamentals tutorial let us see about casting in Java. This tutorial is having two parts, the first one is for casting on reference types and the second is for primitives cast. In each part let us see about the different types of cast available and how we can use them in Java.
First we have to fix the terminologies. Java language specification (SE7-JLS-5.0) uses the word ‘conversion’ as a superset for anything and everything related to transforming objects. The word ‘cast’ is used at places where the developer needs to explicitly tell the compiler that the instance value needs to be converted. Attaching the cast-operator (a type between parentheses), before an object is referred as cast.

type-safety in Java

Type-safety is the mechanism provided in a programming language to ensure that there are no issues because of type mismatch between a variable and value attempted to store in it. In Java to ensure type-safety, during compile time the compiler will check for type information between variables using the static type information available. Then during runtime the values are checked for compatibility before storing in a variable.
Conversion
As per Java language specification (SE7-JLS-5.0) conversions are broadly categorized as,
  • Identity conversions
  • Widening primitive conversions
  • Narrowing primitive conversions
  • Widening reference conversions
  • Narrowing reference conversions
  • Boxing conversions
  • Unboxing conversions
  • Unchecked conversions
  • Capture conversions
  • String conversions
  • Value set conversions

Identity Conversion

This is given for theoretical completeness. Assigning two instance of same type is identity conversion.
 Integer i1;
 Integer i2 = new Integer(2);

 i1 = i2; //identity conversion
 // cast not required, but done compiler will not complain
 i1 = (Integer) i2;

Primitive Conversions and Cast in Java

These are the conversions between the primitives.

Widening Primitive Conversion

“A widening primitive conversion does not lose information about the overall magnitude of a numeric value.” There is no cast required and will never result in a runtime exception. Following are the possible widening conversions,
  • byte to short, int, long, float, or double
  • short to int, long, float, or double
  • char to int, long, float, or double
  • int to long, float, or double
  • long to float or double
  • float to double
class WideningConversion {
    public static void main(String[] args) {
 int i = 123456789;
 float f = i;
    }
}

Narrowing Primitive Conversion

“A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.” Cast required between types. Overflow and underflow may happen but a runtime exception will never happen. Following are the possible narrowing conversions,
  • short to byte or char
  • char to byte or short
  • int to byte, short, or char
  • long to byte, short, char, or int
  • float to byte, short, char, int, or long
  • double to byte, short, char, int, long, or float
package com.javapapers.java;

public class NarrowingPrimitiveConversion {
 public static void main(String[] args) {

 float f = Float.POSITIVE_INFINITY;
 long l = (long) f;
 int i = (int) f;

 System.out.println("long: " + l + " int: " + i);

 int j = 255;
 byte b = (byte) j;

 // size is too large and resulted in negative
 System.out.println(b);
  }
}

Reference Conversions and Cast in Java

In this section let us see about categories, widening reference conversion and narrowing reference conversion. With respect to classes and objects, there are four categories to understand for casting.
public class JavaCast {
    public static void main(String... args) {
        
        Integer integer = new Integer(10);
        Float floatt = new Float(20F);

        //this is not a cast - error
        // integer = floatt; //compiler error - incompatible types
        // integer = (Integer) floatt;//compiler error - inconvertible types
        
        //upcast - widening conversion
        Object obj = integer; //no explicit cast required
        System.out.println(obj);

        //downcast - narrowing conversion
        Integer in = (Integer)obj;//only subtype
        System.out.println(in);

        //downcast - Object to String
        //runtime issue - instance Object is not of String
        String str = (String)obj;//ClassCastException
    }
}
  1. Assigning a Float object to Integer directly has got nothing to do with casting and it will throw a compile error as incompatible type. Casting a Float into Integer is not proper and will get compile error as inconvertible types. Casting in Java is done within same hierarchy of types, that is between inherited types.
  2. upcast – Casting a subtype object into a supertype and this is called upcast. In Java, we need not add an explicit cast and you can assign the object directly. Compiler will understand and cast the value to supertype. By doing this, we are lifting an object to a generic level. If we prefer, we can add an explicit cast and no issues.
  3. downcast – Casting a supertype to a subtype is called downcast. This is the mostly done cast. By doing this we are telling the compiler that the value stored in the base object is of a super type. Then we are asking the runtime to assign the value. Because of downcast we get access to methods of the subtype on that object.
  4. ClassCastExcpetion – We get ClassCastException in a downcast. In principle, we guarantee the compiler that the instance value of is subtype and ask it to cast. But during runtime, because of unforeseen circumstances, the value is not of expected subtype. In such cases, we get ClassCastException.

Boxing and Unboxing Conversions

Converting from a primitive type to its corresponding reference type is boxing conversion and vice versa is unboxing conversion.
Examples are,
  • From primitive boolean to type Boolean
  • From primitive int to type Integer
 int i = 10;
 Integer iObj = new Integer(100);

 iObj = i;//boxing conversion
 i = iObj;//unboxing conversion

String Conversion

String conversion applies only to the ‘+’ operator, when one operand is a String and another is a primitive type. In such a case, primitive type is converted to its corresponding reference type and then it is converted using the toString() method. No cast is required.
 int i = 10;
 String str1 = "";

 String str2 = str1 + i; //string conversion
Unchecked and Capture Conversion will be discussed in the next tutorial as part of the generics series.

SOURCE

Java Abstract Class and Methods

This Java tutorial is to help understand what are abstract classes and methods. This tutorial is applicable for Java beginners. An abstract class in Java cannot be instantiated. It does not end with it. Can a Java abstract class have a constructor? Can an abstract method be defined as static? If you are not comfortable with these questions, then you should read this tutorial and refresh the basics.

Java Abstract Class

A Java class that is declared using the keyword abstract is called an abstract class. New instances cannot be created for an abstract class but it can be extended. An abstract class can have abstract methods and concrete methods or both. Methods with implementation body are concrete methods. An abstract class can have static fields and methods and they can be used the same way as used in a concrete class. Following is an example for Java abstract class.
public abstract class Animal {

}
We cannot create new instances for the above Animal class as it is declared as ‘abstract’.

Java Abstract Method

A method that is declared using the keyword abstract is called an abstract method. Abstract methods are declaration only and it will not have implementation. It will not have a method body. A Java class containing an abstract class must be declared as abstract class. An abstract method can only set a visibility modifier, one of public or protected. That is, an abstract method cannot add static or final modifier to the declaration. Following is an example for Java abstract method.
public abstract class Animal {
 String name;

 public abstract String getSound();

 public String getName() {
  return name;
 }
}

Extending an Abstract Class

When an abstract class is implemented in Java, generally all its abstract methods will be defined. If one or more abstract method is not defined in the implementing class, then it also should be declared as an abstract class. Following is an example class that implements the Animal abstract class. @Override is a Java annotation used to state that this method overrides the method in the super class.

public class Lion extends Animal {

 @Override
 public String getSound() {
  return "roar";
 }

}
Java Abstract Class and Methods

Abstract class Implements an Interface

It is possible for an abstract class to implement a Java interface. If the implementing class does not implement all of the abstract methods from the interface, then this must be defined an abstract class in Java. In the below example, Animal class does not implement the abstract method from Species interface. Though Animal does not have any abstract method on its own, it must be declared as abstract since it did not implement the abstract method from Species interface. Any class that extends the Animal class should implement the getClassification abstract method. Difference between an interface and abstract class is methods in an interface are implicitly abstract. Go through this linked tutorial to know more about the differences.

public interface Species {
 public String getClassification();
}
public abstract class Animal implements Species {
 String name;

 public String getName() {
  return name;
 }
}

When Should I use an Abstract class

We should go for abstract class when we are working with classes that contains similar code. That is, there is a possibility to template behavior and attributes. Common behavior can be elevated to a super class and provide implementation to it. Then add behavior that cannot be implemented and declare it as abstract. Classes that are similar to this abstract class will extend it and use the already implemented methods and add implementation for abstract methods.
In the above Animal example given, name is a common attributes for animals and so it is elevate to the Animal super class. getName is a common behavior for all animal and it depends on the common attribute name. So implementation for this getName is provided in the abstract super class. getSound depends on individual animals and so it is declared abstract and left for extending class to implement it. What we gain from this template pattern is avoiding repetition of common code.

Abstract Class Example in Java API

AbstractMap is an abstract class part of Collections Framework in the Java JDK. It is extended by a long list of Subclasses ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, HashMap, IdentityHashMap, TreeMap, WeakHashMap. These class share and reuse many methods from this abstract class like get, put, isEmpty.

Can an Abstract Class have Constructor in Java?

Yes, an abstract class can have constructor in Java. It can be a useful option to enforce class constraints like setting up a field. Let me demonstrate it using our Animal example below.
public abstract class Animal {
 String name;

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

 public String getName() {
  return name;
 }

 public abstract String getSound();
}
This abstract class defines a constructor with an argument that is used to setup the field name. Classes that extends this abstract class should define a constructor with implicit super() call to the super abstract class. Otherwise we will get an error as “Implicit super constructor Animal() is undefined. Must explicitly invoke another constructor”. This is to do some initialization before instantiation.
public class Lion extends Animal {

 public Lion(String name) {
  super(name);
 }

 @Override
 public String getSound() {
  return "roar";
 }

}

Can an Abstract class be final in Java?

No, an abstract class cannot be declared as final in Java. Because it will completely negate the purpose of an abstract class. An abstract class should be extended to create instances. If it is declared final, then it cannot be extended and so an abstract class cannot be declared as final.

SOURCE

Java Final Keyword

  • A java variable can be declared using the keyword final. Then the final variable can be assigned only once.
  • A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces the constructors to initialise it.
  • Java classes declared as final cannot be extended. Restricting inheritance!
  • Methods declared as final cannot be overridden. In methods private is equal to final, but in variables it is not.
  • final parameters – values of the parameters cannot be changed after initialization. Do a small java exercise to find out the implications of final parameters in method overriding.
  • Java local classes can only reference local variables and parameters that are declared as final.
  • A visible advantage of declaring a java variable as static final is, the compiled java class results in faster performance.

A discussion inviting controversy on java final keyword:

‘final’ should not be called as constants. Because when an array is declared as final, the state of the object stored in the array can be modified. You need to make it immutable in order not to allow modifcations. In general context constants will not allow to modify. In C++, an array declared as const will not allow the above scenario but java allows. So java’s final is not the general constant used across in computer languages.
A variable that is declared static final is closer to constants in general software terminology. You must instantiate the variable when you declare it static final.
Definition as per java language specification (third edition) – 4.12.4 is “A final variable may only be assigned to once.”(§4.1.2)
Java language specification tries to redefine the meaning of constant in the following way!
We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).

SOURCE

Java Static Import

First lets understand what does “java import” does to your java program!
Consider the java import statements:
1) import package.ClassA;
2) import package.*;
Java statement (1) gives you a license to use ClassA inside the whole program without the package reference. That is you can use like ClassA obj = new ClassA(); or ClassA.getStatic(); Java statement (2) allows you to use all the java classes that belong the imported package in the above manner. That is without the package reference.
If you don’t use import statement, you can still use the classes of that package. But you should invoke it with package reference whereever you use.
That is like, package.ClassA obj = new package.ClassA(); – looks very ugly isn’t it?
Now coming to the static import part. Like the above ugly line we have been unknowingly using (abusing) the java static feature.
Consider the java example: double r = Math.cos(Math.PI * theta);
How about writing the same java code like: double r = cos(PI * theta); – looks more readable right?
This is where static import in java comes to help you.
import static java.lang.Math.PI;
import static java.lang.Math.cos;
Do the above static imports and then you can write it in the more readable  way!

Java Static Import

The normal import declaration imports classes from packages, so that they can be used without package reference. Similarly the static import declaration imports static members from classes and allowing them to be used without class reference.
Now, we have got an excellent java feature from java 1.5. Ok now we shall see how we can abuse this!

Can i static import everything?

like, import static java.lang.Math.*; – yes it is allowed! Similarly you do for class import.
Please don’t use this feature, because over a period you may not understand which static method or static attribute belongs to which class inside the java program. The program may become unreadable.
General guidelines to use static java import:
1) Use it to declare local copies of java constants
2) When you require frequent access to static members from one or two java classes


SOURCE

Java Static

Java Static Variables

  • Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single java class, then the static modifier should be used in the variable declaration.
  • Any java object that belongs to that class can modify its static variables.
  • Also, an instance is not a must to modify the static variable and it can be accessed using the java class directly.
  • Static variables can be accessed by java instance methods also.
  • When the value of a constant is known at compile time it is declared ‘final’ using the ‘static’ keyword.

Java Static Methods

  • Similar to static variables, java static methods are also common to classes and not tied to a java instance.
  • Good practice in java is that, static methods should be invoked with using the class name though it can be invoked using an object. ClassName.methodName(arguments) or objectName.methodName(arguments)
  • General use for java static methods is to access static fields.
  • Static methods can be accessed by java instance methods.
  • Java static methods cannot access instance variables or instance methods directly.
  • Java static methods cannot use the ‘this’ keyword.

Java Static Classes

  • For java classes, only an inner class can be declared using the static modifier.
  • For java a static inner class it does not mean that, all their members are static. These are called nested static classes in java.
SOURCE