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

Friday, April 15, 2011

Published 4/15/2011 by with 0 comment

java.sql.SQLException: Access denied for user

The full error message may be :

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password : YES)

or


java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: NO)

When we try to connect to a database through JDBC with wrong username or password - we see this error message.

See the sample code below:

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","root","mypassword");

In the above code, root is the username and mypassword is the password. If the username root or the password is not correct we see this error message "java.sql.SQLException: Access denied for user 'root'@'localhost' (using password : YES)".

If the password is not provided (blank password) as the code below but the user has password we see the error message "java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: NO)"

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","root","");
If you are using JPA with eclipselink/toplink or other, correct the username and password in the persistence.xml file of your project.

persistence.xml may look like below:


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
  <persistence-unit name="MyPersistenceUnitPU" transaction-type="RESOURCE_LOCAL">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <properties>
      <property name="toplink.jdbc.user" value="root"/>
      <property name="toplink.jdbc.password" value="mypassword"/>
      <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/DatabaseName"/>
      <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
    </properties>
  </persistence-unit>
</persistence>

Read More
    email this       edit
Published 4/15/2011 by with 0 comment

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database

Trying to connect to a MySQL server from Java? But seeing the error "Unknown database"?

The reason is that the database does not exist in the MySQL server. You might have accidentally misspelled the database name in the JDBC connection url.

See the code below:
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sales","username","password");

Here sales is the database name. If you misspelled this or the database sales does not exist in the server, you see this error message.

Read More
    email this       edit
Published 4/15/2011 by with 0 comment

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure


This error message may include the following text also:

"The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server."


When we try to connect to a MySQL server "Communications link failure" error may occur for any of the following errors:

i) MySQL server is not running. Check for this and run the sever if it is stopped.

ii) Host name is wrong: If the server is running in the same computer, the correct host name is localhost otherwise it is a valid IP address or computer name.

iii) Wrong port no given : By default MySQL server runs in port 3306. If it is different, check that correct port no is given.


Sample code:

public static Connection getConnection()
{
Connection connection = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","username","password");
System.out.println("Connection successful");
}
catch(ClassNotFoundException cnfe)
{
System.err.println("MySQL driver not found");
cnfe.printStackTrace();
}
catch(SQLException sqle)
{
System.err.println("Database/Connection error");
sqle.printStackTrace();
}

return connection;
}



Read More
    email this       edit
Published 4/15/2011 by with 2 comments

ClassNotFoundException: com.mysql.jdbc.Driver

This error occurs when the required JDBC driver file is not in the CLASSPATH. Also, if the driver name is not correct ClassNotFoundException occurs. To solve this problem, at first check the driver name; if the driver name is correct, do one of the followings as per requirement.

i) Add an entry for the driver file (mysql-connector-java-5.1.10.jar, for example) in the CLASSPATH variable.

or

ii) If you are not familiar with the CLASSPATH variable, place the mysql-connector-java-5.1.10.jar file in \jre\lib\ext folder in the JDK install directory (for example C:\Program Files\Java\jdk1.6.0_20\jre\lib\ext)

or

iii) If you are doing this in NetBeans or other IDEs, add MySQL JDBC Driver Library in the project.
Read More
    email this       edit

Sunday, April 10, 2011

Published 4/10/2011 by with 1 comment

call to super must be first statement in constructor

The error message is very clear actually:

i) We can call super in the constructor of a subclass
ii) If we call super in the constructor of a subclass, it must be the first statement in that constructor; i.e, before writing any other statement we call to super must be made.

It is mentionable that, super(parameters) calls the constructor of the super class.

See the code below:

The super class...


public class Employee
{
private int id;
private String name;
public Employee()
{
}
public Employee(int id,String name)
{
this.id = id;
this.name = name;
}
}

The subclass...


public class SalariedEmployee extends Employee
{
private double salary;
public SalariedEmployee()
{
}
public SalariedEmployee(int id,String name,double salary)
{
this.salary = salary; //this is the first statement now
super(id,name); //error : call to super must be first statement in constructor
}
}

The correct subclass will be...


public class SalariedEmployee extends Employee
{
private double salary;
public SalariedEmployee()
{
}
public SalariedEmployee(int id,String name,double salary)
{
super(id,name); // now call to super is the first statement in the constructor
this.salary = salary; // it is now the second statement
}
}



Read More
    email this       edit

Friday, October 30, 2009

Published 10/30/2009 by with 0 comment

java.lang.ArrayIndexOutOfBoundsException


It's a very common runtime error message or exception we face when we use array wrongly. Very specifically this exception is thrown to indicate that an array has been accessed with an illegal index (location / position / subscript). The index is either negative or greater than or equal to the size of the array.


See the following code:

int data[]={5,7,18,21,27,15,3};

//show the array elements
for(int i=0;i<=7;i++)
{
System.out.println(data[i]);
}

Here the array size is 7 as the array is initialized by assigning 7 elements {5,7,18,21,27,15,3}. So the valid array index is 0 to 6. In the loop condition, we have given i&lt=7 and i is used as the array index inside the loop - so when i is 7 it tries to access the array element 7 but 7 is not a valid index. This causes the exception. Correct loop condition is i<7 or i<=6. The recommended approach is using the array built in variable length instead of the static size. Correct the code as below:


int data[]={5,7,18,21,27,15,3};

//show the array elements
for(int i=0;i<data.length;i++)//data is the array name
{
System.out.println(data[i]);
}

Read More
    email this       edit
Published 10/30/2009 by with 0 comment

array dimension missing

'array dimension missing' is shown when the array size is not specified while allocating memory for the array or creating an array.

See below:

int data[ ]=new int[ ];

See that, blank [ ] is given in new int[ ]. We must give an int as the size of the array. Memory will be allocated for the array according to the given int within the [ ] as below:

int data[]=new int[5];
Read More
    email this       edit
Published 10/30/2009 by with 7 comments

illegal initializer

You may see this error for writing wrong expression to initialize an array. See the code below:

int data={42,15,27,20,19};

If you compile this, you will see the following error message:

illegal initializer for int
int data={42,15,27,20,19};
^

Here the array is not declared properly as we have not put [ ] for declaring the array. The correct code is:

int data[ ]={42,15,27,20,19};

or

int[ ] data={42,15,27,20,19};
Read More
    email this       edit