Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Sunday, February 10, 2013

Difference between ClassNotFound exception and NoClassDefinition

ClassNotFoundException comes when JVM tries to load a class at runtime dynamically means you give the name of class at runtime and then JVM tries to load it and if that class is not found in classpath it throws ClassNotFoundException.  ClassNotFoundException comes on Runtime when requested class is not available in classpath and mainly due to call to Class.forName () or Classloader.loadClass () or ClassLoader.findSystemClass ().

While in case of NoClassDefFoundError the problematic class was present during Compile time and that's why program was successfully compile but not available during runtime by any reason.



Thread life cycle


Saturday, February 9, 2013

why String is immutable

Immutable means that the current object is unchangeable & operations on it will return another new object which you have to catch to see the changes.  String class is such class where methods like toUpperCase() etc will return String object which you have to save in a new variable....
however if their is a long string of operations & you dont want to make many variables
you can always use StringBuffer or StringBuilder class where all operations are performed on original object without the need to create multiple new objects.......


String s1= "samba";
s1.toUpperCase();
then s1 will not automatically point to a new String variable at another memory location.
 s1 would still be pointing to the original String object, and the new String object that comes out of toUpperCase() will be ignored and thrown away.  If you wanted s1 to point to the new String, you must assign it explicitly:

Assign the result of the method to name
s1= s1.toUpperCase();

example:


package com.samba.org.sample;

public class StringImmutableTest {

public StringImmutableTest()
{
System.out.println("StringImmutableTest.StringImmutableTest()");
}

public static void main(String[] args)
{

String s1="samba";

System.out.println("Before String Operation hash code:"+s1.hashCode());
s1.toUpperCase();
System.out.println("After String Operation but nt assigned to any variable hashcode:"+s1.hashCode());
s1=s1.toUpperCase();
System.out.println("After String Operation and assigned to variable hashcode:"+s1.hashCode());

/*OUTPUT
*
* Before String Operation hash code:79649854
* After String Operation but nt assigned to any variable hashcode:79649854
* After String Operation and assigned to variable hashcode:78664766
                 *
*/
}

}





Thursday, February 7, 2013

stringbuffer vs stringbuilder

StringBuilder was introduced in JDK 1.5. What's the difference between StringBuilder and StringBuffer? According to javadoc, StringBuilder is designed as a replacement for StringBuffer in single-threaded usage. Their key differences in simple term:
  • StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.

  • StringBuilder has better performance than StringBuffer under most circumstances.

  • Use the new StringBuilder wherever possible.

What happens when a Static Variable has the same name as a Static Class in Java?


public
class Test {
public static void main(String[] args) {
System.out.println(X.Y.Z);
  }
}

class
X {
static class Y {
static String Z = "Black";
}
static C Y = new C();
}
 

class
C {
String
Z = "White";
}

What Does It Print? Do not run it in eclipse and tell me the answer. I need to know why as well?

Ans: White


Reason :Outer static variable priority is higher than inner static variable.. 
You're hiding the class Y with a static instance of C named Y. The class Y is still there and can be used.

Try:
System.out.println(X.Y.Z);
System.out.println((new X.Y()).Z);
The output should be:
White
Black

Wednesday, February 6, 2013

== vs equals in Strings in Java

The equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

package
blogspot.sbollam.com
 public class Sample {
 public Sample()
 {
  System.out.println("Sample.Sample()");
 }

 /**
  * @param args
  */
 public static void main(String[] args)
 {


  String s1= new String("abc");
  String s2= new String("abc");
  String s3 ="abc";
  String s4 ="abc";
  System.out.println(s1==s3);
  System.out.println(s1==s2);
  System.out.println(s1.equals(s2));
  System.out.println(s1.equals(s3));
  System.out.println(s3.equals(s4));
  System.out.println(s3==s4);
  /*OUTPPUT:
   *
   * false false true true true true
   * */
 }

}


StringUtils.isNotEmpty() VS StringUtils.isNotBlank() in Java

isNotEmpty

public static boolean isNotEmpty(String str)
Checks if a String is not empty ("") and not null.
 StringUtils.isNotEmpty(null)      = false
 StringUtils.isNotEmpty("")        = false
 StringUtils.isNotEmpty(" ")       = true
 StringUtils.isNotEmpty("bob")     = true
 StringUtils.isNotEmpty("  bob  ") = true
 



Parameters:
str - the String to check, may be null

Returns:
true if the String is not empty and not null



isNotBlank

public static boolean isNotBlank(String str)
Checks if a String is not empty (""), not null and not whitespace only.
 StringUtils.isNotBlank(null)      = false
 StringUtils.isNotBlank("")        = false
 StringUtils.isNotBlank(" ")       = false
 StringUtils.isNotBlank("bob")     = true
 StringUtils.isNotBlank("  bob  ") = true
 



Parameters:
str - the String to check, may be null

Returns:
true if the String is not empty and not null and not whitespace








StringUtils.isEmtpty() vs StringUtils.isBlank() in Java



1) isEmpty

public static boolean isEmpty(String str)
Checks if a String is empty ("") or null.

StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false


2) isBlank

public static boolean isBlank(String str)
Checks if a String is whitespace, empty ("") or null.

StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false

Difference between NULL and empty string in Java

What is difference between null string (String abc = null) and empty string (String abc = "") ?

Analysis:
--------
Try to call a method on both of them and you'll see the difference


  1. String s = "";   s.length();  
you actually declare a new String Object, and it means the variable (in this case - s) has a String Object associated to it. you can call String methods on that object.
it is like typing:
              String s = new String();
  if you type:   String s = "";   s.lentgh; // return 0  

   2.   String s = null;   s.length();
    s.lentgh;//returns a null pointer exception

 Basically a reference to an empty string points to an object in the heap so you can call methods on it. But a reference pointing to null has no object to point in the heap and thus you'll get a Null Pointer Exception


Monday, February 4, 2013

Copy Elements from one ArrayList to Another ArrayList

Here is the Program to copy the values from one ArrayList to another ArrayList.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package collect;
  
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
  
  
public class ListClas {
 public static void main(String[] args) {
  
  List <STRING>l1=new ArrayList<STRING>(); 
    
  l1.add("hi");
  l1.add("brother");
    
  ArrayList<STRING> al=new ArrayList<STRING>(); 
  al.add("hello");  
  al.add("guru");   
    
  Collections.copy(al,l1);   
  Iterator i= al.iterator();  
    
  while(i.hasNext()){ 
   i.hasNext();  
   System.out.print(" "+i.next()); 
   //System.out.println(al);  
  }   
 }  
}

This is the procedure to copying the objects from one list to another.

How to Copy properties from one Bean OtherBean

As we know the Bean class containing the variables with setters and getters methods. We can access through the getXxx and setXxx methods by different properties. To copy the properties form one bean to another they should have same datatypes.

To Run our program the requirements are:

As per shown in the below image you can create the files in Eclipse.



Person.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package blog.sbollam;
public class Person {
  
 private String name;
    private int age;
      
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}
CopyPerson.java


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package blog.sbollam;
public class CopyPerson {
  
 private String name;
    private int age;
      
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
  
}

The TestCopyProperties class will let us test copying properties from one bean to another. First, it creates a person object(fromBean) and a copyPerson(toBean) object. It outputs these objects to the console. Then, it call the BeanUtils.copyProperties() method with toBean as the first parameter and fromBean as the second parameter. Notice that the object that is copied to is the first parameter and the object that is copied from is the second parameter.

In the below program we are copying the properties from person object to copyPerson object using BeanUtils.copyProperties(targer,source) method.

TestCopyProperties.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package blog.sbollam;
import org.apache.commons.beanutils.BeanUtils;
  
public class TestCopyProperties {
   
 public static void main(String[] args) throws Exception{
    
  Person person = new Person();
  person.setName("Ramu");
  person.setAge(24);
    
  CopyPerson copyPerson = new CopyPerson();
  copyPerson.setName("Krishna");
  copyPerson.setAge(22);
    
  System.out.println("----Before copying the properties----");
  System.out.println("--Person Proerpties--");
  System.out.println(person.getName());
  System.out.println(person.getAge());
  System.out.println("--copyPerson Proerpties--");
  System.out.println(copyPerson.getName());
  System.out.println(copyPerson.getAge());
    
  //BeanUtils.copyProperties(destination,source);
  BeanUtils.copyProperties(copyPerson,person);
    
  System.out.println("----Person to CopyPerson----");
  //the Person bean properties copied to CopyProperties bean
  System.out.println(copyPerson.getName());
  System.out.println(copyPerson.getAge());
 }
}

Output: