Return statement on a void?

Theres a part that i dont understand, and if its possible i'd like to be helped a bit with it ^_^.
This class is part of a program that uses threading to display a consistent "Tick Tock", but the part that i dont get is why is there a return statement on the method that is on bold, isn't void supposed to mean that it doesnt return a value, is the return statement just used to get out of the if loop?, or maybe something else! help is appreciated!
class TickTock {
synchronized void tick(boolean running) {
if(!running) { // stop the clock
notify(); // notify any waiting threads
return;
System.out.print("Tick ");
notify(); // let tock() run
try {
wait(); // wait for tock() to complete
catch(InterruptedException exc) {
System.out.println("Thread interrupted.");
synchronized void tock(boolean running) {
if(!running) { // stop the clock
notify(); // notify any waiting threads
return;
System.out.println("Tock");
notify(); // let tick() run
try {
wait(); // wait for tick to complete
catch(InterruptedException exc) {
System.out.println("Thread interrupted.");
}Message was edited by:
Rix87

A simple return statement means that you are just exiting that function. A function can use the return statement even if it is declared a void. It is just that from a void function you can not return a value.
In your code the function is doing some condition checking (if statements) and based on that decides whether to exit the function or to continue going forward.
Additionally, the if-construct is not a loop. If statements provide conditional branching mechanism.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html
You probably will never need to break out of an if statement. If you do need it, then perhaps your if condition is suspect.
http://java.sun.com/developer/TechTips/2000/tt0613.html
You can use labeled breaks if you need to break out of nested if statements but it is very rare that you will need them and the code can perhaps be written in another way which is much more readable than labeled breaks.

Similar Messages

  • Problems with asynchronous(?) function call before return statement

    I have a function as following inside a class deriving from CustomNode:
    override protected function create () : Node {
                    parseContent();
                    return group;
            }parseContent() executes a HttpRequest and then a PullParser. At least that's what it should do. But actually, it doesn't. Is this because the HttpRequest is asynchronous and is "cancelled" because of the return statement? Or can't this be the problem?

    You would have to update or create the view in the finally block of the onOutput: or onInput methods within the request.
    You could also try
    var viewContent: Node;
    override protected function create () : Node {
                    parseContent();
                    FX.deferAction(function():Void{
                           viewContent = group;
                    return Group{ content: bind viewContent }
            }I never tried that, but it might work.
    Another option is to bind the parsed content to whatever view you are pushing it to. Then whenever the request is done, the view will populate its content on the change of the variable where the content is stored.
    Example:
    var allTables: TableModel[];      
    //***************start of table list decleration****************************\\
    public var list: SwingJList = SwingJList {
        var shortcutKey: Boolean = false;
        focusTraversable: true
        selectedIndex: 0
        action: function(){
            FX.deferAction(function():Void{
                openButton.fire();
        items: bind for( table in allTables ){
            table.name
    var searchDataXml = xmlGenerator.generateSearchXMLString(searchData);
    var contentLength: Integer = searchDataXml.getBytes().length;
    def postRequest: HttpRequest = HttpRequest {
        location: "{WEB_APPLICATION_REQUEST_URL}searchData/?database={DATABASE_KEY}";
        method: HttpRequest.POST;
        headers: [
                HttpHeader {
                    name: HttpHeader.CONTENT_TYPE;
                    value: "application/xml";
                HttpHeader {
                    name: HttpHeader.CONTENT_LENGTH;
                    value: "{contentLength}";
        onStarted: function() {
            println("onStarted - started performing method: {postRequest.method} on location: {postRequest.location}");
        onConnecting: function() { println("onConnecting") }
        onDoneConnect: function() { println("onDoneConnect") }
        onWriting: function() { println("onWriting") }
        onOutput: function(os: java.io.OutputStream) {
            try {
                os.write(searchDataXml.getBytes());
            } finally {
                println("onOutput - about to close output stream.");
                os.close();
                os.flush();
        onToWrite: function(bytes: Long) { println("onToWrite - entire content to be written: {bytes} bytes") }
        onWritten: function(bytes: Long) { println("onWritten - {bytes} bytes has now been written") }
        onDoneWrite: function() { println("doneWrite") }
        onReadingHeaders: function() { println("onReadingHeaders") }
        onResponseCode: function(code:Integer) { println("onResponseCode - responseCode: {code}") }
        onResponseMessage: function(msg:String) { println("onResponseMessage - responseMessage: {msg}") }
        onResponseHeaders: function(headerNames: String[]) {
            println("onResponseHeaders - there are {headerNames.size()} response headers:");
            for (name in headerNames) {
                println("    {name}: {postRequest.getResponseHeaderValue(name)}");
        onReading: function() { println("onReading") }
        onToRead: function(bytes: Long) {
            if (bytes < 0) {
                println("onToRead - Content length not specified by server; bytes: {bytes}");
            } else {
                println("onToRead - total number of content bytes to read: {bytes}");
        onRead: function(bytes: Long) {
            // The toread variable is non negative only if the server provides the content length
            def progress =
            if (postRequest.toread > 0) "({(bytes * 100 / postRequest.toread)}%)" else "";
            println("onRead - bytes read: {bytes} {progress}");
        var parser = new XmlPullParser();
        onInput: function(is: java.io.InputStream) {
            // use input stream to access content here.
            // can use input.available() to see how many bytes are available.
            try {
                allTables = parser.processResults(is);
            } finally {
                is.close();
        onException: function(ex: java.lang.Exception) {
            println("onException - exception: {ex.getClass()} {ex.getMessage()}");
        onDoneRead: function() { println("onDoneRead") }
        onDone: function() { println("onDone") }
    postRequest.start();
    } In this case an array of tableModel names are bound to the list view.
    When the httprequest ends, it sets the parsed tableModel array to the array declared in this class.
    The list view will populate the table names from the array when the request finishes.

  • Missing return statement

    Can anyone tell me why I'm getting a missing return statement error in this code?
    import java.awt.*;
    * Write a description of class Flower here.
    * @author (your name)
    * @version (a version number or a date)
    public class Flower
        protected FilledOval dot;
        protected FilledRect stem;
        protected FilledOval petal1;
        protected FilledOval petal2;
        protected static final int boundary = 100;
        protected RandomIntGenerator colorGen =
                new RandomIntGenerator(0,255);
        protected Color petalColor;
        protected Boolean flowerContains=false;
        private DrawingCanvas canvas;
        public void changeColor(Location point){
        dot = new FilledOval(point,15,15, canvas);
        dot.setColor(Color.YELLOW);
        petalColor = new Color(colorGen.nextValue(),
                                    colorGen.nextValue(),
                                    colorGen.nextValue());
        petal1.setColor(petalColor);
        petal2.setColor(petalColor);
        public void grow(Location point){
        stem = new FilledRect (dot.getX()+3, dot.getY()+10, 10, 10, canvas);
        stem.setColor(Color.GREEN);
        if (dot.getY()>boundary){
            dot.move(0,-4);
        else{
         petal1 = new FilledOval(dot.getX()-12, dot.getY()-25, 40,70,canvas);
         petal2 = new FilledOval(dot.getX()-25, dot.getY()-10, 70,40,canvas);
         dot.sendToFront();
         stem.sendToBack();
         petal1.setColor(petalColor);
         petal2.setColor(petalColor);
        public Boolean flowerContains(Location point){
            if (petal1.contains(point)){
                return true;
            else if (petal2.contains(point)){
                return true;
            else if (dot.contains(point)){
                return true;
    }

    public Boolean flowerContains(Location point){
            if (petal1.contains(point)){
                return true;
            else if (petal2.contains(point)){
                return true;
            else if (dot.contains(point)){
                return true;
        }That method returns a Boolean value. But if none of the condition gets satisfied then what is it going to return?

  • "missing return statement" error code

    well... i feel like such a n00b... I can't seem to figure out what the problem is with my code, if someone could help me, that would be great. I get an error saying 'missing return statement'. I know that I have some things in here that I don't need but I will need them as I go on making this program.
    with this code:
    import java.io.*;
    import java.math.*;
    public class Tester
         public static int time = 0;
         public static void main(String[] args) throws IOException
              System.out.println("Welcome to the 2008 Java Games!!!");
              time=1000;
              delay(100);
              //Method Name: delay
              //Method Arguments: used to wait for a given time
              //Goal of Method: Delay for a given time
         public static int delay(int time)
              try {
                   Thread.sleep(time);
              catch(InterruptedException ex) {}
              time++;
    }

    What does the error say? "Missing return statement"? Then I'm going to venture a guess and say that you're missing a return statement. If you don't know what a return statement is, then you have some learning to do:
    http://java.sun.com/docs/books/tutorial/java/javaOO/returnvalue.html
    Read that, then look at your delay() method and how you call it. And notice that you've made delay() of type "int".
    Edit: Or just have someone else give you the answer :P
    Edited by: newark on Feb 27, 2008 3:20 PM

  • Missing return statement question

    I got a missing return statement error when i compile in this code but however i dont get any missing return statement errors in the second code that i pasted here.. What is the difference i didn't get it ? Thank you.
    public class primechecker {
        static double remainder = 0;
        public static boolean primecheck(int number){
             for(int i=2; i<number; i++){
                  remainder = number % i;
                  if (remainder == 0){
                       return false;
             if (remainder !=0){
                  return true;
        public static void main(String[] args) {
             System.out.print(primecheck(10));
    }That is the second code which gives no error.
    public class positiveornegative {
       public static boolean numbercheck (int number){
           boolean booleann = true;
           if(number > 0){
             return true;
           else if (number < 0){
             return false;
           else {
                return false;
        public static void main(String[] args) {
             System.out.println(numbercheck(-2));
    }

    In your first snippet, the compiler has no guarantee that the for loop will be executed at all. That leaves only one return inside an if condition which again it has no guarantee that it will ever be reached(the if test may fail). This leads the compiler to the conclusion that your method may never return anything at all. Yet it's definition says that it must return a value.

  • Missing Return Statement Hell!!

    public class EventSite
    private int siteNumber;
    public EventSite()
    siteNumber = 999;
    public int getSiteNumber()
    return siteNumber;
    public Void setSiteNumber(int n)
    siteNumber = n;
    I'm taking a java class and this won't compile...Whats wrong??
    Why the Missing return statement error?

    flounder wrote:
    NewProgramGirl wrote:
    no need it is now compiled, think it was the big "V'...thank you....soooo much!!Well that contradicts what you said in reply 4.I'm guessing we forgot the all important "Save" step of the development lifecycle.
    Speaking of development lifecycle my version control system at my new job consists of zipping my project to the main fileserver each night before I leave. Apparently the SVN will be set up any day now...

  • "Missing Return Statement" although the return statement IS there?

    Hello :) I am currently studying computing science at staffordshire university, java is one of my modules (first year) and im about half way through (still at introduction stage though)... Within my code apparently I have not returned a statement... yet to my believe the return statement is there and in the correct space, i would appreciate it if you could have a look and tell me where I am going wrong please:
    import java.util.*;
    public class ReadWriteArrayApp3
    +{+
    + public static void main(String [ ] args)+
    + {+
    + int[] nums = int double[6];+
    + double result;+
    + readArray(nums);+
    + printArray(nums);+
    + printReverse(nums);+
    + averageArray(nums);+
    result = averageArray(nums);
    + System.out.println("The average of your numbers is " + result);+
    + } // end main+
    public static void readArray(int [] a)
    + {+
    + Scanner kybd = new Scanner(System.in);+
    + System.out.println("Please enter 6 Integers");+
    + for(int i=0; i < a.length; i++)+
    + {+
    + a[i] = kybd.nextInt();+
    + }+
    + }+
    +public static void printArray(int [ ] b)+
    + {+
    + for (int i = 0; i < b.length; i++)+
    + {+
    + System.out.println(b);+
    + }+
    + }+
    + public static void printReverse(int [ ] c)+
    + {+
    + for (int i = c.length-1; i >= 0; i--)+
    + {+
    + System.out.println(c[i]);+
    + }+
    + }+
    + public static double averageArray(int [ ] d)+
    + {+
    + double sum, tot, average;+
    + for (int i = 0; i < d.length; i++)+
    + {+
    + tot = tot + d[i];+
    + average = (tot)/d.length;+
    + if ((average)=(tot/d.length))+
    + {+
    + sum = average;+
    +*  }
    + return sum;+
    + }+
    +} // end application class+
    Console states:
    javac  ReadWriteArrayApp3.java
    ReadWriteArrayApp3.java:49: missing return statement
    * ^*
    *1 error*
    Above in the code I have shown I have made a part bold... this shows the area in which console has a problem with.
    I would really appreciate any help in which I get
    Thankyou
    Victoria
    Edited by: StaffsUniJavaGirl on Nov 12, 2009 9:48 AM

    import java.util.*;
    public class ReadWriteArrayApp3
         public static void main(String [ ] args)
              int[] nums = int double[6];
              double result;
              readArray(nums);
              printArray(nums);     
              printReverse(nums);
              averageArray(nums);
              result = averageArray(nums);
              System.out.println("The average of your numbers is " + result);
         }  //  end main
         public static void readArray(int [] a)
              Scanner kybd = new Scanner(System.in);
              System.out.println("Please enter 6 Integers");
              for(int i=0; i < a.length; i++)
              a[i] = kybd.nextInt();
         public static void printArray(int [ ] b)
              for (int i = 0; i < b.length; i++)
                   System.out.println(b);
         public static void printReverse(int [ ] c)
              for (int i = c.length-1; i >= 0; i--)
                   System.out.println(c[i]);
         public static double averageArray(int [ ] d)
              double sum, tot, average;
              for (int i = 0; i < d.length; i++)
                   tot = tot + d[i];
                   average = (tot)/d.length;
                   if ((averagetot)=(tot/d.length))
                        sum = average;
         return sum;
    } // end application class*line 49 is bold*                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Missing Return Statement - Please Help

    I get the "missing return statement" in line 47 in the getNumber method when I try to compile. Any suggestions?
    import java.util.Scanner; //imports scanner
    import java.util.Random;  //imports class Random
    public class Guess {
        Random randomNumbers = new Random();
        int answer;
        int userGuess;
        public void newGame()
            int answer = getNumber();
        public void play()
           Scanner input = new Scanner( System.in ); //creates scanner input
           System.out.println("\n\n Guess a number between 1 and 1000 or just" +
                   "press 0 to exit:" );
           userGuess = input.nextInt();
           while (userGuess != 0);
               checkUserGuess();
               System.out.println("Please enter another guess:");
               userGuess = input.nextInt();
        public int getNumber()
           int answer = 1 + randomNumbers.nextInt( 1000 );
        }  //ERROR IS DISPLAYED HERE
        /** Creates a new instance of Guess */
        public void checkUserGuess()
            if ( userGuess >= answer)
                System.out.println("Your guess is too high, try again");
            else
                if ( userGuess <= answer)
                    System.out.println("Your guess is too low, try again");
                else
                    System.out.println("Congratulation, you guessed correctly");
    }

    The error message says it all.
    You declared your getNumber method as returning integer.
    However you didnt return any number.
    add the reutrn statement to the method
    return answerJust to add, you have declared answer as global
    variable and agian answer as local variable.
    You are messing up a little there.
    Message was edited by:
    lupansansei

  • Missing return statement?  News to me!

    Before I ask anything let be begin by saying thanks to all you people that help others on these boards, I've never posted a question before but I have often found the answers to my problems somewhere here. I'm currently working on one of my last java assignments ever and I am completely stumped as to whats going on. All I want out of this code is for it to read a txt file for a bunch of phone book entries, load them into some arrays, then sort them by first name, last name, then phone# then return the array so I can use it later on. I've got the entries loaded, I've got em sorted, but I can;t return it. When I try I get a missing return statement error. I dont know why its not returning the array, so I thought I'd ask the pros. I can get it to work fine if I dont return anything but what good is that eh?
    Please forgive my terrible coding, I am in no way a real programmer, I just want to pass my classs and never think about it again 8) any help would be appreciated. Tis is built to work with an "Entry" file, if you guys need it to proceed lemme know and I will post it. Thanks.
    the code....
        public class CSCD210PhoneBook {
           public static void main(String[] args)throws IOException
          {//Opening main          
             Scanner kb = new Scanner(System.in);
               int entryCount=0;
                   Scanner fileScanner=null;
                   Entry[] array=null;
         array=populateEntry(entryCount, fileScanner, kb);
          }//end main array=
                 public static  Entry[] populateEntry(int entryCount, Scanner fileScanner,Scanner kb)throws IOException
                    int lineCount=0;
                   String fileName;
                   File fileHandle;     
                   System.out.println("Which file would you like your entries pulled from?");
                   fileName= kb.nextLine();
                               fileHandle = new File(fileName);
                   fileScanner = new Scanner(fileHandle);
                   while(fileScanner.hasNext())
                         fileScanner.nextLine();
                         lineCount++;
                   entryCount= lineCount/8;
                   Entry[] array=new Entry[entryCount];
                   fileScanner.close();
                   fileHandle = new File(fileName);
                   fileScanner = new Scanner(fileHandle);
                        for(int i =0; i<array.length;i++)
                             array=new Entry(fileScanner);
                   fileScanner.close();
                   int curPos, indexSmallest, start;
    Entry temp;
    for (start = 0; start < array.length - 1; start++)
    indexSmallest = start;
    for (curPos = start + 1; curPos < array.length; curPos++)
    if (array[indexSmallest].compareTo(array[curPos]) > 0)
    indexSmallest = curPos;
    } // end for
    temp = array[start];
    array[start] = array[indexSmallest];
    array[indexSmallest] = temp;
                   return array;
    Any help would be most appreciated.

    The code you posted has mismatched braces: it needs another } at the end.
    Linked with this is how - or rather when - you return array from the populateEntry()
    method. You have a couple of nested for-loops and you return array inside (at the
    end of) the outer loop.
    The compiler is really fussy about making sure that an Entry[] is returned from this
    method. If you outer for-loop never gets executed for some reason, then the return
    statement will never be reached. The compiler won't accept this.
    Either
    (1) move the return statement outside both loops so it is always executed. This
    appears to be the most logical thing - but I haven't read your code that closely. It's
    just that having return at the end of a for-loop (with no "continue" in sight), doesn't
    make a lot of sense.
    or
    (2) add another return after both loops have finished.

  • Return statement in exception and consequences

    Hi,
    Can any one give me the explanation for my doubt?
    Case 1:
    I am having some code throwing some exception lets say arithematic exception in my try block.
    I caught it in the catch block and at last I am having one finally?
    as per normal order try block next catch block and at last finally will execute.
    I execute the above code by putting a return statement inside catch block.I got the same order of execution irrespective of return statement inside catch?
    What is the significance of return inside catch?
    Case 2:
    Lets take the scenario.
    class MyException
         public static void main(String[] args)
              int i=1,j=0;
              try
                   try
                   System.out.println("the value is: "+(i/j));
                   System.out.println("Inside try block");
                   catch(ArithmeticException e)
                   System.out.println("hi in ame");
                   //return;
              finally
              System.out.println("inner finally");
                                            System.out.println("outer try");
              catch(Exception e)
                             e.printStackTrace();
                   System.out.println("in exception");
              finally
                   System.out.println("plz wait");
    If return statement is there inside the inner try and catch the code out of inside outer try not getting executed Why So?
    Any clarifications?
    Thanking you,
    Murthy.

    First, please format your code as per http://forum.java.sun.com/features.jsp#Formatting
    I'm not sure what part you don't understand.
    .    public static void main(String[] args) {
    .        try {
    .            try {
    .                throw new ArithmeticException();
    .                System.out.println("Inside try block"); // #1
    .            catch(ArithmeticException e) {
    .                System.out.println("hi in ame"); // #2
    .                return;
    .            finally {
    .                System.out.println("inner finally"); // #3
    .            System.out.println("outer try"); // #4
    .        catch(Exception e) {
    .            System.out.println("in exception"); // #5
    .        finally {
    .            System.out.println("plz wait"); // #6
    .    }#1 -- You won't get here because you throw AME.
    #2 -- You will get here because you caught the AME you just threw.
    #3 -- You will get here because it's a finally
    #4 -- You won't get here. I think that this is what you're asking about: Why don't we get here? Because we've already done 'return' and this line is NOT inside a finally. The only things that can get executed after a return are finally blocks.
    #5 -- You won't get here because you already caught the AME and didn't rethrow it or any other exception.
    #6 -- You will get here because it's a finally.
    Once you do a return, the only code you can execute before exiting the method are finally blocks. First the one corresponding to the try/cathc block where your return is, then the finally for the try/catch that encloses that one, and so on outward. The code between one finally and the next (#4 here) is NOT executed.
    If you still have a question, please try to clarify exactly what behavior you don't understand.
    Don't return from inside t/c/f.

  • Return statement in catch block !

    Hello Java Gurus,
    The code is not compiling when i remove return from the catch block
    i dont really understand the essence of return statement in catch block
    any help is greatly appreciated !
    Thanks in advance !
    import java.io.*;
    public class fileinputstream  {
       public static void main(String arg[]) {
            FileInputStream fin ;
            FileOutputStream fout;
           try  {
                 fin =new     FileInputStream("input_file.txt");
                 int bytes_av = fin.available();
                 System.out.println("bytes available the input file "+bytes_av);
           catch(FileNotFoundException e)
               System.out.println("The input file is not present");
               return;
           catch(IOException e)
               System.out.println("error while giving bytes available the input file");
               return;
           try
                     fout =new FileOutputStream("output_file.txt");
           catch(FileNotFoundException e)
               System.out.println("The output file cannot be created");
               return;
           int data=0;
           try  {
               data =(int)fin.read();
           catch(IOException e) {
               System.out.println("Exception while reading from file");
            while(-1!=data)      {
                       try
                       fout.write(data);
                       catch(IOException e)
                           System.out.println("Error while writing to file");
                       try
                           data =(int)fin.read();
                       catch(IOException e)
                           System.out.println("Exception while reading from file");
            try  {
                   fin.close();
                   fout.close();
            catch(IOException e)  {
               System.out.println("Error while closing files");
    }

    You do understand what "return" means, don't you? It
    exits the method, main() in this case.
    So the return statements in the catch blocks end the
    program. If you remove the return statements, the
    program will continue with the code after the catch
    blocks. It needs the variables "fout" and "fin"
    there, and these must be initialised.
    If there are no return statements in the catch
    blocks, the variables "fin" and "fout" will be not
    initialized when you get to the code that uses them,
    and that's an error. The java compiler is telling you
    that you must always initialise the variables (you
    can set them to "null", for example).Great explanation !!!
    Thanks !

  • Return statement issue

    I am trying to get my jdbc method (with boolean data type) to compile but I get compile error. I seem to have a problem with my return statement:
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class UserDB
        public static boolean isMatch(String lastname) throws SQLException
             try
              Class.forName("org.gjt.mm.mysql.Driver");
            String dbURL = "jdbc:mysql://localhost/dbhere";
            String username = "namehere";
            String password = "passwordhere";
            Connection connection = DriverManager.getConnection(dbURL, username, password);
             Statement stmt = connection.createStatement();
            ResultSet results = stmt.executeQuery("SELECT lastname from user where lastname = '" + lastname + "'");
             boolean myhit = results.next();
              results.close();
              stmt.close();
             return myhit;
            catch(ClassNotFoundException e)
                System.out.println("Database driver not found.");
            catch(SQLException e)
                System.out.println("Error opening the db connection: " + e.getMessage());
    }Error message:
    prompt>javac UserDB.java
    UserDB.java:34: missing return statement
         ^
    1 errorPlease advise what I am doing wrong??

    Or rewrite your code like this:
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class UserDB
       public static boolean isMatch(String lastname) throws SQLException
          boolean myhit = false;
          Connection connection = null;
          Statement stmt = null;
          ResultSet results = null;
          try
                Class.forName("com.mysql.jdbc.Driver");
             String dbURL = "jdbc:mysql://localhost/dbhere";
             String username = "namehere";
             String password = "passwordhere";
             connection = DriverManager.getConnection(dbURL, username, password);
             stmt = connection.createStatement();
             results = stmt.executeQuery("SELECT lastname from user where lastname = '" + lastname + "'");
             myhit = results.next();
          catch(Exception e)
               e.printStackTrace();
          finally
                close(results);
                close(stmt);
                close(conn);
          return myhit;
       public static void close(ResultSet rs)
           try
              if (rs != null)
                 rs.close();
           catch (Exception e)
                 e.printStackTrace();
       public static void close(Statement stmt)
           try
              if (stmt != null)
                 stmt.close();
           catch (Exception e)
                 e.printStackTrace();
       public static void close(Connection conn)
           try
              if (conn != null)
                 conn.close();
           catch (Exception e)
                 e.printStackTrace();
    }%

  • Unreachable statement error occured while using return statement.

    Consider this code
    class q25{
         public static void main(String args[]){
              amethod(args);
         public static void amethod(String args[]){
              String str;
              try{
                   str = "Hello "+args[0];
                   System.out.println(str);
                   System.out.println("Returning to caller");
                   System.exit(0);
              catch(Exception e){
                   System.out.println("Exception ocured");
                   System.exit(0);          
              finally{
                   System.out.println("In finally");
              System.out.println("At the end of method");     
    }Above code compiles and runs successfully without any errors.
    Now consider below code which is same as above one except "System.exit(0)" statements were replace by "return" statements. Below code when compiled gives error as
    "q25.java:22: unreachable statement
    System.out.println("At the end of method");
    ^
    1 error"
    One thing i didn't understood in this context that, the above code when compiled should get same error as stated above. But not. It is obvious that presence of System.exit(0) must generate unreachable statement same as when it is replaced by "return" statement. What is the difference in getting the error for above but not for below code. Pls anyone help.
    class q25{
         public static void main(String args[]){
              amethod(args);
         public static void amethod(String args[]){
              String str;
              try{
                   str = "Hello "+args[0];
                   System.out.println(str);
                   System.out.println("Returning to caller");
                   return;
              catch(Exception e){
                   System.out.println("Exception ocured");
                   return;     
              finally{
                   System.out.println("In finally");
              System.out.println("At the end of method");     
    }

    warnerja wrote:
    masijade. wrote:
    Since you have a "return" in both the try and the catch portions of the try/catch block *(the second of which you should never do)* , anything thing that comes after the try/catch/finally blocks will be unreachable.That is not true. There are plenty of reasons to return from a catch block. If you handle the exception instead of rethrowing it or another exception, then you'll need a return somehow, either there or after the catch block. What you should never do is "return" in a finally block, because that will mask any exception in flight about to be thrown to the caller.Perhaps masijade's use of never is too strong, but I too prefer/tend to avoid using return anywhere in try/catch/finally to avoid potential gotchas. Consider:
    public class TryCatchFinally
      public Data process(String s)
        Data returnData = new Data();
        try
          returnData.value = Integer.parseInt(s);
          returnData.message = "Success";
          return returnData;
        catch (Exception ex)
          returnData.value = -1;
          returnData.message = "Fail";
          return returnData;
        finally
          returnData.value = 42;
          returnData.message = "?";
      public static void main(String[] args)
        TryCatchFinally demo = new TryCatchFinally();
        Data d = demo.process("2");
        System.out.println(d.message + ": " + d.value);
        d = demo.process("2.1");
        System.out.println(d.message + ": " + d.value);
      class Data
        int value = 0;
        String message = "";
    }

  • Return statement

    How do I combine two Variables in a return statement?
    public static int bewege(int x,int y,int u,int v)
    Y=y+u;
    X=x+v;
    return X,Y; <<<<<I know,that doesn�t work!
    }

    I try to combine the two variables in the return statement like
    Now,I have tried the following.
    I have marked the position of my problem:
    public class Punkt
    private static int X,Y,P;
    private static int u,v,p,ps;
    public Punkt()
    public int x()
    return this.X;
    public int y()
    return this.Y;
    class PunktBewege
    {   int x=0;
    int y=0;
    public static PunktBewege bewege(int x,int y,int u,int v)
    Y=y+u;
    X=x+v; //<<<<<<<<<<
    return new PunktBewege(X,Y); //<<<<<<<<<<<<
    public static int spiegle(int x,int y)
    X=-x;Y=-y;
    return X; //<<<<<<<<it should return x AND y
    public static int verschiebeX(int ux,int x)
    X=x+ux;
    return X;
    public static int verschiebeY(int vy,int y)
    Y=y+vy;
    return Y;
    public static void main(String[]args)
    Punkt p=new Punkt();
    PunktBewege q =bewege(x,y,u,v);
    System.out.println(q.bewege(2,2,3,3));
    p.spiegle(2,3);
    System.out.println(p.spiegle(2,3));
    p.verschiebeX(2,2);
    System.out.println(p.verschiebeX(2,2));
    p.verschiebeY(3,3);
    System.out.println(verschiebeY(3,3));
    //public class Rechteck extends Punkt
    //}

  • Return statement error and java.lang.noclassDefFoundError?

    public class Calculation
         public static void main (String[] args)
              int a[]=new int [12];
              int iNum=0;
              MainPrompt();
         static public int MyInput()
         return MyInput.readInt();
         public static boolean MainPrompt()
              System.out.println("\n This program will show you the times table [1-12] of any number between 1 & 100 inclusive.");
              int a[]=new int [12];
              int iNum = 0;
              do
                   do
                        System.out.print("\n Enter your number [1-100] or 999 to exit: ");
                        iNum = MyInput();
                        while ((iNum>=1)&&(iNum<=100));
                             if (iNum==999)
                                  System.out.println("\n Goodbye \n");
                        while (!(((iNum>=1)&&(iNum<=100))||(iNum==999)));
                             if ((iNum>=1)&&(iNum<=100))
                                  Calculation(a,iNum);
                                  TimesTable(a,iNum);
         public static void Calculation(int a[], int iNum)
              for(int j=0;j<a.length;j++)
              a[j]=iNum*(j+1);
         public static void TimesTable(int a[], int iNum)
              for(int i=0;i<a.length;i++)
              System.out.println((i+1)+"     *"+iNum+"     ="+a);
    In build output it says missing return statement line 42 "}"
    and also when I try to execute the program it gives me the Exception in thread "main" java.lang.NoClassDefFoundError: calculation
    In the folder I have placed the myinput.java and myinput.class file where my calculation.java is, but still no go.
    can anyone here help me out here?
    thanks in advance

    public class Calculation
         public static void main (String[] args)
              int a[]=new int [12];
              int iNum=0;
              MainPrompt();
         static public int MyInput()
         return MyInput.readInt();
         public static void MainPrompt()
              System.out.println("\n This program will show you the times table [1-12] of any number between 1 & 100 inclusive.");
              int a[]=new int [12];
              int iNum = 0;
              do
                   do
                        System.out.print("\n Enter your number [1-100] or 999 to exit: ");
                        iNum = MyInput();
                        while ((iNum>=1)&&(iNum<=100));
                             if (iNum==999)
                                  System.out.println("\n Goodbye \n");
                        while (!(((iNum>=1)&&(iNum<=100))||(iNum==999)));
                             if ((iNum>=1)&&(iNum<=100))
                                  Calculation(a,iNum);
                                  TimesTable(a,iNum);
         public static void Calculation(int a[], int iNum) //This part doesn't execute
              for(int j=0;j<a.length;j++)
              a[j]=iNum*(j+1);
         public static void TimesTable(int a[], int iNum)
              for(int i=0;i<a.length;i++)
              System.out.println((i+1)+"     *"+iNum+"     ="+a);

Maybe you are looking for

  • Satellite A205-S5804/PSAF3U-0NR00V

    toshiba my laptop won't boot on windows,but the the power indicator was on. so what i did was i long press the power button to turn it off, then then i press it again still it doesn't work...i tried it a couple of times...luckily it works! but it hap

  • Error from F.5G

    Hello, I am going to run F.5G. While I am going to run this Tcode, I am getting error- The error is *Transactn KDF:  No valuation acct has been specified for acct 1120300800* Please tell me the Required Correction. Thanks

  • E-Mail Generating from database error ORA-06502: PL/SQL:

    Hello, I have write script for generating HTML formated email from database (11g). when text body increase 4000 char it generating error ORA-06502: PL/SQL: numeric or value error: character string buffer too small ORA-06512: at "EXPORT.REALIZATIONHTM

  • How do you batch edit still photos with panning/zooming effect in FCP X?

    Hi, I was making a slideshow with a lot of photos.  I had to manually add two keyframes in each photo (one in the beginning and one at the end), and then manually adjusted the scale/position for each photo so they pan/zoom during the slideshow. Is it

  • Can't see other person in video chat

    Hi Folks This one is perplexing: I have been video chatting with my mother in the UK for 1 yr without a hitch. Since I upgraded to 10.4.7 the video chats are only one way. She can see me, but I cannot see her. She was on 10.4.6 and it didn't work so