Monday, May 26, 2014

# 15 - STATIC made SIMPLE

Hello,

In my starting days of programming I tried to understand the use of static keyword in Java. I googled about it, I discussed with my seniors to exactly understand what is all about this BIG guy static. Yes, I call this modifier as a BIG guy coz it is not like any other modifier in Java. It is different that’s what makes him special..!! In this post I am gonna make this BIG guy really simple for you to understand so that you guys can get it in ONE reading..! That’s the only motto of my blog..! J

static

This modifier can be used with classes/methods/variables. As a basic definition, before we go into the details, static modifier makes classes/methods/variables static..!! That’s it..! :P

Yea. I am explaining. Static means not instance specific. Class Specific. The first time we instantiate the class, all the static variables/methods gets instantiated. And later if you create 1000 instances, the value static variables/methods do not change.  You can see this in programming below so that you understand better. I know you guys understand better in Programming language than English.!

Btw, I wanna add one more point. Many people get confused about class members and instance members in Java.
The methods/variables which are declared as static --> are Class members
The methods/variables which are NOT declared as static --> are Instance members.

Static modifier with classes

Yes, static modifier can be used with classes. ONLY WITH INNER CLASSES. If you try to put the static modifier before a base class (top level class), the compiler will start shouting at you.
public static class ClassA{
	
	public static void main(String... args){
		
		// your code and logic for this method goes here. 
	}
}
I have a class ClassA which is the only class in the file. I declared the class as static and when I tried to compile the class, I get the below error.
Illegal modifier for the class ClassA; only public, abstract & final are permitted
You knew it. Classes can have ONLY public, abstract or final modifiers. It cannot accept any other modifier.

Let us see with inner classes.
public class ClassA{
	
	public static void main(String... args){
		
		System.out.println("ClassA.main()");
		
		// create an instance of Inner class ClassB
		ClassB b = new ClassB();
		
		// retrieve the value of ClassB instance variable i 
		System.out.println("ClassA.main().. instance variable i --> "+b.i);
		
		// retrieve the value of ClassB class variable j
		System.out.println("ClassA.main().. class variable j --> "+ClassB.j);
		
	}
		
	// Inner class
	static class ClassB{
		
		//instance vaiable
		int i = 10;
		
		// static variable
		static int j = 20;
		
	}
}
}

When I try to compile the above class, I get,
Output:
ClassA.main()
ClassA.main().. instance variable i --> 10
ClassA.main().. class variable j --> 20
  • Static nested(inner) classes are allowed. There is no such thing called static top-level class in Java.
  • If an inner class is declared as static, it doesn't mean that it should necessarily contain ONLY static methods/variables. It can also contain non-static members.
  • For accessing non-static members of an inner class, we need to create an instance of that class. But for accessing static members, we just need to use InnerClassName.StaticMember.

So here comes the BIG question, WHY ?
Why a top-level class is not allowed to declare as static when an inner class is allowed?

Top-level class is not allowed to declare as static bcoz it doesn’t make any sense..! static keywords says to the compiler that, “I do not need any instance. I can instantiate myself..!” But if a class doesn’t require any instances then what is the use of a class in an Object Oriented Programming ?  No sense - no use.

In the case of inner classes, static keyword helps us to use the static inner class without creating an instance of the outer class. If we do not use the static keyword for the inner classes, then we need to create instance of the outer class and then use this instance, we need to create the instance of non-static inner class.
public class ClassA{
	
	public static void main(String... args){
		
		System.out.println("ClassA.main()");
		
		// create an instance of Inner class ClassB
		ClassB b = new ClassB();
		
		// retrieve the value of ClassB instance variable i 
		System.out.println("ClassA.main().. instance variable i --> "+b.i);
		
		// retrieve the value of ClassB class variable j
		System.out.println("ClassA.main().. class variable j --> "+ClassB.j);
		
	}
		
	// Inner class
	static class ClassB{
		
		//instance vaiable
		int i = 10;
		
		// static variable
		static int j = 20;
		
	}
}

Static modifier with Methods/Variables

The static modifier works in the same way with the methods and variables. The first question comes why and when we have to use static keywords with methods/variables.

As I have already mentioned that the static members are class specific, so if we would like to make the methods/variables work irrespective of the class state or value of the instance members then declare that method/variable as static. 

In real time, we mostly declare the utility methods as static. Coz the utility methods should work in same way irrespective of the instance we create or the values we pass.
Assume that I have a requirement of counting the instances of my class that are being created. In this case I cannot use the instance members as they are assigned default values every time we create an instance.
public class ClassA{
	
	// class member
	static int staticCount = 0;
	
	// instance member
	int nonStaticCount = 0;
	
	// constructor
	public ClassA(){
		
		// increment by 1 every time we create an instance
		staticCount += 1;
		nonStaticCount +=1;
	}
	
	public static void main(String... args){
		
		// instance 1
		ClassA a = new ClassA();
		
		System.out.println("ClassA.main()..staticCount --> "+staticCount);
		System.out.println("ClassA.main()..nonStaticCount --> "+a.nonStaticCount);
		
		// instance 2
		ClassA aa = new ClassA();
		System.out.println("ClassA.main()..staticCount --> "+staticCount);
		System.out.println("ClassA.main()..nonStaticCount --> "+aa.nonStaticCount);
		
	}
}
When I run the above program, I get the output as
Output:
ClassA.main()..staticCount --> 1
ClassA.main()..nonStaticCount --> 1
ClassA.main()..staticCount --> 2
ClassA.main()..nonStaticCount --> 1
You can see that I have created 2 variables. One is static and the other is Non-static. For my requirement only static variable gives me the correct count. When instance 1 is created both the variables staticCount and nonStaticCount are incremented by one. When the instance 2 is created, the nonStaticCount variable is assigned to its default value zero, but the static variable staticCount value is already 1(bcoz of instance 1) and again it is incremented by 1 so that makes its value 2 and nonStaticCount value 1.
Now you may be wondering why I have used the nonStaticCount variable with the object “a” and “aa” where I have used staticCount variable directly. Right?
Bcoz, in Java we CANNOT access non-static members from a static method. If we try to do so, we get a compiler error saying,
Cannot make a static reference to the non-static field nonStaticCount
If you observe in the above program, main() method  is declared as static and so we can access static members directly in a static method. Hence I can use the staticCount variable directly in the main(). But when I want to use non-static members inside a static method, I need to create an object of a class to access its members. That is the reason I have accessed the nonStaticCount variable using a.nonStaticCount and aa.nonStaticCount


Access Static Members

We know that we don’t need to have an instance for accessing static members. Then how can we invoke or access the static members?
It’s the same DOT operator that we access the instance members with an object. But with static members we need to use ClassName.StaticMember
public class ClassA{
	
	// class member
	static int staticCount = 20;
	
	// Inner Class
	static class InnerClassA{
		public static void main(String... args){
			
			System.out.println("ClassName DOT StaticMember --> "+ClassA.staticCount);
		}
	}
}
We can also access static members using the object/instance of the class. But it is not suggested bcoz there may be a chance of not having any instances of the class at all..! So always access the static members with the class name.
public class ClassA{
	
	// class member
	static int staticCount = 20;
	
	// Inner Class
	static class InnerClassA{
		public static void main(String... args){
			
			// GOOD
			System.out.println("ClassName DOT StaticMember --> "+ClassA.staticCount);
			
			// BAD..! NOT SUGGESTED
			ClassA a = new ClassA();
			System.out.println("Using the object of Class A --> "+a.staticCount);
		}
	}
}
The above program runs perfectly without any errors.

The last point about static keyword is, static methods CANNOT be overridden but re-defined..!!
public class ClassA{
	
	// class member
	static void printString(){
		System.out.println("ClassA.printString()");
	}
}

class ClassB extends ClassA{
	
	// this is NOT allowed, bcoz static methods canNOT be overriden
	void printString(){
		System.out.println("ClassB.printString()");
	}
	
	
	// this is allowed, bcoz if we define the method here with static then it becomes the member of ClassB
	// something like we are re-defining the method. NOT overriding..!
	static void printString(){
		System.out.println("ClassB.printString()");
	}
}
static keyword shows a huge impact on the methods/variables that are declared as static, mostly when multiple users trying to access your application at a time. So make sure you use it with care..!

transient

transient is the keyword mostly associated with Serialization concept.

Serialization – is the process of streaming the objects or data into bytes before transferring to other networks.
De-Serialization – is a reversal process. Converting the byte stream data to objects.

transient keyword comes into the picture when we don’t like to serialize a particular property of an object.

Imagine I have a class Student. It has 3 properties Id, Name and Roll Number. I want to serialize the student details except studentId. In this kinda cases we should use transient keyword before the property. Below program gives you more idea.
import java.io.Serializable;

public class Student implements Serializable{

	// when we serialize student object, the id will be zero (default value of the dataType)
	transient private int id;
	private String name;
	private int rollNum;
	
	
	// getters and setters goes here	
}


LindlarsForLife :)

Monday, May 19, 2014

# 14 - All About Java Modifiers (Part III)

Hello,

We have seen all about Java Access Modifiers and so it’s time to know all about Java Non-Access Modifiers.

Just to make it clear,

Java Access Modifiers – are the modifiers which provide the facility to access/restrict the class members from a different class.
Java Non-access Modifiers – are the modifiers which are not used for accessing/restricting the class members. In short, all the modifiers which are not related to visibility/accessing the class members are Non-access Modifiers.

Each non-access modifier works in its own way which is completely different from other modifiers. Here are the non-access modifiers that are available in Java.
  • final
  • abstract
  • synchronized
  • native
  • strictfp
  • static
  • transient

All the above words are reserved, meaning they are keywords in Java. Let us look into each modifier in detail.

final :
The final modifier can be applied to classes/methods/ variables. It will act differently when applied to a class from the way it acts when applied to a method/variable.
As the name suggests, when final keyword is used it restricts the user to modify the class/method/variable details. JVM will decide it as FINAL, it doesn't listen to anyone else..!

final modifier when applied to a class
So when I apply the final keyword to a class, that class canNOT be extended by any other subclass. See the below example
// ClassA
public final class ClassA{
 public static void main(String... s){
  System.out.println("ClassA.main()");
  }
 }

// ClassB
class ClassB extends ClassA{
 // class members and variables goes here 
}
You can see that I have a class ClassA which is marked as final and I tried to extend the ClassA so that I can use ClassA variables and methods. But as ClassA is a final class, if I try to extend ClassA I get a compiler error saying,
The type ClassB cannot subclass the final class ClassA
If we want to restrict other developers in extending our class features, mark it as final. By marking it final we can be sure that no other developer can modify the features of our class.

final modifier when applied to a method
When a final keyword is used in a method’s signature, then that method canNOT  be overridden in any subclass. Imagine I have a method in a class which finds two strings are meaningfully equal are not. I want other developers to use this method without modifying the logic inside the method. That’s where I use final keyword to the method which informs other developers that the logic inside the method shouldn’t be changed.
public class ClassA{
 public final void methodA(){
  System.out.println("ClassA.methodA()");
 }
}

class ClassB extends ClassA{ // we can extend ClassA as it is not marked as final
 public void methodA(){ // Compiler error..!!! method is marked as final in classA, so we cannot use method in its subclass.
 }
}
If we try to compile the above program, we get the below error.
Cannot override the final method from ClassA
Make sure you use the final keyword for methods with great caution. If there are any bugs in the logic of your method, then the developers who use your method may start searching for you..:P
final modifier when applied to variable
When a final modifier is used to a variable, then that variable value cannot be changed in its corresponding scope. In other words, the memory address associated with that variable cannot be changed. If we try to do so, we will get a compiler error.
public class ClassA{
 
 final int classInt = 50; 
 
 public void methodA(){
  final int methodInt = 100;
 }
}
You can see that I have 2 final variables. One is of class scope and the other is of method scope. The class variable classInt value cannot be modified in the entire class and the method variable methodInt cannot be modified in the method method.

abstract:
The abstract modifier can be used only with classes and methods but not with variables. The word abstract means that something not described clearly or not having clear idea/picture. The same meaning applies in Java as well.

abstract modifier when applied to a class:
If a class contains at least one abstract method, then the class should be marked as abstract. It is illegal to have even a single abstract method in a class that is not explicitly declared abstract. But we can have an abstract class with no abstract methods.
I have no intention to confuse you. See the below code :)
public abstract class ClassA{
 
 // concrete method
 public void methodA(){
  
  // your code and logic for this method goes here. 
 }
 
 // concrete method
 public void getUserDeatails(){
  // connect to the database and get the user details.
 }
}
In the above Java class, we don’t have any abstract methods. But still, it is legal to declare the class a abstract.
public class ClassA{
 
 // concrete method
 public void methodA(){
  // your code and logic for this method goes here. 
 }
 
 // abstract method - no implementation code
 public abstract void getUserDeatails();
}
In this Java class, you can see that we have one abstract method and one concrete method. But the class is not declared as abstract. When we try to compile this class, we get a compiler error saying,
The type ClassA must be an abstract class to define abstract methods
So the bottom line is, if a class contains at least 1 abstract class then we are forced to declare the entire class as abstract.

abstract modifier when applied to a method:
An abstract method is a method that has been declared but not implemented. A method which is marked as abstract will never have implementation code. The implementation for the abstract methods will be developed in the concrete class that implements the abstract class.
Let’s take an example for better understanding.
Imagine I have a class Car and different companies want to implement their own design of the car. So I have written an abstract method design() in the class Car so that the car that implements the class Car can implement their own design() code depending on their own car configuration. Audi wants to implement the design() differently and BMW might want to implement differently. That’s how the abstract class/methods are useful by providing the capability to implement the code specifically..!
Here are the clues to differentiate between abstract method and concrete methods,
  1. abstract methods are marked as abstract. The concrete methods are not marked as abstract.
  2. abstract methods doesn’t include curly braces or it will not have a method body. The abstract method ends with semi-colon. The concrete methods contain open/close curly braces and don’t end with semi-colon.
  3. The concrete methods provide actual implementation code where as abstract method does not.
public abstract class Car{
 
 // abstract method
 public abstract void design();
 
 //concrete method
 public void move(){
  // the logic in this method can be shared by all the sub classes
  System.out.println("Car.move()");
 }
}

// sub class
class BMW extends Car{
 
 public void design(){
  // Implement their own BMW Design of the car
 }
}

// sub class
class Audi extends Car{
 
 public void design(){
  // Implement their own Audi Design of the car
 }
}
synchronized
The synchronized keyword is associated with Threading concept.  When multiple threads try to access one single resource, thread 1 may not see the change thread 2 made which causes logical errors in the program. This can be prevented by using the keyword synchronized. This keyword can be applied ONLY to methods and cannot be used for classes or variables.
We can see more about this modifier during the concept of Multi-Threading in Java :)

native
native modifier can be used ONLY with method not with class nor variables. By using this modifier we are letting know the JVM that the code inside the method is not Java. Earlier (may be before Java 1.5v) developers use other languages for increasing the performance but later Java has undergone many changes in the performance sections and hence native modifier has become less used.
All you just need to know about native modifier is it allow us to use other programming languages.

strictfp
strictfp is a keyword used with ONLY methods. strictfp says “I strictly follow IEEE754 Floating Point standards”. If we declare a method with strictfp, then the code inside the method will follow IEEE 754 standards. Now don’t ask me what is IEEE 754, if you really wanna know you can see it here.

There are chances that different platforms (32 bit, 64 bit etc.,) may produce different results of calculation if decimals are involved (may be coz of truncating). To make sure our code follows a particular standard for calculating the decimal results on any platform so that we get the same results, we better use strictfp keyword.

We will discuss about the other 2 modifiers (static and transient) in next post..!! Thanks :)