Archive for the ‘java’ Category

Finding longest palindrome in a string

Posted by guptaradhesh on August 26, 2013

Here is an elegant code I found.

string expandAroundCenter(string s, int c1, int c2) {

  int l = c1, r = c2;
  int n = s.length();
  while (l >= 0 && r <= n-1 && s[l] == s[r]) {
  return s.substr(l+1, r-l-1);
string longestPalindromeSimple(string s) {
  int n = s.length();
  if (n == 0) return “”;
  string longest = s.substr(0, 1);  // a single char itself is a palindrome
  for (int i = 0; i < n-1; i++) {
    string p1 = expandAroundCenter(s, i, i);
    if (p1.length() > longest.length())
      longest = p1;
    string p2 = expandAroundCenter(s, i, i+1);
    if (p2.length() > longest.length())
      longest = p2;
  return longest;
source: here

Posted in java, puzzles/ algorithms, tech | Tagged: , , , | Leave a Comment »

Why char array is preferred over String for storing password?

Posted by guptaradhesh on August 23, 2013

String is immutable in java and stored in String pool. Once it’s created it stays in the pool until unless garbage collected, so even though we are done with password it’s available in memory for longer duration and there is no way to avoid it. It’s a security risk because anyone having access to memory dump can find the password as clear text.

If we use char array to store password, we can set it to blank once we are done with it. So we can control for how long it’s available in memory that avoids the security threat with String.

Posted in java, tech | Tagged: , , , | Leave a Comment »

Print matrix in a sprial order

Posted by guptaradhesh on August 22, 2013


Recursive Solution (Java):

public class PrintMatrixSpiral
 public static void main(String[] args)
  int[][] matrix =
  { 2, 4, 6, 2, 5, 7 },
  { 2, 5, 7, 8, 9, 3 },
  { 6, 4, 7, 3, 5, 7 } };


 public static void printSpiral(int[][] matrix)
  printSpiral(matrix, 0);

 private static void printSpiral(int[][] matrix, int depth)
  if (matrix == null && matrix.length == 0)
  int rows = matrix.length;
  int cols = matrix[0].length;
  if (2 * depth > Math.min(rows, cols))
  for (int i = depth; i < cols - depth - 1; ++i)
   System.out.print(matrix[depth][i] + ",");
  for (int i = depth; i < rows - depth - 1; ++i)
   System.out.print(matrix[i][cols - depth - 1] + ",");
  for (int i = rows - depth; i > depth; --i)
   System.out.print(matrix[rows - depth - 1][i] + ",");
  for (int i = rows - depth - 1; i > depth; --i)
   System.out.print(matrix[i][depth] + ",");
  printSpiral(matrix, ++depth);

Posted in java, puzzles/ algorithms, tech | Tagged: , , , , | Leave a Comment »

Permutations of a String

Posted by guptaradhesh on February 4, 2013

public  static void permutation(String str) { 
    permutation("", str); 

 private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0) System.out.println(prefix);
    else {
        for (int i = 0; i < n; i++)
           permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));

Posted in java, puzzles/ algorithms | Tagged: , , , | 1 Comment »

Difference between ClassNotFoundException and NoClassDefFoundError?

Posted by guptaradhesh on February 16, 2012

ClassNotFoundException is thrown when the reported class is not
found by the ClassLoader in the CLASSPATH. It is thrown when an application tries to load in a class through its string name using:

  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader.
  • The loadClass method in class ClassLoader.

but no definition for the class with the specified name could be found.

NoClassDefFoundError is Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found

Posted in java | Tagged: , , | 1 Comment »

What is serialVersionUID in Java?

Posted by guptaradhesh on February 16, 2012

The serialVersionUID is a universal version identifier for a Serializable class. Deserialization uses this number to ensure that a loaded class corresponds exactly to a serialized object. If no match is found, then an InvalidClassException is thrown.

The docs for java.io.Serializable have a great explaination saying:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender’s class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named “serialVersionUID” that must be static, final, and of type long:

static final long serialVersionUID =543543543545L;  

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class–serialVersionUID fields are not useful as inherited members.

Posted in java | Tagged: , , | Leave a Comment »

Ant “Unable To Locate tools.jar”

Posted by guptaradhesh on April 6, 2011

While running an ant, if we get an error/warning that says unable to locate tools.jar, then we are seeing the wrong java version from the one you set in JAVA_HOME.

i.e. Unable to locate tools.jar. Expected to find it in C:\Program Files\Java\jre6\lib\tools.jar

Just try changing your JAVA_HOME environment variable. In most cases either JAVA_HOME is not set or is set to “\jdk5\bin”, and they have to remove the “\bin” part, because ant looks for “%JAVA_HOME%\bin\java*”. This is because ant looks for “C:\Program Files\Java\jdk5\bin\bin\java.exe”.

Reference: web

Posted in java | Tagged: , | 2 Comments »

“Java and Oracle, One Year Later”

Posted by guptaradhesh on April 3, 2011

Screen shot 2011-02-18 at 11.12.58.png The TechCast “Java and Oracle, One Year Later” is now available on damand. Ajay Patel and Justin Kestelyn talks about a wide range of topics, changes, and plans since the Sun acquisition happened a year ago.

Some Key Notes:

– “One key thing we have learned … Java is not just a platform, it is also an ecosystem, and you can’t have an ecosystem without a community.”

– “It’s not just about Oracle anymore, it’s about Java, the technology, the community, the developer base, and how we work with them to move the innovation forward.”

– On the JDK and SE: “… aggressively moving forward, JDK 7 is now code complete … looking good for getting JDK 7 out by summer as we promised. Started work on JDK 8, Jigsaw and Lambda are moving along nicely, on track for JDK 8 release next year … good progress.”

– On Java EE and Glassfish: “… Very excited to have Glassfish 3.1 released, with clustering and management capabilities … working with the JCP to shortly submit a number of JSRs for Java EE 7 … You’ll see Java EE 7 becoming the platform for cloud-based development.”

– “You will see Oracle continue to step up to this role of Java steward, making sure that the language, the technology, the platform … is competitive, relevant, and widely adopted.”

Posted in java, markets | Tagged: , | Leave a Comment »

change author name in ECLIPSE (for javadocs)

Posted by guptaradhesh on March 5, 2011

its pretty simple..

1- open eclipse.ini file in the eclipse directory

2- add the following line after -vmargs line

-Duser.name=your name

You might have to restart Eclipse after saving.

Happy Coding!

Posted in java, tech | Tagged: , , , , | Leave a Comment »

Association, Aggregation, Composition

Posted by guptaradhesh on February 15, 2011

[Here is the easiest explanation I found while gazing on web]

When we have only one relationship between objects, that is called Association. Aggregation and Composition both are specialized form of Association. Composition is again specialize form of Aggregation.

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.

Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Let’s take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about “has-a” relationship.

Composition is again specialize form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete. Let’s take another example relationship between Questions and options. Single questions can have multiple options and option can not belong to multiple questions. If we delete questions options will automatically delete.


Posted in java, tech | Tagged: , , | Leave a Comment »