<< Chapter < Page Chapter >> Page >
This module describes compilation errors that result from incorrect methods (primarily incorrect return statements) and incorrect use of the static attribute.

Methods and return statements

There are a number of errors related to the structure of methods and their return statements; in general they are easy to fix.

missing return statement

When a method returns a non-void type, every path that leaves the method must have a return -statement, A path may also leave the method via a throw statement. even if there is no way that the path can be executed:

int max(int i, int j) {   if (i > j) return i;   else if (i <= j) return j;   // Error: what about the path when i>j, i<=j are both false?!! }

Adding a dummy alternative else return 0; at the end of the method will enable successful compilation.

Eclipse: This method must return a result of type int This Eclipse message is rather hard to understand because, clearly, the method does return a result of type int , just not on all paths.

missing return value

A method returning a type must have a return -statement that includes an expression of the correct type:

int max(int i, int j) {   return;                // Error, missing int expression}

Eclipse: This method must return a result of type int

cannot return a value from method whose result type is void

Conversely, a return -statement in a void method must not have an expression:

void m(int i, int j) {   return i + j;          // Error, the method was declared void}

Eclipse: Void methods cannot return a value

invalid method declaration; return type required

Every method except constructors must have a return type or void specified; if not, this error will arise:

max(int i, int j) {   ...}

The error frequently occurs because it is easy to misspell the name of a constructor; the compiler then thinks that it is a normal method withouta return type:

class MyClass {   MyClass(int i) { ... }  Myclass(int i, int j) { ... }   // Error: lowercase c }

Eclipse: Return type for the method is missing

unreachable statement

The error can occur if you write a statement after a return statement:

void m(int j) {   System.out.println("Value is " + j);  return;   j++;}

The check is purely syntactic, so the error will occur in the following method:

if (true) {   return n + 1;        // Only this alternative executed, but ...} else {  return n - 1;   n = n + 1;           // ... this is an error}

Eclipse: Unreachable code

Access to static entities

The modifier static means that a variable or method is associated with a class and not with individual objects of a class. static has other uses that we do not consider here: (a) as a modifier for nested classes and (b) in static initializers. Normally, static entities are rarely used in Java (other than for the declaration ofconstants), because programs are written as classes to be instantiated to create at least one object:

class MyClass {   int field;  void m(int parm) {     field = parm;  }   public static void main(String[] args) {     MyClass myclass = new MyClass();    // Create object     myclass.m(5);                       // Call object's method    System.out.println(myclass.field);  // Access object's field   }}

Some teachers of elementary programming in Java prefer to start with a procedural approach that involves writing a class containing static variables and staticmethods that are accessed from the main method without instantiating an object as was done above:

class MyClass1 {   static int field;  static void m(int parm) {     field = parm;  }   public static void main(String[] args) {     m(5);                                 // OK    System.out.println(field);            // OK   }}

non-static variable ... cannot be referenced from a static context

Since the method main is (required to be) static, so must any variable declared in the class that is accessed by the method.Omitting the modifier results in a compile-time error:

  int field;                  // Forgot "static"      ...  System.out.println(field);  // Error, which field?

The variable field does not exist until an object of the class is instantiated, so using the identifier field by itself is impossible before objects are instantiated. Furthermore, it is ambiguous afterwards, as there maybe many objects of the same class.

Eclipse: Cannot make a static reference to the non-static field ...

non-static method ... cannot be referenced from a static context

Similarly, a non-static method cannot be called from a static method like main ; the reason is a bit subtle.When a non-static method like m is executed, it receives as an implicit parameter the reference to an object. (The reference can be explicitly referred to using this .) Therefore, when it accesses variables declared in the class like field :

void m(int parm) {            // Forgot "static"   field = parm;               // Error, which field?}  public static void main(String[] args) {  m(5); }

it is clear that the variable is the one associated with the object referenced by this . Thus, in the absence of an object, it is meaningless to call a non-static method from a static method.

Eclipse: Cannot make a static reference to the non-static method ... from the type ...

Questions & Answers

Preparation and Applications of Nanomaterial for Drug Delivery
Hafiz Reply
Application of nanotechnology in medicine
what is variations in raman spectra for nanomaterials
Jyoti Reply
I only see partial conversation and what's the question here!
Crow Reply
what about nanotechnology for water purification
RAW Reply
please someone correct me if I'm wrong but I think one can use nanoparticles, specially silver nanoparticles for water treatment.
yes that's correct
I think
what is the stm
Brian Reply
is there industrial application of fullrenes. What is the method to prepare fullrene on large scale.?
industrial application...? mmm I think on the medical side as drug carrier, but you should go deeper on your research, I may be wrong
How we are making nano material?
what is a peer
What is meant by 'nano scale'?
What is STMs full form?
scanning tunneling microscope
how nano science is used for hydrophobicity
Do u think that Graphene and Fullrene fiber can be used to make Air Plane body structure the lightest and strongest. Rafiq
what is differents between GO and RGO?
what is simplest way to understand the applications of nano robots used to detect the cancer affected cell of human body.? How this robot is carried to required site of body cell.? what will be the carrier material and how can be detected that correct delivery of drug is done Rafiq
analytical skills graphene is prepared to kill any type viruses .
Any one who tell me about Preparation and application of Nanomaterial for drug Delivery
what is Nano technology ?
Bob Reply
write examples of Nano molecule?
The nanotechnology is as new science, to scale nanometric
nanotechnology is the study, desing, synthesis, manipulation and application of materials and functional systems through control of matter at nanoscale
Is there any normative that regulates the use of silver nanoparticles?
Damian Reply
what king of growth are you checking .?
What fields keep nano created devices from performing or assimulating ? Magnetic fields ? Are do they assimilate ?
Stoney Reply
why we need to study biomolecules, molecular biology in nanotechnology?
Adin Reply
yes I'm doing my masters in nanotechnology, we are being studying all these domains as well..
what school?
biomolecules are e building blocks of every organics and inorganic materials.
anyone know any internet site where one can find nanotechnology papers?
Damian Reply
sciencedirect big data base
Introduction about quantum dots in nanotechnology
Praveena Reply
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get the best Algebra and trigonometry course in your pocket!

Source:  OpenStax, Compile and runtime errors in java. OpenStax CNX. Dec 28, 2009 Download for free at http://cnx.org/content/col10913/1.2
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Compile and runtime errors in java' conversation and receive update notifications?