Saturday, June 15, 2013

How Memory Allocation Happens in Java?


This post is all about a small introduction about how memory is allocated in java.
When JVM is getting started , Underlaying Operating system allocates a chunk of memory to JVM.
This chunk size is dependent on the version of OS, Version of java and total memory available to OS.

A quick way to explain java memory allocation is , java mainly keeps it data to heap and stack area. So whenever JVM gets some memory it divides the area to stack and heap area.
Heap area is to keep the live objects and stack area is to keep all method calls and local variables.
Mainly the heap area is the garbage collectable area.

The problem arises when we talk about the variables. It is bit complicated to understand where they live.
Let me explain the variable part to make it easy...
Variables can be divided into two broad categories..

  • Instance variables
  • Local variables
Local variables mostly declared in methods, even the method parameters are local to method. As all the methods stay in stack, hence local variables stay in stack in the frame corresponding to the method. That is the reason Local variables are called stack variables.

again for instance variable they are mostly declared inside a class. They become active when the object is created. So instance variable stay in heap area,where the objects are stored.The memory allocation depends on the size of the type. say a int will take 32 bits, a long will take 64 bits. JVM will not consider the value of it, It will allocate 32 / 64 bit memory.

Methods:
For methods as I said earlier, JVM pushes themselves to stack.
So if your program have 3 methods
main()
dosometask1() // having 1 local variable
dosometask2()//having 2 local variables

JVM reads it and pushes the methods to the stack one by one.
so the stack will be ..
  • dosometask2()
  • dosometask1()
  • main()
with Local variables.
One more area we need to think, if the variable holds reference of an object. like..
public int calc()
{
Tree t=new Tree();

}
For this case, the method calc() will go to stack, with the variable 't'. But since we have created a new object here with new keyword, the object will go to heap and the reference will be created with this variable.

So if only give

public int calc()
{
Tree t;

}

so public method calc will be pushed to stack with a reference variable t but no object will be crated in the heap.again when JVM gets a command called new Tree(); only then the object in the heap will be created.

In the first look we might think that object creation is calling a method..Method name is Tree()
public int calc()
{
Tree t=new Tree();

}

Not exactly, It is calling the Tree constructor.(Constructor is nothing but a set of codes which runs when we instantiate an object)
Saturday, June 1, 2013

What Is The Difference Between enum,Enum and Enumeration in Java?


Few days back I got this question from one of my blog follower Anish. Thanks for raising this point Anish. I am going publish a little comparison between them what ever I got with the help of Google.


enum

Enum

Enumeration

enum is a keyword which represents a group of named constants

Enum is present in java.lang package. It is a parent class of enum. So it acts as a base class for every enum

Enumeration is an interface present in java.util package

enum can hold constructor(no argumented and argumented) and methods

Enum can not hold the constructor or methods

We use this method to get object from collection one by one

Below 1.4 version it was used as a literal and after 1.4 version it becomes group of constants and it is reserved



Friday, May 31, 2013

How Constructor Works In Java Enum ?


In my last few posts

I have discussed concepts on Enum. In this post I would like to show the constructor concept in java enum.Constructor!!! that too in enum???
Yes!!! java has come up with this beautiful concept.
enum can contain constructors. This constructors will be executed at the time of enum class loading automatically for every enum constant.

enum Month    
{    
JAN,FEB,MAR;    
//note semicolon(;) is optional here    
Month()
{
System.out.println("enum constructor");
}
} 
class Testenumcons{
public static void main(String... Args)
{
Month mon=Month.JAN;
System.out.println("Main method");
}
}
output:
enum constructor
enum constructor
enum constructor
Main method
Now we can also conclude-
we can not create enum object explicitly if we do so we will get compile time error.

enum Month    
{    
JAN,FEB,MAR;    
//note semicolon(;) is optional here    
Month()
{
System.out.println("enum constructor");
}
} 
class Testenumcons{
public static void main(String... Args)
{
Month mon=new Month();
//illegal statement.
Month mon=Month.JAN;
System.out.println("Main method");
}
}
E:\myProgram\Testenumcons.java:13: error: enum types may not be instantiated
Month mon=new Month();
^
E:\myProgram\Testenumcons.java:14: error: variable mon is already defined in met
hod main(String...)
Month mon=Month.JAN;
^
2 errors
So we can not invoke enum constructor directly.
Till now in the above example we have seen no argument constructor.But we can also have argumented constructor.
enum Month    
{    
JAN(31),FEB(28),MAR(31),APR;   
int days ;
//note semicolon(;) is optional here  
//argumented constructor  
Month(int days)
{
System.out.println("enum argumented constructor ");
this.days=days;
}
// no argumented constructor
Month()
{
System.out.println("enum no argument constructor");
this.days=31;
}
public int getDays()
{
return days;
}
} 
class Testenumcons{
public static void main(String... Args)
{

Month[] mon=Month.values();
for (Month m:mon)
{
System.out.println(m+"-->"+m.getDays());
}
}
}

output:
enum argumented constructor
enum argumented constructor
enum argumented constructor
enum no argument constructor
JAN-->31
FEB-->28
MAR-->31
APR-->31
in general if you do not define any no argument constructor, Compiler will automatically put a no argument constructor inside enum when it transfer enum to class. but that will have no statement inside it. But there are two cases to check out..
Case 1. if the enum constants have mix with argumented and non argumented then it is compulsory to define both argumented and non argumented constructor. Otherwise compiler will throw compile time error.
Case-2 Compiler will automatically add no argumented constructor if no argumented constructor is defined.
enum Month    
{    
JAN(31),FEB(28),MAR(31),APR;   
int days ;
//note semicolon(;) is optional here  
//argumented constructor  
Month(int days)
{
System.out.println("enum argumented constructor ");
this.days=days;
}
// no argumented constructor

public int getDays()
{
return days;
}
} 
class Testenumcons{
public static void main(String... Args)
{

Month[] mon=Month.values();
for (Month m:mon)
{
System.out.println(m+"-->"+m.getDays());
}
}
}

E:\myProgram\Testenumcons.java:3: error: constructor Month in enum Month cannot
be applied to given types;
JAN(31),FEB(28),MAR(31),APR;
^
required: int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
Also inside enum we can add methods. But the methods should be concrete,not abstract.
Every enum constant represents an object of the type enum so the calling of the methods are same as the way we call normal methods
Possible operators we can use are--
  • enum.constantname.equals(enum.constantname)
  • enum.constantname==enum.constantname
  • enum.constantname.ordinal>enum.constantname.ordinal
Normal methods in enum

enum testenum21
{
JAN,FEB,MAR;
public void info()
{
System.out.println("enum info method called");
}
}

class getvalues{
public static void main(String... Args)
{
testenum21[] mon=testenum21.values();
for(testenum21 m: mon)
{
System.out.print(m.ordinal()+ " ");
m.info();

}
}
}
output:
0 enum info method called
1 enum info method called
2 enum info method called

Specific methods in enum
Let us see some specific method attached to enum.
enum testenum21
{
JAN,FEB{
public void info()
{
System.out.println("Festival of love");
}
},MAR;
public void info()
{
System.out.println("enum info method called");
}
}

class getvalues{
public static void main(String... Args)
{
testenum21[] mon=testenum21.values();
for(testenum21 m: mon)
{
System.out.print(m.ordinal()+" ");
m.info();

}
}
}
output:
0 enum info method called
1 Festival of love
2 enum info method called
Thursday, May 30, 2013

How Inheritance Concept Works For Java Enum??


In my previous post (http://www.askqtp.com/2013/05/enum-concept-simplified-in-java.html) I have told how compiler will treat enum.
It will treat enum as a class.
enum Month  
{  
JAN,FEB,MAR;  
//note semicolon(;) is optional here  
}  
will be transferred by the compiler as..
Class Month  
{  
//for JAN  
public static final Month JAN=new Month();  
//similarly for FEB and MAR  
public static final Month FEB=new Month();  
public static final Month MAR=new Month();  
}  

Since the underlying concept is class, the very next question arises as can Inheritance concept works for enum? Let us see few concepts..

  • Every enum is direct child of java.lang.Enum class in java, So enum can't extend any other enum
  • Every enum is always final implicitly hence we can't create child enum
With the above statements we can conclude that inheritance concept is not applicable for explicitly.Hence we can't use extends keyword for enums.
enum x
{}
enum y extends x{}
output: Compile time error
enum x extends java.lan.Enum
{}
output: Compile time error
Class x
{}
enum y extends x{}
output: Compile time error
enum x
{}
Class y extends x{}
output: Compile time error
Can not inherit from final (enum) or enum types are not extensible

However an enum can implement any no of interfaces simultaneously.
interface x
{}
enum y implements x{}
Valid deceleration.

How To Work With Java Enum In Switch Argument??


In my last post (http://www.askqtp.com/2013/05/how-to-get-values-from-enum-in-java.html) I have said how to get values from enum. This post talks about how to work with enum inside switch statement.

Generally we use if when we need to compare small number of (say 2-3) variables,but for big number of condition check it is always better to go for switch statement.
Until java 1.4 version(java4) switch statement used to take byte,short,char and int as argument.
From java1.5(java 5 or tiger) edition switch supports corresponding wrapper classes and enum types.

Java 1.4

java 1.5

java 1.7

byte

Byte

String

short

Short



char

Character



int

Interger





enum

So after java 1.5 onwards,enum can be passed as a type as an argument to switch statement
lets check out one example:
enum Month
{
 JAN,FEB,MAR;
//declare enum
}
public class enumTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Month mon=Month.MAR;
//create switch statement
  switch(mon)
  {
  case JAN : System.out.println("1st Month");break;
  case FEB : System.out.println("2nd Month");break;
  case MAR : System.out.println("3rd Month");break;
  
  }

 }

}

output:
3rd Month
we can pass enum type as argument to switch statement, but every case label should be Valid enum contant. Otherwise we will get compile time error.
enum Month
{
 JAN,FEB,MAR;
//declare enum
}
public class enumTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Month mon=Month.MAR;
//create switch statement
  switch(mon)
  {
  case JAN : System.out.println("1st Month");break;
  case FEB : System.out.println("2nd Month");break;
  case MAR : System.out.println("3rd Month");break;
  case APR : System.out.println("4th Month");break;
  }

 }

}

Output:
Compilation error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
APR cannot be resolved or is not a field
^
at enumTest.main(enumTest.java:20)
Wednesday, May 29, 2013

How To Get Values from Enum In Java


In my last post (http://www.askqtp.com/2013/05/enum-concept-simplified-in-java.html) I have shown how to declare enum in java. In this post we would see how to get values from enum rather how to get values from enum in a systematic approach.

There are three ways we can get values from enum..
  • direct way
  • by using values() method
  • by using ordinal() method

Direct Method
enum testenum21
{
JAN,FEB,MAR;
}
class getvalues{
public static void main(String... Args)
{
testenum21 mon=testenum21.JAN;
System.out.println(mon);
}
}

output: JAN
values() Method
We can use values method to get each element from enum.
The syntax is [[enumname]][] variable=[[enumname]].values();
enum testenum21
{
JAN,FEB,MAR;
}
class getvalues{
public static void main(String... Args)
{
testenum21[] mon=testenum21.values();
for(testenum21 m: mon)
{
System.out.println(m);
}
}
}

output:
JAN
FEB
MAR
ordinal() Method
If in our programming order of the enum constant becomes important,we can use ordinal method to get the order of the element.
The syntax is
public final int ordinal();
enum testenum21
{
JAN,FEB,MAR;
}
class getvalues{
public static void main(String... Args)
{
testenum21[] mon=testenum21.values();
for(testenum21 m: mon)
{
System.out.println(m+"..."+m.ordinal());
}
}
}
The output is
JAN...0
FEB...1
MAR...2
The ordinal method is more powerful and starts with zero. It is zero based.
Tuesday, May 28, 2013

ENUM Concept Simplified In Java


If the programmer wants to represent a group of constants across programming, then they can implement enum.
Enumeration. It has been introduced in Java 1.5 (or java 5 or Tiger release)

The main objective of enum is to define our own datatypes like enumerated data types. This is more powerful concept than older java constant.

enum Month
{
JAN,FEB,MAR;
//note semicolon(;) is optional here
}


or let us check a new example
enum Laptop_company
{
Lenevo,DELL,HP;
//note semicolon(;) is optional here
}


Internal Implementation of enum:

  • If we declare a enum in java compiler is going to transform that to a class concept so in the .class file that enum is structured as class. you can see a <<enum name.class>> file where you have stored your .class file.
  • If we declare element inside enum that is constant. So they are public static and final.
  • Every enum constant is an object of the type enum
Now let us see in practical how it works. Lets us take the first example..

enum Month
{
JAN,FEB,MAR;
//note semicolon(;) is optional here
}


Compiler will transform that in to the class file as..
Class Month
{
//for JAN
public static final Month JAN=new Month();
//similarly for FEB and MAR
public static final Month FEB=new Month();
public static final Month MAR=new Month();
}
Based on the discussion we can say ..
Every enum constant is always static hence we can always access them using enum name

enum Month{
JAN,FEB,MAR;
}
class testenum2
{
public static void main(String... Args)
{
Month m=Month.JAN;
System.out.println(m);
}

}

output: JAN

  • Inside every enum toString() method is internally implemented to return the name of the constant.
  • We can declare enum inside of a class and outside of a class.If we declare inside of a class compiler will treat that as inner class.
    The applicable modifiers are 1. public 2. <default> 3. strictfp 4.private 5. protected 6.static 
  • if we put enum outside of the class then compiler will treat it as different class. Hence the modifier would be public,<default>,strictfp 
so
enum Month{
JAN,FEB,MAR;
}
class testenum2
{
public static void main(String... Args)
{
Month m=Month.JAN;
System.out.println(m);
}

}

This is a valid deceleration
class testenum2
{
enum Month{
JAN,FEB,MAR;
}
public static void main(String... Args)
{
Month m=Month.JAN;
System.out.println(m);
}

}

This is also a valid deceleration.
We can not declare an enum inside of a method. If so, Compiler will throw Compile time exception.

let us check out that example..
class testenum2
{
public static void main(String... Args)
{
Month m=Month.JAN;
System.out.println(m);
}
public static void somemethod();
{
enum Month{
JAN,FEB,MAR;
}
}
}
here well get the compiler error as..
E:\myProgram\testenum2.java:11: error: enum types must not be local
enum Month{
^
1 error


When I said new enum is more powerful after 1.5 version of java.In new enum, we can add constant, method, constructor, normal variables.
Even enum can contain main method. We can also invoke enum class directly from command prompt.
enum testenum21
{
JAN,FEB,MAR;
public static void main(String... Args)
{
System.out.println("Runing enum main method");
}
}

output:
C:\Documents and Settings\anichatt.APPLICATIONS>javac E:\myProgram\testenum21.java
C:\Documents and Settings\anichatt.APPLICATIONS>java testenum21
Runing enum main method

  • In addition to constant if other members(methods) other than constant are taken, list of constant should be in the written in the first line.
  • The constants must end with semicolon.
  • No constants are allowed to write after method name.
  • If the enum is having only method inside in, then the firstline should be empty statement(i.e only semi colon) 
  • empty enum is valid in java.
let us check the standards one by one..
The first line should be constant deceleration and it must end with semicolon
enum testenum21
{
JAN,FEB,MAR;

public static void somemethod()
{
System.out.println("do something");
}
}
This syntax is valid and semicolon is mandate

Let us check out if we don't give semicolon what will happen

enum testenum21
{
JAN,FEB,MAR

public static void somemethod()
{
System.out.println("do something");
}
}
The output is :
E:\myProgram\testenum21.java:4: error: ',', '}', or ';' expected
public static void somemethod()
^
E:\myProgram\testenum21.java:4: error: '}' expected
public static void somemethod()
^
E:\myProgram\testenum21.java:7: error: class, interface, or enum expected
}
^
3 errors
Let us see how it behaves with constants to declared after method:
enum testenum21
{
public static void somemethod()
{
System.out.println("do something");
}
JAN,FEB,MAR;
}
The output: Compilation error:
E:\myProgram\testenum21.java:2: error: expected
{
^
E:\myProgram\testenum21.java:4: error: ',', '}', or ';' expected
public static void somemethod()
^
E:\myProgram\testenum21.java:4: error: '}' expected
public static void somemethod()
^
E:\myProgram\testenum21.java:7: error: class, interface, or enum expected
}
^
E:\myProgram\testenum21.java:9: error: class, interface, or enum expected
}
^
5 errors




Similar compilation error will happen if and only if methods are declared inside enum without blank statement:
enum testenum21
{
public static void somemethod()
{
System.out.println("do something");
}

}
This syntax is also invalid.
The modified version will be something like written below with an empty statement.
enum testenum21
{
;
//this semicolon means an empty statement.
public static void somemethod()
{
System.out.println("do something");
}

}
Also empty enum is valid...

enum testenum21
{

}
Final points to remember:

  • Every enum is direct child of java.lang.Enum class.
  • It is an abstract class
  • Hence it becomes a base class for java enum
  • This is also a direct child of Object
  • enum implements comparable and serializable interface


Monday, May 20, 2013

How Integer.ParseInt Method Works In Java


Integer.ParseInt is very commonly used method in java.The parameter to this method will be String. So It works on String only.But what kind of String??
Those which can represent ASCII values for digit(0-...9). Remember Integer.ParseInt only works on string representation of numeric value but not something like "five".

int x=Integer.parseInt("9");
//valid
int y=Integer.parseInt("nine");
//invalid compilation error

Let us check the syntax:

  • static int parseInt(String s) // here s is the string representation of Numeric value
  • static int parseInt(String s, int radix) //This returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.
Let us check out one example:

public class parseTest{ 

   public static void main(String args[]){
      int x =Integer.parseInt("5");
      double c = Double.parseDouble("8");
      int b = Integer.parseInt("444",16);

      System.out.println(x);
      System.out.println(c);
      System.out.println(b);
   }


Output
5
8.00
1092
Sunday, May 19, 2013

Do's and Don'ts While Working With Assertions In Java


In my last post (http://www.askqtp.com/2013/05/assertion-concept-simplified-in-java.html). I have briefed how to work with assertion. Now in this post let us check out few rules and best practices to work with assertion.



Let us follow few common rules:


Do not mix business logic/programming logic with Assertion. As assertion will not run always until assertion is enabled.(Please refer here for more)

Good coding practice:
amount_withdraw(int amount)
{
//some validation
if((amount<100 || amount>=5000))
System.out.print("This amount can not be deducted");
else
//let user deduct the amount
}
Bad coding practice:
amount_withdraw(int amount)
{
//some validation
assert(amount>=100)||assert(amount<5000)
//let the user allow to get data
}

During debugging,in our program, the best place to put assertion where control does not reach or not allowed to reach.(Please refer here for more)
Good coding practice:
switch(month_val)
{
case 1: System.out.println("Jan");break;
case 2: System.out.println("Feb");break;
case 3: System.out.println("Mar");break;
......
......
case 12: System.out.println("Dec");break;
default: assert(false);
}
This is not violating 1st rule ..if the month value is anything other than 1 to 12.We need to check. Hence it is valid.

  • It is a bad practice to use assertion inside public method.As the public methods will be accessed by outside coders and method consumers, they will not be knowing whether to enable or disable assertion.
  • Secondly it is always good to have assert for private method as the method designer is local and can check the assertion
  • Thirdly, this not good to put assert while validating command line argument. This can be argument of public main method.(Please refer here for more)
Let us check with some example.
class assertTest{
public static void main(String... args)
{
asset(args.length<5):"Need more inputs";

}
}


  • All the assertion errors are child class of Error. Super class Error is unchecked during compile time hence assertion error will be unchecked.
  • All the assertion errors will be raised when the assertion will fail during run time
  •  It is legal to catch assertion error but the objective of assertion is to fail if something is not as per programmer's expectation.So it is not recommended to use.(Please refer here for more)
class assertTest{
public static void main(string... args)
{

int a=12;
-----
-----
-----
try
{
assert(a>12);
}
catch(AssertionError e)
{
//some code
}
}
}

Saturday, May 18, 2013

Assertion Concept Simplified In Java


In our day to day coding we frequently use System.out.println() statement to debug our code. This is very popular and simple way to debug our development code or test code.One problem of this approach, we can not keep these System.out.println() statement as it is. we need to remove this statement before releasing this code. It is basically overhead for any coder. To overcome this problem Java has come up with a concept called Assertion in java 1.4. prior to java 1.4, in Java 1.3 version it was declared as Indentifier.
The concepts are as follows..

  • The main advantage of assertion is like System.out.println statement, we don't need to delete these statements  as they do not get executed by default.
  • Secondly after release if any bug has come to that particular module we need to fix that. Post bug fix or during debugging again we don't need to enter System.out.println   or Assert statement. It is already available inside the code hence only enabling that will reduce our work.
  • So it exists in development and test instance but not in production environment
  • It is a better alternative for System.out.println statement.
Let us see more details:
class assertTest
{
public static void main(String[] args)
{
int assert=13;
System.out.println(assert);

}
}

Compiler will throw errors saying:

javac E:\myProgram\assertTest.java


E:\myProgram\assertTest.java:5: error: as of release 1.4, 'assert' is a keyword,and may not be used as an identifier
int assert=13;
     ^
(use -source 1.3 or lower to use 'assert' as an identifier)
E:\myProgram\assertTest.java:6: error: as of release 1.4, 'assert' is a keyword,and may not be used as an identifier
System.out.println(assert);
                            ^
(use -source 1.3 or lower to use 'assert' as an identifier)
2 errors
But if we compile against java 1.3, it will compile fine but with warning.


javac -source 1.3 E:\myProgram\assertTest.java
warning: [options] bootstrap class path not set in conjunction with -source 1.3
E:\myProgram\assertTest.java:5: warning: as of release 1.4, 'assert' is a keywor
d, and may not be used as an identifier
int assert=13;
^
(use -source 1.4 or higher to use 'assert' as a keyword)
E:\myProgram\assertTest.java:6: warning: as of release 1.4, 'assert' is a keywor
d, and may not be used as an identifier
System.out.println(assert);
^
(use -source 1.4 or higher to use 'assert' as a keyword)
3 warnings


let us see one more example..
class assertTest
{
public static void main(String[] args)
{
assert(false);
System.out.println(assert);

}
}


For this case if we compile with source -1.3, we will get compiler error. but similarly if we compile against 1.4 or upgraded version of java. We will not get the compilation error.
Conclusion: assert could have been used as an identifier in java 1.2 or java 1.3 and in java 1.4 it was promoted as a keyword.So, now ,java 1.4 onward assert can not be used as an identifier. 
Types of Assert:

  • Simple
  • Augmented
Simple Assertion:
The syntax for simple assertion is
assert(b)
Where b should be Boolean.
It signifies that up to assert statement if b value calculated as true then rest of the statements (below assert statements will be executed). If the assert value calculated as false then it will throw an assertion error and terminate the program.
let us check out one sample program
class assertTest{
public static void main(String... args)
{
int a=12;
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
assert(a>12);
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
System.out.println(a); 
}
}
The output for this program will be:

javac assertTest.java
java assertTest
output:12
now ..
java -ea assertTest
output:Assertion Error
Exception in thread "main" java.lang.AssertionError
at assertTest.main(assertTest.java:6)


Why?
By default the assertions are disabled , but by using "-ea" we are enabling the assertion.
Now if you see the output of the previous program, by seeing the console it is very tough to understand what went wrong.If it is small program then it is ok.We can identify the problem.But think about a scenario where thousands of lines are getting executed.
To get more clarity to the program java has come up with upgrade version of assertion called Augmented version assertion

Augmented Assertion:
So the main advantage of augmented version is that in the console we can append some description with assertion error.
The syntax for the augmented assertion is assert(b):c;
where b is boolean and c can be any data type
Now let us modify our previous program little bit:
class assertTest{
public static void main(String... args)
{
int a=12;
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
assert(a>12):"The value of a should be greater than 12";
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
System.out.println(a); 
}
}
javac assertTest.java
java assertTest
output:12
now ..
java -ea assertTest
The output:
Exception in thread "main" java.lang.AssertionError: The value of a should be greater than 12
at assertTest.main(assertTest.java:6)
So we are getting bit more clarity from the code.
Augment Assertion Rule-1
For this augmented assertion if the first argument is true(value of b)then the second argument c(some string output for this case) will not be evaluated.
lets see that:
class assertTest{
public static void main(String... args)
{
int a=12;
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
assert(a==12):++a;
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
System.out.println(a); 
}
}
javac assertTest.java
java assertTest
output:12
now ..
java -ea assertTest
output:12
This time the assertion passed hence ++a was not executed .

Now let us see the same example by failing the assertion condition ...this time b fails so c should get executed
class assertTest{
public static void main(String... args)
{
int a=12;
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
assert(a>12):++a;
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
System.out.println(a);
}
} 
javac assertTest.java
java assertTest
output:12
now ..
java -ea assertTest
output:Exception in thread "main" java.lang.AssertionError: 13
at assertTest.main(assertTest.java:6)

So a value is now incremented by one and got printed.
Augment Assertion Rule-2
The second argument c can be a method call,and very logically that method should not be a void type.

So the syntax should be assert(b):method_name();
let us check out via code:
class assertTest{
public static void main(String... args)
{
int a=12;
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
assert(a>12):methodxyz();
//do some calculation
//do some calculation
//do some calculation
//do some calculation
//do some calculation
System.out.println(a);
}
public static int methodxyz()
{
return 65;
}
} 

javac assertTest.java
java assertTest
output:12
now ..
java -ea assertTest
output:Exception in thread "main" java.lang.AssertionError: 65
at assertTest.main(assertTest.java:6)

Now if we change the return type of that function as void , we are going to get compile time error.
The error details:
E:\myProgram\assertTest.java:6: error: 'void' type not allowed here
assert(a>12):methodxyz();
^
1 error

Various Possible Runtime Flags
Let us check what are the flags available--

Flags

Description
-ea/-enableassertions To enable assertion in every non-system classes
-da/-diaableassrtions To disable assertion in every non-system classes
-esa/-enablesystemassertions To enable assertion in every system classes
-dsa/-deletesystemassertions To disble assertion in every non-system classes


In general normal java developers use assertion for non-system classes and java-API developers use assertion for system classes.
we can use the above flags simultaneously then JVM will consider these flags from left to right.
java -ea -esa -da -ea-esa-da -dsa -ea testAssert
the above written syntax is valid.
Let us check out few more examples:

In our real time coding we might require to enable assertion against customized classes .
if our package structure is the picture above then..

Objective

Required Code

To enable assertions only for B class

java -ea:package1:B

To enable assertions only in B and D classes

java -ea:package1:B -ea:package1.package2.D

To enable assertion everywhere inside package1 except B class

java -ea:package1... -da:package1.B

To enable assertion everywhere inside package1 except package2 classes

java -ea:package1... -da:package1.package2...

To enable assertions everywhere inside package1

java -ea:package1...

Conclusion:
So we can enable or disable assertions classwise or package wise.

Thursday, May 16, 2013

What Is HAS-A Relationship In Java??



When designing our classes , our basic tendency is to design classes maximum code re usability.  Reusable code means less work and maximum output. in this post(http://www.askqtp.com/2013/05/what-is-is-relationship-and-what-are.html) we have seen how to make code reusable by using extension.
We divide our classes into child and parent and then try to put check a IS-A relationship test.
http://www.askqtp.com/2013/05/cyclic-inheritance-prohibited.html  in this post I have shown what are the prohibited concept of java in terms of extension.
Now think about a scenario, I have a Tree class, I have Leave class and I have Root class as well.
Now Tree class has a methods like-
  • Consume_water();
  • Takes_CO2()
  • Release_O2()
  • Provide_shelter()
Again for Leaves class we can have the methods
  • Consume_water();
  • Takes_CO2()
  • Release_O2()
for Root class we can have  the methods..
  • Consume_water();
  • Provide_strength()
Now if you observe the methods of the classes(Tree,Leaves and Root) we can clearly say that Tree can be super class and Leave and Root can be subclass. By this approach we can get more reusable code.
so the structure could be for Tree class
class Tree{
public void Consume_water()
{
//consumes some water
}
Public void Takes_CO2()
{
//takes x amount of CO2
}
public int Release_O2()
{
//return some o2
}
}
For Leave class
class Leave extends Tree
{
//no methods are required as all will come from Tree
}

Similarly for Root class
class Root extends Tree
{
//no methods are required as all will come from Tree
public void Provide_Strength()
{
//provide some strength to tree
}
}

Looks like we are good to go!!!

But is it ok?? Surely no. The purpose of Tree is different from Leaves so as the corresponding methods. And to make a parent child relationship the child has to follow IS-A relationship.

Leaves IS(ARE)-A Tree?
or
Root IS-A Tree?

Both the answers are false. So this is not a valid parent child relationship. Now the next question is "if we can not extend Root or leaves to Tree , then how to reuse those codes?? if not possible the code redundancy will be higher . Isn't it?

To resolve such problem Java has come up with a concept called HAS-A Relationship.
Let us check the feature of HAS-A relationship

  • HAS-A relationship is also known as Composition or Aggregation 
  • For IS-A relationship there is a keyword available called "extends" but for HAS-A relationship there is no such keyword available,Mostly we use new.
  • Code re usability is the core concept for HAS-A relationship
Class Tree{
Leaves lvs=new Leaves();
//It means Tree has leaves reference
Root rt=new Root();
//It means Tree has Roots reference

Even though HAS-A relationship resolves problems of extension.At the same time it increases dependency between the underlying components.
It creates problem in maintenance of the code.


Wednesday, May 15, 2013

Indiblogger Organizes Ring The Bell Contest



Laws alone are not enough. Ring The Bell believes in the power of individual and collective action to challenge the habits, norms, and cultures that perpetuate violence. One person adds up to one million; one million acts add up to change.
You can be a part of the change by telling us how YOU will Ring The Bell, and inspiring your readers to do the same. What action will you take to bring violence against women to a halt? Blog about your experiences, your intentions, and make a promise!--as per indiblogger

  • There is no winner and no looser
  • Entries will be displayed on 10/6/2013
  • Campaign closes at 11:59 PM on 10/6/2013
Every participants with valid entry will get #RingTheBell mug

Original publisher of the content is indiblogger. Please go the below written link to provide your valid entry or more information about this contest.

Cyclic Inheritance: A Prohibited Approach While Designing Inheritance In Java


3 Prohibited Approaches While Designing Inheritance In Java
In my last post I have written about Inheritance and IS-A relationship here. That post will talk about what is an inheritance and how to implement that. Objective of this post is little different. This post talks about what we can not do with respect to inheritance.

Cyclic Inheritance is prohibited in java


class A extends B
{
//do some code
}
class B extends A
{
//do some code
}



let me show one more example
class A extends A{
//do some code
}

For such cases we are going to get compilation error during compilation but we need to take care while designing this class. It is said the first example of cyclic reference is generally occurred while design real time complex java project.


Second important aspect of java class design , multiple inheritance. This is not supported in java.
class A
{
//some code
}
class B
{
//some code
}
class c extends A,B
{
//some code
}

This is also one kind of Cyclic reference.

Say for this example Class B and Class C is derived from Class A and A is having a method which is overridden  in Class B and Class C. Now if a fourth class D trying to extend both the class,by the principal of inheritance both the modified method will come to D. this creates a ambiguity for compiler which one to take.

Secondly by theory, even if D is trying to override all the conflicting methods, then it has to reinvent the wheel. Code redundancy will increase. It will surely destroy the main idea behind inheritance i.e-code reusability.

This diagram is popularly known as diamond diagram for Multiple inheritance.

Multiple inheritance is not directly supported by java. But by using interface we can implement the same. A class can not extend more than one class at a time but for interface there is no such limitation.
Now wait for one more concept. Every class in java extends class Object. Class Object is the superclass for all class we create in java.It is the job for compiler to check and update the .class file accordingly.
Like if you write a class like below:
class A{
//do some activity
}

The java compiler will transform the same into a .class file as..
class A extends Object{
//do some activity
 }
Any class that does not explicitly extend another class, implicitly extends object.
This is how, java has removed diamond problem.
Monday, May 13, 2013

What Is IS-A Relationship And What Are The Rules Of IS-A Relationship In Java


In java Inheritance concept came to reduce the number of code line i.e code redundancy.

Say in an college we have some student,lecturer,principal.

Now for student we can have n column, so the corresponding class design will be..
class student{
int id
String name;
int age;
int No_of_Subject;
----
----
student(int id,string name,int age,......)
{
//constructor to initialize the value
this.id=id;
this.name=name;
this.age=age;
----
----

}
}
Similarly for lecturer class we will have...
class lecturer{
int id
String name;
int age;

----
----
lecturer(int id,string name,int age,......)
{
//constructor to initialize the value
this.id=id;
this.name=name;
this.age=age;
----
----

}
}
for principal we will have--
class principal{
int id
String name;
int age;

----
----
principal(int id,string name,int age,......)
{
//constructor to initialize the value
this.id=id;
this.name=name;
this.age=age;
----
----

}

}

now if you observe closely most of the code is redundant in nature. To get reduce redundancy we can create a common class and can derive more special classes from it.


How to design the common class?
It is interesting..we can create a parent class with all the common attribute..the common class is more abstract in nature.And the child classes are more specific class.Child classes can override the methods it got from parent class. It can also add more instance variable and child specific method. Instance variables are not overridden because they do not define behavior.So a sub class can give an inherited instance variable any value
like-
class College_person{
int id
String name;
int age;

----
----
College_person(int id,string name,int age,......)
{
//constructor to initialize the value
this.id=id;
this.name=name;
this.age=age;
----
----

}

}

Now the corresponding classes will become:
Student:
class student extends College_person {
int id
String name;
int age;

----
----
student(int id,string name,int age,......)
{
//constructor to initialize the value
super(id,name,age,......)
this.xyx=xyz;
----
----

}

}
Similarly for lecturer class we will have...
class lecturer extends College_person{
int id
String name;
int age;

----
----
lecturer(int id,string name,int age,......)
{
//constructor to initialize the value
super(id,name,age,......)
this.abc=abc;
----
----

}
}
for principal we will have--
class principal extends College_person{
int id
String name;
int age;

----
----
principal(int id,string name,int age,......)
{
//constructor to initialize the value
super(id,name,age,......)
this.tgb=tgb;

----
----

}

}
If you observe closely the super method is taking care of default value's initialization and specific values specific to the class are mentioned in the corresponding class.This is inheritance in nature.
the College_person becomes parent for all class student,lecturer and principal.

Cool isn't it???
But to perform a valid parent child relationship , the relationship has to go through a IS-A test. If it passes then only we can confirm the relationship is perfect.

here is student IS-A College_person? the answer is yes...hence College_person and student are in valid parent child relationship.Similarly it is yes for lecturer and principal

So the conclusions are--
  • IS-A relationship is valid inheritance
  • By using extends keyword we can implement IS-A relationship
  • It reduces the code redundancy but increases code re usability.
Let us see some one more example with respect to inheritance:
Class Parent:
Class Parent{
metho1()
{
}
}

Class Child:

Class Child extends Parent{
method2()
{
}

Class test:

Class test{
public static void main(String... Args)
{
//case-1
Parent p=new Parent();
p.method1();
p.method2();

//case-2
Child c=new Child();
c.method1();
c.method2();

//case-3
Parent p=new Child()
p.method1();
p.method2();

//case-4
Child c=new Parent();
c.method1();
c.method2();
}
Let us discuss case by case..
Case-1
Parent p=new Parent();
p.method1();
p.method2();

here Parent class is a independent class hence
p.method1() is a valid method call
but
p.method2() is invalid as in Parent class, method2 is unavailable
so we will get a Compilation error
Error Details:
Can not find symbol
symbol:method method2()
location:Class Parent
Conclusion:
The methods very specific to child is not available to Parent .So all child specific methods can not be called with parent reference.

Case-2
Child c=new Child();
c.method1();
c.method2();

As Child class is extending to Parent class hence by default method1 is available to Child class.
hence both the method calls are valid


Conclusion:
For the valid parent child relationship, whatever the parent is having by default will be available to child


Case-3
Parent p=new Child()
p.method1();
p.method2();

This is really interesting..We are creating object of Child of type Parent.
so p.method1() call is perfectly valid
but
p.method2() we will get compilation error
Error Details:
can not find symbol
symbol:method method2()
location:Class Parent

Conclusion:
Parent reference can hold child class object but using that variable (reference) we can not call child specific methods. We can only call parent's methods


Case-4
We will get compilation error
Error Details:
incompatible types
found Parent
Required Child



Conclusion:
Child reference can not be used to hold parent class object.
The last point is keep the IS-A direction one way, Child to parent. Java supports Child to parent direction. Not the other way round.
Square IS-A shape,but not necessarily Shape IS-A Square.
That's it for today!!.
Sunday, May 12, 2013

Types Of Encapsulation In Java


Types of Encapsulation


In my last post here I have provided the concept of Encapsulation. In this post I will describe the different types of Encapsulation.



There are two types of Encapsulation present in java..
  • Tightly Encapsulated Class
  • Loosely encapsulated class(Normal class)

Tightly Encapsulated Class
If a class is having every variable declared as private then it is called tightly encapsulated class.


class test
{

private int age;
private double salary;
private int phoneNumber;

}
Loosely Encapsulated Class
if a class is having atleast one normal variable or any variable other than private,then it is called Loosely Encapsulated Class.


class test
{

int age;
private double salary;
private int phoneNumber;

}
lets see how it works in parent child relationship:
Encapsulation mode Code
Tightly Encapsulated
class test
{
Private int age;
private double salary;
private int phoneNumber;
}
Loosely Encapsulated
class abc extends test
{
String Address;
}
Tightly Encapsulated
class xyz extends test
{
private String Name;
}

In this above example the parent class test is having 3 private variable, hence the parent class is tightly Encapsulated class.
The class abc is extending test class hence it is having total 4 variables available with it in which one is normal variable(other than private)
Private int age;
private double salary;
private int phoneNumber;
String Address;
As the string is normal variable so it does not pass the condition to be Tightly Encapsulation rule 
With the same logic the xyz class when extending to test  is a tightly Encapsulated class.

Encapsulation mode Code
Loosely Encapsulated
class test
{
String Name;
}

Loosely Encapsulated
class xyz extends test
{
private String Name;
}
Loosely Encapsulated
class abc extends xyz
{
private String Name;
}




In the above example test is the parent class which is loosely encapsulated as Name variable is not declared  as private. so class xyz when extends to test , automatically becomes loosely Encapsulated class even though it is having one private variable. Now when abc extends to xyz which is already a loosely Encapsulated hence it becomes loosely encapsulated.

So the rule is if the parent is not tightly coupled, there is no child class exists who is tightly coupled.