Friday, May 20, 2011

Published 5/20/2011 by with 2 comments

attempting to use incompatible return type

We may encounter this error message when we override a superclass method in the subclass with a wrong return type in the subclass method. To understand this, let's see the following two classes.

public class SuperClass
{
public double sum(double a,double b)
{
return (a+b);
}
}

public class Subclass extends SuperClass
{
public long sum(double a,double b)
{
return Math.round(a+b);
}
}

In the above example code, the super class method sum has double return type and in the subclass we have overridden this method where return type is long which is not compatible with double.
What should we do now to remove the error? We should either declare the return type of the subclass as double or change the parameter type.

See the correct code of the subclass below:

public class Subclass extends SuperClass
{
public double sum(double a,double b)
{
return Math.round(a+b);
}
public long sum(long a,long b)
{
return (a+b);
}
}


Read More
    email this       edit

Thursday, May 19, 2011

Published 5/19/2011 by with 5 comments

is not abstract and does not override abstract method

See the code below:


import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyFrame extends JFrame implements ActionListener{
private JButton exitButton = new JButton("Exit");
public MyFrame()
{
Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(exitButton);
  exitButton.addActionListener(this);
setSize(300,200);
}
}

If this code is compiled, we will see the error "MyFrame is not abstract and does not override abstract method actionPerformed(java.awt.event.ActionEvent) in java.awt.event.ActionListener"

Why? When we implement an interface(ActionListener in this example) or extend an abstract class in a concrete class, we must override the abstract method(s). In the above example we have implemented ActionListener but have not overridden the abstract method actionPerformed.

The correct code of the above is:

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyFrame extends JFrame implements ActionListener
{
private JButton exitButton = new JButton("Exit");
public MyFrame()
{
Container container = getContentPane();
container.setLayout(new FlowLayout());
container.add(exitButton);
exitButton.addActionListener(this);
setSize(300,200);
}
public void actionPerformed(ActionEvent ae)
{
System.exit(0);
}
}


Sometimes it happens that we override the abstract method with wrong name spelling or wrong signature, then also we see the same error message. Note that Java is a case sensitive language; most often we write the method name with wrong case (example, actionperformed/ActionPerformed instead of actionPerformed) and see this error message.

For implementing an interface or extending an abstract class, we must override all of the abstract methods (if more than one), though we do not need all. For example, if we implement KeyListener we must override each of the three abstract methods keyPressed, keyTyped and keyReleased though we may not need all of them. In that case, method body can be kept blank. Instead of interface, we can use adapter class (if available) to get rid of overriding all abstract methods.

In summary, override the abstract method with correct name spelling and signature to remove the error.
Read More
    email this       edit
Published 5/19/2011 by with 2 comments

attempting to assign weaker access privileges

Java error "attempting to assign weaker access privileges" can happen when we override a superclass method in the subclass if the access modifier is not correctly chosen.

See the sample code below:

public class SuperClass
{
public void display()
{
System.out.println("this is super class");
}
}


public class Subclass extends SuperClass
{
private void display()
{
System.out.println("this is subclass");
}
}

If the above Subclass is compiled the error message will be:
display() in Subclass cannot override display() in SuperClass; attempting to assign weaker access privileges; was public

Let's understand the error message:
The method display has public access in the SuperClass and private access in the Subclass, that means when overriding this method, a weaker access privilege is going to be set (private is weaker access privilege than public).

So we need to know the allowed access modifier in the subclass for method overriding. The table below shows this:


Access modifier in super class method
Allowed access modifier for overriding
private
private, package, protected, public
package
package, protected, public
protected
protected, public
public
public


Read More
    email this       edit
Published 5/19/2011 by with 4 comments

modifier private not allowed here

Java error "modifier private not allowed here" can occur for any of the following reasons:

1. An outer class declared as private like below:
private class OuterClass
{
    //...
}
An outer class only be public or package private not private or protected. So you can write an outer class as below:
public class OuterClass
{
   //...
}
or
class OuterClass
{
   //...
}
This is true for an interface also. An interface can only be public or package not private or protected.


2. An interface method declared as private.

public interface TestInterface
{
   private void method(); // wrong as the interface method is private
}

An interface can contain only public or package private method.

The correct code of the above is:

public interface TestInterface
{
   public void method();
}
or
public interface TestInterface
{
   void method(); // interface method declared as package private
}
Read More
    email this       edit

Tuesday, May 17, 2011

Published 5/17/2011 by with 0 comment

No Persistence provider for EntityManager named

Are you using JPA and getting the error "Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named ..."

You might have used an entity manager as the following code:


public void persist(Object object) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TestPU");
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        try {
            em.persist(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }


And you might have a persistence.xml file as below:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="PersonPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>person.entity.Person</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/persondb"/>
<property name="javax.persistence.jdbc.password" value="mypassword"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
</properties>
</persistence-unit>
</persistence>


Now see that, this error may happen for any of the following reasons:



1. In the code EntityManagerFactory emf = Persistence.createEntityManagerFactory("TestPU"); TestPU is passed in the method which must be a valid persistence unit name. In the persistence.xml file the name is defined as persistence-unit name="PersonPU". These two names must be same. So to remove the error the correct code will be :

EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersonPU");

2. If the persistence unit name is correctly used but still the error exists, then confirm that the required jar file containing the JPA implementation classes are available in the classpath. Required jar files for the above code are eclipselink-2.0.0.jar and eclipselink-javax.persistence-2.0.jar

Read More

    email this       edit
Published 5/17/2011 by with 1 comment

is not a known entity type

To understand the error, let us assume that we have the following classes:

1) An entity class
package person.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
/**
 *
 * @author Shamsuddin
 */
@Entity
@Table(name = "person")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Person.findAll", query = "SELECT p FROM Person p"),
    @NamedQuery(name = "Person.findById", query = "SELECT p FROM Person p WHERE p.id = :id"),
    @NamedQuery(name = "Person.findByFirstName", query = "SELECT p FROM Person p WHERE p.firstName = :firstName"),
    @NamedQuery(name = "Person.findByLastName", query = "SELECT p FROM Person p WHERE p.lastName = :lastName"),
    @NamedQuery(name = "Person.findByDateOfBirth", query = "SELECT p FROM Person p WHERE p.dateOfBirth = :dateOfBirth"),
    @NamedQuery(name = "Person.findByEmail", query = "SELECT p FROM Person p WHERE p.email = :email")})
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "date_of_birth")
    @Temporal(TemporalType.TIMESTAMP)
    private Date dateOfBirth;
    @Column(name = "email")
    private String email;
    public Person() {
    }
    public Person(Integer id) {
        this.id = id;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Date getDateOfBirth() {
        return dateOfBirth;
    }
    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }
    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Person)) {
            return false;
        }
        Person other = (Person) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }
    @Override
    public String toString() {
        return "person.entity.Person[ id=" + id + " ]";
    }
 
}

2. A java class that encapsulates an EntityManager

package person.manager;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
 *
 * @author Shamsuddin
 */
public class MyEntityManager {
   EntityManagerFactory emf = Persistence.createEntityManagerFactory("PersonPU");
   EntityManager em = emf.createEntityManager();
    public void persist(Object object) {
        em.getTransaction().begin();
        try {
            em.persist(object);
            em.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
        } finally {
            em.close();
        }
    }
 
}

3. A main class

package person;
import person.entity.Person;
import person.manager.MyEntityManager;
/**
 *
 * @author Shamsuddin
 */
public class PersonMain {
    public static void main(String args[])
    {
        MyEntityManager entityManager = new MyEntityManager();
     
        Person person = new Person();
        person.setFirstName("Shamsuddin");
        person.setLastName("Ahammad");
     
        entityManager.persist(person);
     
     
    }
}


If we run the PersonMain class, in a situation, following error may be encountered:



java.lang.IllegalArgumentException: Object: person.entity.Person[ id=null ] is not a known entity type. The compiler indicates the error in the line entityManager.persist(person); meaning person is not an instance of an entity class.



Now Let's see:

1. See that Person is an entity class which has an annotation @Entity that means we have declared this class as an entity class. If your entity class does not have @Entity annotation, this may be the cause of this error. In that case, add annotation @Entity in the entity class. In our case, though the entity class is annotated properly, other reasons may cause this error(see below).

2. As we are using Java Persistence API (JPA), we have a persistence.xml file containing the following xml code:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="PersonPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/persondb"/>
      <property name="javax.persistence.jdbc.password" value="mypassword"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
    </properties>
  </persistence-unit>
</persistence>

We have error in this persistence.xml file. What's that? The persistence.xml must declare the entity class by writing <class>person.entity.Person</class>

So the correct persistence.xml will be:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="PersonPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>person.entity.Person</class>    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/persondb"/>
      <property name="javax.persistence.jdbc.password" value="mypassword"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
    </properties>
  </persistence-unit>
</persistence>

If you use netbeans you can add the entity class declaration in the persistence.xml file very easily using the design view.
Read More

    email this       edit

Monday, May 9, 2011

Published 5/09/2011 by with 0 comment

Color parameter outside of expected range: Red Green Blue

Java error "Color parameter outside of expected range: Red Green Blue" can be encountered when we use the java.awt.Color class with wrong arguments for RGB (Red Green Blue).

See the wrong code below:
import javax.swing.JFrame;
import java.awt.Container;
import java.awt.Color;
public class MyFrame extends JFrame
{
public MyFrame()
{
Container container = getContentPane();
container.setBackground(new Color(-5,256,300)); // wrong value for RGB
setSize(800,600);
}
public static void main(String args[])
{
MyFrame myFrame = new MyFrame();
myFrame.setVisible(true);
}
}



See that, we have used -5, 256, 300 for Red, Green and Blue values respectively in the java.awt.Color class constructor. These arguments are illegal as the supported values are in the range 0 to 255.

So a correct code is:

container.setBackground(new Color(5,156,200)); // RGB values are in the range 0 to 255

If the constructor with float arguments is used than the correct RGB values are in the range 0.0 to 1.0

For more details http://download.oracle.com/javase/1.5.0/docs/api/java/awt/Color.html
Read More
    email this       edit
Published 5/09/2011 by with 1 comment

modifier static not allowed here


Java error "modifier static not allowed here" can occur for any of the following reasons:

1. Constructor is declared as static(!)

A constructor cannot be static. In the wrong code below:

public class Person
{
private String firstName;
private String lastName;
public static Person()
{
//...
}
}

Here the constructor Person is declared as static. As the constructor must be non-static, the correct code is:

public class Person
{
private String firstName;
private String lastName;
public Person()
{
//...
}
}



2. Interface contains static method(!)

All methods of any interface is abstract and hence they must be non static. See the code below:

public interface MyInterface
{
public static void myMetod();
}

The above code is wrong as the interface method is declared as static. Corrected code is:

public interface MyInterface
{
public void myMetod();
}
Read More
    email this       edit
Published 5/09/2011 by with 1 comment

illegal combination of modifiers: abstract and static

An abstract method cannot be static because the abstract method must be overridden i.e, body of the abstract method must be defined before invocation.

See the wrong code below:

public abstract class Employee
{
public static abstract double earnings(); // error
}

Here the abstract method earnings() is declared as static. An abstract method must be non-static. So the correct code is:


public abstract class Employee
{
public abstract double earnings(); // no error now
}


Read More
    email this       edit
Published 5/09/2011 by with 1 comment

interface methods cannot have body

Java error "interface methods cannot have body" occurs when body of the method within an interface is defined.

See the code below:

public interface MyInterface
{
public void myMetod()
{
}
}

Here the method myMethod has body starting at the symbol { and ending at }. An interface can have abstract methods (method without any body). The class that implements the interface defines the body of the interface methods.

So to remove the error, the method signature/header will end by ; (semi colon) and there will be no body section for the method. Below is the correct code:



public interface MyInterface
{
public void myMetod();
}


Read More
    email this       edit
Published 5/09/2011 by with 0 comment

interface expected here

The code below leads to an error "interface expected here"

public interface MyInterface extends Thread
{
}

Here an interface is created (MyInterface) and it inherits(extends) the Thread class which is not possible at all. Why? Because an interface can inherit only another interface, not any class. As Thread is a class, it cannot be inherited by any interface.

The code below is correct as the interface inherits another interface Runnable



public interface MyInterface extends Runnable
{
}


A similar type of error is posted at  no interface expected here

Read More
    email this       edit
Published 5/09/2011 by with 0 comment

no interface expected here

Any Java code as below will lead an error "no interface expected here"

import java.io.Serializable;
public class Person extends Serializable
{
private String firstName;
private String lastName;
//...
}

See that, here Person is a class (public class Person) and it inherits an interface (extends Serializable). Note that a class can inherit another class only, not any interface. A class can implement one or more interface only. Serializable is an interface, not a class.

Actually the correct code of the above will be:


import java.io.Serializable;
public class Person implements Serializable
{
private String firstName;
private String lastName;
//...
}

Here it is notable that, only an interface can inherit another interface.

A similar type of error is posted at interface expected here
Read More
    email this       edit

Thursday, May 5, 2011

Published 5/05/2011 by with 2 comments

invalid method declaration; return type required

The Java error "invalid method declaration; return type required" can occur for any of the following reasons:

1. You are trying to define a constructor (of course without any return type; not even void)  but the constructor name is not given same as the class name.

See the wrong code below:

public class Employee
{
 private int id;
 private String name;
 public employee(int id,String name) // constructor name is not same as the class name.
 {
  this.id = id;
  this.name = name;
 }
}


So check the spelling of the constructor name and also note that Java is a case sensitive language.

2. If you are really defining a method (not a constructor) you have forgotten to declare the return type as the wrong code given below:


public class Test
{
public aMethod() // no return type given
{
System.out.println("This is a method");
}
}

The correct code is:


public class Test
{
public void aMethod() // return type void is given now
{
System.out.println("This is a method");
}
}


Read More
    email this       edit

Tuesday, May 3, 2011

Published 5/03/2011 by with 3 comments

recursive constructor invocation

If a constructor calls itself, then the error message "recursive constructor invocation" is shown. It may happen when we overload constructors and call the wrong constructor (itself) accidentally.

See the wrong code below:
public class Employee
{
  private int id;
  private String name;
  public Employee(int id,String name)
  {
    this.id = id;
    this.name = name;
  }
  public Employee(int id)
  {
    this(id); 
    /* this(id) calls the constructor having one parameter of int type. Thus this is calling itself.*/
  }
  public Employee()
  {
  }
}


In the above code, there are three constructors:
i) Employee(int id,String name)
ii) Employee(int id)
iii) Employee()

Within the second constructor, we have written this(id) which means it calls a constructor with one int parameter and see that it is the constructor itself. It means we have not invoked the right constructor. If we want to invoke the first constructor Employee(int id,String name) within the second constructor we should write this(id,null). We are providing null for the String name as no value is available for the name variable in the second constructor but now it calls the first constructor Employee(int id,String name) as we have provided  two parameters now.

See the corrected code below:

public class Employee
{
  private int id;
  private String name;
  public Employee(int id,String name)
  {
    this.id = id;
    this.name = name;
  }
  public Employee(int id)
  {
    this(id,null); // this(id,null) calls another constructor having two parameters
  }
  public Employee()
  {
  }
}

Summary:

If you see the error message "recursive constructor invocation", check that you have provided correct no and type of parameters while calling one constructor in another one.
Read More
    email this       edit