Tips to fallow while doing JAVA code


  • Counting down (i.e. for (int i=n; i>0; i–)) is twice as fast as counting up: my machine can count down to 144 million in a second, but up to only 72 million.
  • Calling Math.max(a,b) is 7 times slower than (a > b) ? a : b. This is the cost of a method call.
  • Arrays are 15 to 30 times faster than Vectors. Hashtables are 2/3 as fast as Vectors.
  • Use System.arraycopy(firstArray, 0, secondArray, 0, firstArray.length) method instead of iterating the first array and copying into second array.
  • Use compound assignment operators (+=, -=, *=, and /=) instead of using normal operators.
  • Ex: a = a+b takes longer time to execute when compared to a += b. In fact, these cause different Java byte codes to be generated.
  • Eliminate unnecessary code in the loops and you should avoid declaring variables unnecessarily within loops.
  • Use int instead of other primitive types because operations performed on int primitives generally execute faster than for any other primitive type supported by Java, so you should use int values whenever possible; char and short values are promoted to int automatically before arithmetic operations.
  • Use notify() instead of notifyAll(), notify will execute faster than notifyAll().
  • When joining couple of Stings use StringBuffer instead of String.
  • Don’t try to convert Strings to upper or lower case for String comparison.
  • In the String Class prefer charAt() method instead of startsWith() method. From performance perspective, startWith() makes quite a few comparisons preparing itself to compare it’s prefix with another string.
  • Don’ t initialize the public instance variable in constructor if they already initialized outside the constructor. Because all public initialized instance variables are again initialized in constructor by default.
  • Vector provides the following methods to insert elements.
    addElementAt( e, index)
    addElement (e)
    add(e)
    add(index, e)
  • Out of these try to avoid using methods, addElementAt( e, index) and add(index, e). The way these methods work is , all the elements are moved down between the insertion point and the end of the vector, making space for the new Element. The same works for deleting element at a Particular index. If possible, if these features are required, then try to use a different Data Structure if possible.
  • If the approximate size of the Vector is know initially then use it. Instead of declaring Vector as,

Vector v = newVector();
declare it as,Vector v = new Vector(40);
or  Vector v = new Vector(40,25) ;

  • This method indicates initial capacity of Vector is 40 and increment by 25 elements per expansion.The way the Vector is expanded is, a new Vector of double the size of currentVector is created, all the Elements in the old Vector is copied to the new Vector and then the old Vector is discarded. (During GC). This has major effect on performance.

Enable JMX Remote port in WebSphere


By default JMX remote port is not enabled in WebSphere, We have to manually enable the JMX remote port. Here I am giving some steps to enable the JMX remote port in Websphere.

This has been done with Websphere 7.0.
After installation of web sphere application server 7.0, fallow the fallowing steps to configure Remote JMX port.

STEP 1:
Login to Admin console of the web sphere any profile(server), short cut will be available in start menu programs.
deploy the PerfServletApp.ear application if not deployed already.
GO TO Applications IN LEFT PANE CLICK WebSphere Enterpise Applications TO CHECK PerfServletApp.ear IS DEPLOYED OR NOT.
IF NOT THEN CLICK New Application UNDER Applications. BROWSE FROM WebSphere directory -> AppServer -> InstallableApps.
FOLLOW THE STEPS.
STEP 2:
Enable the PMI Data and set all the statistics enabled.
GO TO Monitoring and Tuning IN LEFT PANE CLICK ON Performance Monitoring Infrastructure(PMI) IN CONIFGURATION TAB ENABLE THE PMI AND
SET THE ALL STATISTICS. ALSO SET THE ALL STATISTICS IN Runtime Tab. SAVE THE CHANGES.

STEP 3:

Set the generic jvm argument = -Djavax.management.builder.initial= -Dcom.sun.management.jmxremote

in Severs -> Server Types -> WebSphere Application Servers
shows the servers list. click on the server you want.
In the right pane -> Server Infrastructure -> Java and Process Management  click on Process definition, again in Additional Properties of Configuration tab
click on Java Virtual Machine. put the -Djavax.management.builder.initial= -Dcom.sun.management.jmxremote in Generic Jvm Argument field.
and save changes.

STEP 4:

To enable the JMX remote port open the below properties file and add the code below.

FILE : WebSphere directory \AppServer\java\jre\lib\management\management.properties

CODE :
com.sun.management.jmxremote.port=9001
com.sun.management.jmxremote.ssl=false
com.sun.management.jmxremote.authenticate=false

STEP 5:

SAVE THE MASTER DATA AND STOP THE SERVER AND START THE SERVER TO LOAD THE CHANGES………

Enabling JMX port in JBOSS


By default JMX port is not enabled in the JBOSS. If you want enable the JMX port, add the falowing properties
in run.bat file which located in bin directory of the %CATALINA_HOME%.

set JAVA_OPTS= %JAVA_OPTS% -Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl
-Djboss.platform.mbeanserver -Dcom.sun.management.jmxremote.port=8007
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

To add the above propertis in run.bat fallow the steps

1. Find for the fallowing code:

set JAVA_OPTS=%JAVA_OPTS% -Xms128m -Xmx512m

2. Replace the above code with :

set JAVA_OPTS=%JAVA_OPTS% -Xms128m -Xmx512m -Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl -Djboss.platform.mbeanserver -Dcom.sun.management.jmxremote.port=8007 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false

Enabling JMX port in Tomcat


By default JMX port is not enable in the Tomcat.
If you want to enable the JMX port, add the fallowing properties
in catalina.bat file which located in bin directory of the %CATALINA_HOME%.

Add the fallowing properties as starting line of catalina.bat

set JAVA_OPTS= %JAVA_OPTS% -Dcom.sun.management.jmxremote.port=7009
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false

SCJP Questions


1

Class C {

public static void main(String[] args) {

int[]a1[]=new int[3][3]; //3

int a2[4]={3,4,5,6}; //4

int a2[5]; //5

}}

5.None of the above

What is the result of attempting to compile and run the program ?.

1.compiletime error at lines 3,4,5

2.compiltime error at line 4,5

3.compiletime error at line 3

4.Runtime Exception

Ans: 2

Explanation:

no value shoud be specified in the rightsidebrackets when constructing an array

Difference between Abstract Class and Interface:


Most of the people confuses with Abstract class and interface. Here I am planning to share some information with examples, I hope this will help you more………

Simple abstract class looks like this:

public abstract class KarateFight{

public void bowOpponent(){

//implementation for bowing which is common for every participant       }

public void takeStand(){

//implementation which is common for every participant

}

public abstract boolean fight(Opponent op);

//this is abstract because it differs from person to person

}

The basic interface looks like this:

public interface KarateFight{

public boolean fight(Opponent op);

public Integer timeOfFight(String person);

}

The differences between abstract class an interface as fallows:

1.  Abstract class has the constructor, but interface doesn’t.

2.  Abstract classes can have implementations for some of its members (Methods), but the interface can’t have implementation for any of its members.

3.  Abstract classes should have subclasses else that will be useless..

4. Interfaces must have implementations by other classes else that will be useless

5. Only an interface can extend another interface, but any class can extend an abstract class..

6.  All variable in interfaces are final by default

7. Interfaces provide a form of multiple inheritance. A class can extend only one other class.

8. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.

9.  A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.

10. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

11. Accessibility modifier(Public/Private/internal) is allowed for abstract class. Interface doesn’t allow accessibility modifier

12.  An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface can not implement methods.

13.  An abstract class can contain fields, constructors, or destructors and implement properties. An interface can not contain fields, constructors, or destructors and it has only the property’s signature but no implementation.

14. Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces.

15.  Abstract scope is upto derived class.

16.  Interface scope is upto any level of its inheritance chain.

Other Useful Links:

What are the differences between object and instance?

What are the differences between EAR, JAR and WAR file?

Differences between callable statements, prepare statements, createstatements

The basic Properties of Interface


1. Interface must be declared with the key word ‘interface’.

2. All interface methods are implicitly public and abstract. In another words you dont need to atually type the public or abstract modifiers in the metod declaration, but method is still allways public and abstract.

3. All variables defined in an interface is public, static, and final. In another words, interfaces can declare only constants , not instance variables.

4. Interface methods must not be static.

5. Because interface methods are abstract, they cannot be marked final, strictfp, or native.

6. An interfaces can extend one or more other interfaces.

7. An interface cannot implement another interface or class.

8. interface types can be used polymorphically.

SCJP


This is the day i am start posting the topics on scjp. Basically i am planning to prepare for the SCJP (Sun Certified Java programmer), So that I am happy to share my preparation, I am happy to discuss each and every important point which i feel, I want to figure out the success tips to help others.

To day i am happy that  strongly decided to complete the exam in three months. Lets see what will happen.

I hope I will get your support to success.

Lets wish me once for the success.

Differences between Object and Instance


There is a lot of discussions on this topic over the internet. Some of the people says both are same and some of other says both are different. Here I am planning to share my overall view on this topic. As per my knowledge both are looks same but different. Here are the some useful points:

  • Instance is Logical but object is Physical means occupies some memory.
  • We can create an instance for abstract class as well as for interface, but we cannot create an object for those.
  • Object is instance of class and instance means representative of class i.e object.
  • Instance refers to Reference of an object.
  • Object is actually pointing to memory address of that instance.
  • You can’t pass instance over the layers but you can pass the object over the layers
  • You can’t store an instance but you can store an object
  • A single object can have more than one instance.
  • Instance will have the both class definition and the object definition where as in object it will have only the object definition.

Syntax of Object:

classname var=new classname();

But for instance creation it returns only a pointer refering to an object, syntax is :

classname varname;

 

Other Useful Links:

Difference between Abstract Class and Interface

What are the differences between EAR, JAR and WAR file?

Differences between callable statements, prepare statements, createstatements

Jar file Vs Executable Jar file


Jar file is the combination of compiled java classes.
Executable jar file is also be combination of compiled java classes with Main class.

Normal jar file can be created as

C:\> jar -cvf TestNew.jar

But while creating executable jar file we have to specify the Main-Class in a manifest file. Following are the steps to fallow while creating the executable jar file. Here its explained with a simple class in a test package.

Step 1: create a java class TestNew under package test

package test;
public class TestNew{
     public static void main(String a[]){
         System.out.println("Hello world");
     }
}

Step 2: compile the class with following command.

C:\>javac TestNew.java -d .

Note: Once you run the TestNew class you have to get “HelloWorld” in the console. To run use fallowing command.

C:\>java test.TestNew

Step 3: Create a “mainClass” file in the directory where your test folder is located . This file contains a single line specifying where the main Class is to be found in the jar file. Note that I use the package specification. Here is the single line:

Main-Class: test.TestNew
Note: specify the single line only don't specify anything

Step 4: Create the jar using fallowing command

C:\>jar cmf mainClass test.jar test

Where “c” represents the create that you are going to “create”, “m” specifies the manifest file mainClass (which adds information to the jar file on where the main class will be found) and “f ” refers to “file”.

Note: The file has to be created in your folder with the name test.jar

To view the content of the jar file you can use the fallowing command

C:\>jar tf test.jar

It displays as:

META-INF/
META-INF/MANIFEST.MF
test/
test/TestNew.class

To execute the jar file you can use the following common.

C:\>java -jar test.jar

o/p:

Hello world