Spiga

Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Create JavaOutOfMemory Crash Dump

Create JavaOutOfMemory Crash Dump:


Sometime Java Application crashes due to out of memory exception. If we don't have the proper logging mechanism, we won't be able to find out why the application has crashed. We can use the Jconsole or Jprofiler to debug the memory leak. But if our application crashes after running for 3-4 hours, it will be difficult to debug without having proper dump.
Java provides some useful arguments, using which we can create the core dump using very few arguments.
We can add below arguments in the JVM to get the dump:
                java -ms32m -mx512m -XX:+HeapDumpOnOutOfMemoryError.
By adding the above argument, when the application crashes, It will create the dump with name : java_pid.hprof

Not Accessible Due To Restriction On Required Library

Not Accessible Due To Restriction On Required Library

Today, I was working on some java project in my favourite Eclipse editor, when I encountered some unknown problem. It was throwing some error that the calss cannot be accessed due to restriction on required library. This type of error occurs when some classes cannot be loaded into the projects since some restriction rules are being imposed on those classes. Similarly, I got the error like this:




How To solve this Exception:

As this error is coming because of some setting where we are excluding some files. So we need to change that settings. For that, click on the 'Windows' --> 'Preference' and then go to 'Java'-->Compiler-->'Error/Warnings' tab. You will find 'Forbidden reference (access rules):' and its value has been set to 'Error'. So we only need to do is, to change the 'Error' to 'Warning', and all is done.


Swapping the Variables Without Using Third Variables

Swapping the Variables Without Using Third Variables Using Java

In this post, we will see, how to swap the variables. There are different ways to swap the variables. The major swap algorithms are:
1) Swapping using the third varaibles.
2) Swapping using the Bitwise Operator. This is only for the Integer. This doesn't use the third variables.
3) Swapping using the Arithmetic Operations. This is also, only for the Integer. This also, doesn't use the
    third variables.
4) Swapping the Strings without using the third variables. This is little bit tricky. The logic is similar to the
    above one, i.e. Arithmetic Operations. But the Strings are immutable in the Java, so, externally we are not
    using the third variables, but internally, this uses the third variables.

Below, we have the Java Program to discuss all the above methods in details.

/**
* This class will reverse the two variables.
* Here we will see how to swap the variables using or without using the third variables.
* @author Sonu Mishra
*/
public class SwapVariables {
/**
* Swapping using the third variable and without the third variables.
* Swap two variables using the temporary variables or the third variable.
* @param a The first variable.
* @param b The Second variable.
*/

Basic TreeNode Structure in Java using Generics

Basic TreeNode Structure Using Generics

This is the basic block for creating the binary tree. We generally call this block or the structure as a Node. So this is how a single node is created. This in itself is a tree and when we pile the number of nodes, it become a big tree.

Here is the code, to create the TreeNode.

/**
* Basic Structure of the Tree. Or the Single unit of a tree.
* @author Sonu Mishra
* @param Type of the Node for the tree. Like. String, Integer
*/
TreeNode< E extends Comparable<? super E>>
{
public TreeNode< E > left;
public TreeNode< E > right;
E value;
public TreeNode(TreeNode< E > left, TreeNode< E > right, E value) {
this.left = left;
this.right = right;
this.value = value;
}
/**
* If a node doesn't have left and right child, it is leaf node.
* @param node check whether this node is leaf node or not.
* @return either true or false
*/

JAVA WAY TO WRITE TREE

JAVA WAY TO WRITE BINARY SEARCH TREE

A binary search tree (BST),is a node-based data structure in which each node has no more than two child nodes. Each child must either be a leaf node or the root of another binary search tree. The left sub-tree contains only nodes with keys less than the parent node; the right sub-tree contains only nodes with keys greater than the parent node.BST is also known as an ordered binary tree.
BST
Here is the Code to create a binary search tree in java.

import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.Stack;
/**
* Creates a Binary Search Tree.
* @author Sonu Mishra
*/
public class BinarySearchTree<E extends Comparable<? super E>>
{
private TreeNode<E> root = null;
public BinarySearchTree() {
root = new TreeNode(null, null, null);
}
public BinarySearchTree(E value) {
root = new TreeNode(null, null, value);
}
public void add(E value) {
addBefore(value, this.root);
}

How To Sort a File On the basis of the column Using Java

How To Sort a File On the basis of the column Using Java

Java Program to sort the file.
In the earlier post we have seen how to sort the CSV file. Now, we will see the generalised java code to sort the file on the basis of particular column. This code can be used for any type of files, like csv, txt etc. This can be useful to sort the big files on the basis of the column. For using this code, we need to take care of few things:
The format of the file should be like in this format:
The header or the column should be there and should be the first line of the file, else we will missed the first line.
Header/Col1: Header/Col2 : Header/Col3
a : c : e
s : a  : d
.. : .. : ...
Algorithm Used:
It’s not the rocket science, we have keep it simple and have used the simple algorithm. The each row has been considered as one java object. The column on which we have to sort is taken as the key and against this key we have the associated row data java objects as values. We sort the key and display the respective values.
For example: If we have to sort the above file on column 2, we will create two java objects which will have values:
Java@Obj1: a,c,e
Java@Obj2: s,a,d

Now, we are sorting on column 2, so for first row, key will be c and c will be mapped with the value Java@Obj1: a,c,e and for the second row: key will be a and a will be mapped with the value Java@Obj2: s,a,d. Now we will sort the keys, i.e. c and a and then we will display the mapped value for the sorted keys.

Here is the Java Class Example:

How To Sort The CSV File

How To Sort The CSV File:
Always we came across at some point where we want to sort the data, or we want to compare similar kind of data. So, in this post, we will focus on some of the quick ways to sort the data of the CSV file. Windows provide the SORT command, and using that command we can sort the data of the files.
Sorting Using Windows SORT Command
1)      You can use the sort command to sort the files. In the command prompt, type following:
a.       Sort  Input_filename  : This will sort the file and will display the output on the console. This will sort the file on the basis of first column. Let’s suppose your input is :
Input:
1              g              k
3              f              d
2              c              a
                                             Output will be:
sort Book.csv
1,g,k
2,c,a
3,f,d
b.      Sort  Input filename Output Filename : This will sort the input file data and will store the result in the OutputFile.
Example:     sort Book.csv  outputBook.csv
c.       Sort  Input_filename Output_Filename /+Column_Number: This will sort the file on the basis of column number. If we provide column number as 2, it will sort the file on the basis of column 2nd column. E.g.:
sort Book.csv /+2
2,c,a
3,f,d
1,g,k
2)      You can write the Customized java written program also to sort as per requirement. In the next post we will see the customized Java Program to sort the files. This one is my favourite.
3)      There are several software’s available in the market for this and as well as other purposes.

Java Unsupported Class Version Error-II

Java Unsupported Class Version Error - II

In the last post we have seen about the Java Unsupported Class Version. In this post we will see more on that.

What is UnSupportedClassVersionError in Java?

Java.lang.UnsupportedClassVersionError is a subclass of java.lang.ClassFormatError. This is a kind of linking error which occurs during linking phase accordingly java.lang.ClassFormatError has also derived from java.lang.LinkageError. As the name suggests "UnSupportedClassVersionError" so it’s related to unsupported class version, now questions comes what is class version in Java? Well every source file is compiled into class file and each class file has two versions associated with it, major version and minor version. Version of class file is represented as major_version.minor_version. This version is used to determine format of class file in Java.
According to Java Virtual Machine specification, “A JVM implementation can support a class file format of version v if and only if v lies in some contiguous range Mi.0 v Mj.m. Only Sun can specify what range of versions a JVM implementation conforming to a certain release level of the Java platform may support.” For example: JDK 1.2 supports class file formats from version 45.0 to version 46.0 inclusive. So if a class file has version 48.0 it means that major version of class file is "48" and minor version is "0", which tells us that JDK 1.4 has been used to compile and generate that class file


How to fix UnSupportedClassVersionError

Now we know the root cause of UnSupportedClassVersionError that we are using a lower JVM for running the program. But major problem is that stack trace of UnSupportedClassVersionError will not tell you for which class it’s coming. So if you are using multiple third party jars in your application you find that it comes at a particular part when JVM tries to load a class from a particular jar. anyway we all know that latest version of JDK is 1.6 so maximum version of class file could be generated by JDK 6, so by using JDK 6 we can solve UnSupportedClassVersionError, but many times its not easy to just move to higher JDK version. So I would suggest:
1) Find out due to which jar or class file this UnSupportedClassVersionError is coming?
2) Try to compile source code of that jar with the JDK version you are using to run your program, if source is available.
3) If you don't have source try to find the compatible version of that library.
4) Increase the JRE version you are using to run your program.

When UnSupportedClassVersionError in Java comes:


So now we got the theory behind class file format and major and minor version of class file in Java. Now a million dollar question is when UnSupportedClassVersionError in Java does occur? precise answer of this is "When JVM tries to load a class and found that class file version is not supported it throws UnSupportedClassVersionError and it generally occurs if a higher JDK version is used to compile the source file and a lower JDK version is used to run the program. for example if you compile your java source file in JDK 1.5 and you will try to run it on JDK 1.4 you will get error "java.lang.UnsupportedClassVersionError: Bad version number in .class file [at java.lang.ClassLoader.defineClass1(Native Method)]".
But its important to note is that vice-versa is not true "you can compile your program in J2SE 1.4 and run on J2SE 1.5 and you will not get any UnSupportedClassVersionError". When a higher JDK is used for compilation it creates class file with higher version and when a lower JDK is used to run the program it found that higher version of class file not supported at JVM level and results in java.lang.UnsupportedClassVersionError

Major Class Versions of Various JDK
Following are the major version of class file format in standard JDK environment.
JDK 1.1 = 45
JDK 1.2 = 46
JDK 1.3 = 47
JDK 1.4 = 48
JDK 1.5 = 49
JDK 1.6 = 50

Java Unsupported Class Version Error

Java Unsupported Class Version Error

Java Unsupported Class Version Error occurs when we try to compile the class which has a jar file attached in its classpath and that jar file has been compiled with higher version of java then the one with which  we are trying to compile the class.

This error comes on using different java versions for compilation and execution of java program. Therefore set the path of one java version and use it for compilation and execution.

java.lang.UnsupportedClassVersionError: XXXX (Unsupported major.minor version 49.0)

        at java.lang.ClassLoader.defineClass0(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:539)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:251)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:55)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:194)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:187)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:289)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:274)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:235)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:302)

 If you get the above errors, do the following:
       1) Check the jar file attached in the classpath.
       2) Use the higher version (or equal but not lesser) of java for compiling the class then used for creating  the jar.
      3) Set the path of one java version and use it for compilation and execution.

Getting Java Compilation Error

Getting Java Compilation Error When Compiling JDBC with java 1.5

When we try to compile  some java project with Java 1.5 compiler, we get the error

[javac] Please remove or make sure it appears in the correct subdirectory of the classpath.
[javac] import oracle.sql.ARRAY;
[javac]                              ^
[javac] 1 error

This is because java 1.5 compiler doesn't support oracle.sql.ARRAY, so to remove this compilation error we need to upgrade the java compiler from 1.5 to java 1.6. The Java compiler 1.6 support all this classes as well as the old classes of java 1.5. Java 1.6 can be downloaded from Java Sun website.