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.

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.

Saturday, May 11, 2013

Difference Between JAR,WAR and EAR



if there are many files and they are dependent in nature for your program. It is very tough to put them in classpath to access them run time.For solving this problem java has come up with archiving concept. It's concept is simple. put all the classes in a zip file and make that available in classpath while running the java code.

Again consider one more example, if our program contains of many HTML files,images files etc. so to download one single file, it is required to download all the components of the file. And for that we require so many HTTP connections to get all those. It will take more time and patience. so zip file is a nice concept .

Mainly we have 3 types of zip file in java..
  1. jar (java archive file)
  2. war (web archive file)
  3. ear (enterprise archive file)

Let's check out the difference between them:


Jar WarEar
  1. contains .class files
  2.  A JAR file encapsulates one or more Java classes, a manifest, and a descriptor.
  3. JAR files are the lowest level of archive
  4. It is having MANIFEST.MF in META-INF folder
  5. extension .jar
  1. it contains mostly web application resources like HTMl,CSS,JSP,Servlets,images,beans etc
  2. It is having web.xml to configure
  3. It helps to maintain,deployment and shipping very easy for web application
  4. extension .war
  1. We use it on enterprise application. mainly combination of wars and jars
  2. It is having xml based deployment descriptor to configure all
  3. It helps to maintain,deployment and shipping very easy for enterprise  application
  4. extension .ear
Friday, May 10, 2013

Difference Between Path And Classpath In Java


Let us understand what is path in java..
In java path is the variable which holds the specific location of the binary executable files of java like- java/javac etc

How to set path--
Well there are two ways by which we can set path
  • Permanently set path via environment variable-(click here for more)
  • Temporary for a session.
we will check out how to set path temporarily ..


Temporary settings:
1. Go to start-->run -->type cmd
2. click on ok. It will open command prompt for windows

3. Now navigate to the path where you have installed your java(JDK installation folder)
it might be C:\Program Files\java\jdk<<version>>\
4. Copy the path and come back to command prompt.
5. Type the below written command:

set path=C:\Program Files\Java\jdk1.7.0_21\bin\

 

you are done!! Now you can write any java program and compile the same.

Classpath:

Classpath is the variable which is used to tell JVM from where all my classes are residing. and from which location it has to pick the required .class files.
How to set classpath:
Please go through ..
1. http://www.askqtp.com/2012/01/setting-class-path-in-java-in-windows.html
   for permanent settings
2. http://www.askqtp.com/2013/05/what-is-classpath-and-how-to-set-that.html
   for temporary settings

How To Check System Configuration Before Proceeding With Our Code In Java


The objective of this post is to check system configuration for running java codes. when it is exactly required??
Well lets say I have developed a program in Java-1.6, and used some code which got enhanced in that particular version.
like-
  • Native platform Security (GSS/Kerberos) integration.
  • Java Authentication and Authorization Service (JAAS) login 
  • module that employs LDAP authentication
  • New Smart Card I/O API
  • Native security services technical article
Lets assume that this program will run on java -1.5 . Definitely the compatibility will not be there.

As per stack over flow...
The compiler is not backwards compatible because bytecode generated with Java6 JDK won't run in Java 1.5 jvm (unless compiled with the -target 1.5 flag). But the JVM is backwards compatible, as it can run older bytecodes.

So I guess they chose to consider the compatibility from the point of view of javac (as it is the part specific to the JDK), meaning that the bytecode generated can be run in future releases of the jvm (that is more related to the JRE, but also bundled in the JDK).

In brief, we can say:

    JDK's are (usually) forward compatible.
    JRE's are (usually) backward compatible.
Let us also assume , my program needs the below written...
  • Java version-java 1.7
  • OS-Windows XP
  •  and I have some requirement where the .class file should be in C drive.
if all of the above are matching then our program is good to go else we will simply say with the  configuration, this program will not run...

Lets see how:
In my previous post here..http://www.askqtp.com/2013/05/how-to-get-system-properties-in-java.html
I have shown how to get system properties.
From the list of properties we are only going to choose
  • java version
  • OS 
  • class. path



import java.util.Properties;


public class systemTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  boolean b=false;
  Properties p=System.getProperties();
  p.list(System.out);
//get all the list of properties.
                String path=p.getProperty("java.class.path");
  String os=p.getProperty("os.name");
  String javaVersion=p.getProperty("java.specification.version");
  System.out.println(path);
  System.out.println(os);
  System.out.println(javaVersion);
  if((path.indexOf("C:\\")>=0||path.equals(".")) && os.equals("Windows XP") && javaVersion.equals("1.7"))
    b=true;
//checks the path contains C drive,also checks for OS or java version
                  if(b)
    System.out.print("We can proceed");
    else
    System.out.print("We can not proceed");
      }
       
}

output:
. (dot means present working directory.)
Windows XP
1.7
We can proceed

Now if the java version is 1.4 (running)in the client machine. It should say "We can not proceed"

By this way we can achieve the precondition cases for running our tests.

Thursday, May 9, 2013

How To Get System Properties In Java


For each system , system properties information (persistent ) will be maintained in the form of system properties. Mainly we use properties to maintain system configuration.The system class will maintain a Properties object to get all the details.

In short it is nothing but a key value pair in the form of string.
The important aspect of System property is "to access any value from it , it requires current security manager's approval"

More details can be found here:

Lets see an example:
import java.util.Properties;
public class systemTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Properties p=System.getProperties();
  p.list(System.out);
  
 }
}

output:
java.vm.specification.vendor=XYZ Corporation
user.variant=
os.name=Windows XP
sun.jnu.encoding=Cp1252
java.library.path=C:\Program Files\Java\jdk1.7.0_21\bin...
java.specification.name=Java Platform API Specification
java.class.version=51.0
sun.management.compiler=HotSpot Client Compiler
os.version=5.1
user.home=C:\Documents and Settings\anichatt.AP...
user.timezone=
java.awt.printerjob=sun.awt.windows.WPrinterJob
file.encoding=Cp1252
java.specification.version=1.7
user.name=anichatt
java.class.path=E:\myProgram\
java.vm.specification.version=1.7
sun.arch.data.model=32
java.home=C:\Program Files\Java\jdk1.7.0_21\jre
sun.java.command=systemTest
java.specification.vendor=xyz Corporation
user.language=en
awt.toolkit=sun.awt.windows.WToolkit
java.vm.info=mixed mode, sharing
java.version=1.7.0_21
java.ext.dirs=C:\Program Files\Java\jdk1.7.0_21\jre...
sun.boot.class.path=C:\Program Files\Java\jdk1.7.0_21\jre...
java.vendor=xyz Corporation
file.separator=\
java.vendor.url.bug=http://bugreport.sun.com/bugreport/
sun.cpu.endian=little
sun.io.unicode.encoding=UnicodeLittle
sun.desktop=windows
sun.cpu.isalist=pentium_pro+mmx pentium_pro pentium+m...

 Below are the system properties that can be tracked using system class's Property Object.


Key Meaning
"file.separator" Character that separates components of a file path. This is "/" on UNIX and "\" on Windows.
"java.class.path" Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
"java.home" Installation directory for Java Runtime Environment (JRE)
"java.vendor" JRE vendor name
"java.vendor.url" JRE vendor URL
"java.version" JRE version number
"line.separator" Sequence used by operating system to separate lines in text files
"os.arch" Operating system architecture
"os.name" Operating system name
"os.version" Operating system version
"path.separator" Path separator character used in java.class.path
"user.dir" User working directory
"user.home" User home directory
"user.name" User account name
taken from docs.oracle.com
How to get single property from the list??
say i want to retrieve OS name and current location of the class file.
so the corresponding code:
import java.util.Properties;
public class systemTest {
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Properties p=System.getProperties();
  //p.list(System.out);
  System.out.println(p.getProperty("java.class.path"));
  System.out.println(p.getProperty("os.name"));
  }

}

output:
. (dot -it means current working directory)
Windows XP

Wednesday, May 8, 2013

What Is Classpath And How To Set That In Java


In java, the source file is written in normal text and saved with .java  extension.
The compiler upon invoked by the command javac creates a .class file for the corresponding .java file.

The JVM during run time reads the .class file ,performs certain checks and execute the same.

if the .class file is placed under ...../java/bin/ folder . It is not required to mention classpath. But when our project becomes larger, it is required to create some folder structure and place all the necessary .class file at one place,it is extremely required for JVM to know where the .class files resides.

This post will talk about the different settings how to set classpath in different way.


Classpath settings
How to set classpath for java...
  • In my previous post here, I have shown how to set classpath permanently from environment variable
  • Temporary for a command session
    set classpath=%classpath%;E:\myPrograms\
    //%classpath% is to keep what ever is already present in the classpath;Now provide the required classpath followed by a semi colon(;)
    
    This command is valid for the command prompt it has been set. If you open another command prompt the java command will not work.

  • One more option is also available for setting classpath, valid for a single command.
    java -cp <<full classpath>> <<name of the class>>
    like-java -cp E:\myProgram Test123
    
The scope of the process:
  • Set globally--across the command prompts
  • Set classpath at command prompt--only for that command prompt session
  • Set classpath on command level-only for that command
While going for the 3rd option there are things to remember:
  • -cp will not consider present working directory by default. We need to include dot(.) to get present working directory into classpath
  • Always use full path while working with -cp
  • if the same class file available in different directories then JVM will read from left to write for the -cp command and whenever the first occurrence of the class is available JVM will pick that and execute. But the next sequence will not be picked again.
 so in drive C,D,E three test class is available.
Now if we provide
java -cp C:;D:;E: test 
only C: drives test will be executed,D and E will be ignored.
similarly if we provide
java -cp D:;C:;E: test 
only D: drives test will be executed,C and E will be ignored.